blob: 5213f3aaed5167802b58f21c81954891b7e58608 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000021#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000024#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000025#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000026#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/InlineAsm.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000039#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000040#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000041#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000042#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000043#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000044#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000045#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000046#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000049#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Transforms/Utils/BasicBlockUtils.h"
51#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000052#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000054#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000055using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000056using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000057
Chandler Carruth1b9dde02014-04-22 02:02:50 +000058#define DEBUG_TYPE "codegenprepare"
59
Cameron Zwarichced753f2011-01-05 17:27:27 +000060STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000061STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
62STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000063STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
64 "sunken Cmps");
65STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
66 "of sunken Casts");
67STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
68 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000069STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
70STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000071STATISTIC(NumAndsAdded,
72 "Number of and mask instructions added to form ext loads");
73STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000074STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000075STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000076STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000077STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000078STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000079
Cameron Zwarich338d3622011-03-11 21:52:04 +000080static cl::opt<bool> DisableBranchOpts(
81 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
82 cl::desc("Disable branch optimizations in CodeGenPrepare"));
83
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000084static cl::opt<bool>
85 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
86 cl::desc("Disable GC optimizations in CodeGenPrepare"));
87
Benjamin Kramer3d38c172012-05-06 14:25:16 +000088static cl::opt<bool> DisableSelectToBranch(
89 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
90 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000091
Hal Finkelc3998302014-04-12 00:59:48 +000092static cl::opt<bool> AddrSinkUsingGEPs(
93 "addr-sink-using-gep", cl::Hidden, cl::init(false),
94 cl::desc("Address sinking in CGP using GEPs."));
95
Tim Northovercea0abb2014-03-29 08:22:29 +000096static cl::opt<bool> EnableAndCmpSinking(
97 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
98 cl::desc("Enable sinkinig and/cmp into branches."));
99
Quentin Colombetc32615d2014-10-31 17:52:53 +0000100static cl::opt<bool> DisableStoreExtract(
101 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
102 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
103
104static cl::opt<bool> StressStoreExtract(
105 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
106 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
107
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000108static cl::opt<bool> DisableExtLdPromotion(
109 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
110 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
111 "CodeGenPrepare"));
112
113static cl::opt<bool> StressExtLdPromotion(
114 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
115 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
116 "optimization in CodeGenPrepare"));
117
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000118static cl::opt<bool> DisablePreheaderProtect(
119 "disable-preheader-prot", cl::Hidden, cl::init(false),
120 cl::desc("Disable protection against removing loop preheaders"));
121
Eric Christopherc1ea1492008-09-24 05:32:41 +0000122namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000123typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000124typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000125typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000126class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000127
Chris Lattner2dd09db2009-09-02 06:11:42 +0000128 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000129 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000130 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000131 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000132 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000133 const LoopInfo *LI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000134
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000135 /// As we scan instructions optimizing them, this is the next instruction
136 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000137 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000138
Evan Cheng0663f232011-03-21 01:19:09 +0000139 /// Keeps track of non-local addresses that have been sunk into a block.
140 /// This allows us to avoid inserting duplicate code for blocks with
141 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000142 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000143
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000144 /// Keeps track of all instructions inserted for the current function.
145 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000146 /// Keeps track of the type of the related instruction before their
147 /// promotion for the current function.
148 InstrToOrigTy PromotedInsts;
149
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000150 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000151 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000152
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000153 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000154 bool OptSize;
155
Mehdi Amini4fe37982015-07-07 18:45:17 +0000156 /// DataLayout for the Function being processed.
157 const DataLayout *DL;
158
Chris Lattnerf2836d12007-03-31 04:06:36 +0000159 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000160 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000161 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000162 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000163 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
164 }
Craig Topper4584cd52014-03-07 09:26:03 +0000165 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000166
Craig Topper4584cd52014-03-07 09:26:03 +0000167 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000168
Craig Topper4584cd52014-03-07 09:26:03 +0000169 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000170 // FIXME: When we can selectively preserve passes, preserve the domtree.
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000171 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000172 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000173 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000174 }
175
Chris Lattnerf2836d12007-03-31 04:06:36 +0000176 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000177 bool eliminateFallThrough(Function &F);
178 bool eliminateMostlyEmptyBlocks(Function &F);
179 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
180 void eliminateMostlyEmptyBlock(BasicBlock *BB);
181 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
182 bool optimizeInst(Instruction *I, bool& ModifiedDT);
183 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000184 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000185 bool optimizeInlineAsmInst(CallInst *CS);
186 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
187 bool moveExtToFormExtLoad(Instruction *&I);
188 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000189 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000190 bool optimizeSelectInst(SelectInst *SI);
191 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000192 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000193 bool optimizeExtractElementInst(Instruction *Inst);
194 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
195 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000196 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000197 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000198 Instruction *&Inst,
199 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000200 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000201 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000202 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000203 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000204 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000205}
Devang Patel09f162c2007-05-01 21:15:47 +0000206
Devang Patel8c78a0b2007-05-03 01:11:54 +0000207char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000208INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
209 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000210
Bill Wendling7a639ea2013-06-19 21:07:11 +0000211FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
212 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000213}
214
Chris Lattnerf2836d12007-03-31 04:06:36 +0000215bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000216 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000217 return false;
218
Mehdi Amini4fe37982015-07-07 18:45:17 +0000219 DL = &F.getParent()->getDataLayout();
220
Chris Lattnerf2836d12007-03-31 04:06:36 +0000221 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000222 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000223 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000224 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000225
Devang Patel8f606d72011-03-24 15:35:25 +0000226 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000227 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000228 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000229 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000230 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000231 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000232 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000233
Preston Gurdcdf540d2012-09-04 18:22:17 +0000234 /// This optimization identifies DIV instructions that can be
235 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000236 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000237 const DenseMap<unsigned int, unsigned int> &BypassWidths =
238 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000239 BasicBlock* BB = &*F.begin();
240 while (BB != nullptr) {
241 // bypassSlowDivision may create new BBs, but we don't want to reapply the
242 // optimization to those blocks.
243 BasicBlock* Next = BB->getNextNode();
244 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
245 BB = Next;
246 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000247 }
248
249 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000250 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000251 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000252
Devang Patel53771ba2011-08-18 00:50:51 +0000253 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000254 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000255 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000256 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000257
Tim Northovercea0abb2014-03-29 08:22:29 +0000258 // If there is a mask, compare against zero, and branch that can be combined
259 // into a single target instruction, push the mask and compare into branch
260 // users. Do this before OptimizeBlock -> OptimizeInst ->
261 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000262 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000263 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000264 EverMadeChange |= splitBranchCondition(F);
265 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000266
Chris Lattnerc3748562007-04-02 01:35:34 +0000267 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268 while (MadeChange) {
269 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000270 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000271 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000272 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000273 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000274
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000275 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000276 if (ModifiedDTOnIteration)
277 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000278 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000279 EverMadeChange |= MadeChange;
280 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000281
282 SunkAddrs.clear();
283
Cameron Zwarich338d3622011-03-11 21:52:04 +0000284 if (!DisableBranchOpts) {
285 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000286 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000287 for (BasicBlock &BB : F) {
288 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
289 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000290 if (!MadeChange) continue;
291
292 for (SmallVectorImpl<BasicBlock*>::iterator
293 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
294 if (pred_begin(*II) == pred_end(*II))
295 WorkList.insert(*II);
296 }
297
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000298 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000299 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000300 while (!WorkList.empty()) {
301 BasicBlock *BB = *WorkList.begin();
302 WorkList.erase(BB);
303 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
304
305 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000306
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000307 for (SmallVectorImpl<BasicBlock*>::iterator
308 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
309 if (pred_begin(*II) == pred_end(*II))
310 WorkList.insert(*II);
311 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000312
Nadav Rotem70409992012-08-14 05:19:07 +0000313 // Merge pairs of basic blocks with unconditional branches, connected by
314 // a single edge.
315 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000316 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000317
Cameron Zwarich338d3622011-03-11 21:52:04 +0000318 EverMadeChange |= MadeChange;
319 }
320
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000321 if (!DisableGCOpts) {
322 SmallVector<Instruction *, 2> Statepoints;
323 for (BasicBlock &BB : F)
324 for (Instruction &I : BB)
325 if (isStatepoint(I))
326 Statepoints.push_back(&I);
327 for (auto &I : Statepoints)
328 EverMadeChange |= simplifyOffsetableRelocate(*I);
329 }
330
Chris Lattnerf2836d12007-03-31 04:06:36 +0000331 return EverMadeChange;
332}
333
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000334/// Merge basic blocks which are connected by a single edge, where one of the
335/// basic blocks has a single successor pointing to the other basic block,
336/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000337bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000338 bool Changed = false;
339 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000340 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000341 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000342 // If the destination block has a single pred, then this is a trivial
343 // edge, just collapse it.
344 BasicBlock *SinglePred = BB->getSinglePredecessor();
345
Evan Cheng64a223a2012-09-28 23:58:57 +0000346 // Don't merge if BB's address is taken.
347 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000348
349 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
350 if (Term && !Term->isConditional()) {
351 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000352 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000353 // Remember if SinglePred was the entry block of the function.
354 // If so, we will need to move BB back to the entry position.
355 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000356 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000357
358 if (isEntry && BB != &BB->getParent()->getEntryBlock())
359 BB->moveBefore(&BB->getParent()->getEntryBlock());
360
361 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000362 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000363 }
364 }
365 return Changed;
366}
367
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000368/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
369/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
370/// edges in ways that are non-optimal for isel. Start by eliminating these
371/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000372bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000373 SmallPtrSet<BasicBlock *, 16> Preheaders;
374 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
375 while (!LoopList.empty()) {
376 Loop *L = LoopList.pop_back_val();
377 LoopList.insert(LoopList.end(), L->begin(), L->end());
378 if (BasicBlock *Preheader = L->getLoopPreheader())
379 Preheaders.insert(Preheader);
380 }
381
Chris Lattnerc3748562007-04-02 01:35:34 +0000382 bool MadeChange = false;
383 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000384 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000385 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000386
387 // If this block doesn't end with an uncond branch, ignore it.
388 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
389 if (!BI || !BI->isUnconditional())
390 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000391
Dale Johannesen4026b042009-03-27 01:13:37 +0000392 // If the instruction before the branch (skipping debug info) isn't a phi
393 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000394 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000395 if (BBI != BB->begin()) {
396 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000397 while (isa<DbgInfoIntrinsic>(BBI)) {
398 if (BBI == BB->begin())
399 break;
400 --BBI;
401 }
402 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
403 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000404 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000405
Chris Lattnerc3748562007-04-02 01:35:34 +0000406 // Do not break infinite loops.
407 BasicBlock *DestBB = BI->getSuccessor(0);
408 if (DestBB == BB)
409 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000410
Sanjay Patelfc580a62015-09-21 23:03:16 +0000411 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000412 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000413
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000414 // Do not delete loop preheaders if doing so would create a critical edge.
415 // Loop preheaders can be good locations to spill registers. If the
416 // preheader is deleted and we create a critical edge, registers may be
417 // spilled in the loop body instead.
418 if (!DisablePreheaderProtect && Preheaders.count(BB) &&
419 !(BB->getSinglePredecessor() && BB->getSinglePredecessor()->getSingleSuccessor()))
420 continue;
421
Sanjay Patelfc580a62015-09-21 23:03:16 +0000422 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000423 MadeChange = true;
424 }
425 return MadeChange;
426}
427
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000428/// Return true if we can merge BB into DestBB if there is a single
429/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000430/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000431bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000432 const BasicBlock *DestBB) const {
433 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
434 // the successor. If there are more complex condition (e.g. preheaders),
435 // don't mess around with them.
436 BasicBlock::const_iterator BBI = BB->begin();
437 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000438 for (const User *U : PN->users()) {
439 const Instruction *UI = cast<Instruction>(U);
440 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000441 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442 // If User is inside DestBB block and it is a PHINode then check
443 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000444 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000445 if (UI->getParent() == DestBB) {
446 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000447 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
448 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
449 if (Insn && Insn->getParent() == BB &&
450 Insn->getParent() != UPN->getIncomingBlock(I))
451 return false;
452 }
453 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000454 }
455 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000456
Chris Lattnerc3748562007-04-02 01:35:34 +0000457 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
458 // and DestBB may have conflicting incoming values for the block. If so, we
459 // can't merge the block.
460 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
461 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000462
Chris Lattnerc3748562007-04-02 01:35:34 +0000463 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000464 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000465 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
466 // It is faster to get preds from a PHI than with pred_iterator.
467 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
468 BBPreds.insert(BBPN->getIncomingBlock(i));
469 } else {
470 BBPreds.insert(pred_begin(BB), pred_end(BB));
471 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000472
Chris Lattnerc3748562007-04-02 01:35:34 +0000473 // Walk the preds of DestBB.
474 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
475 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
476 if (BBPreds.count(Pred)) { // Common predecessor?
477 BBI = DestBB->begin();
478 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
479 const Value *V1 = PN->getIncomingValueForBlock(Pred);
480 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000481
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 // If V2 is a phi node in BB, look up what the mapped value will be.
483 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
484 if (V2PN->getParent() == BB)
485 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000486
Chris Lattnerc3748562007-04-02 01:35:34 +0000487 // If there is a conflict, bail out.
488 if (V1 != V2) return false;
489 }
490 }
491 }
492
493 return true;
494}
495
496
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000497/// Eliminate a basic block that has only phi's and an unconditional branch in
498/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000499void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000500 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
501 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000502
David Greene74e2d492010-01-05 01:27:11 +0000503 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000504
Chris Lattnerc3748562007-04-02 01:35:34 +0000505 // If the destination block has a single pred, then this is a trivial edge,
506 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000507 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000508 if (SinglePred != DestBB) {
509 // Remember if SinglePred was the entry block of the function. If so, we
510 // will need to move BB back to the entry position.
511 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000512 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000513
Chris Lattner8a172da2008-11-28 19:54:49 +0000514 if (isEntry && BB != &BB->getParent()->getEntryBlock())
515 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000516
David Greene74e2d492010-01-05 01:27:11 +0000517 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000518 return;
519 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000520 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000521
Chris Lattnerc3748562007-04-02 01:35:34 +0000522 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
523 // to handle the new incoming edges it is about to have.
524 PHINode *PN;
525 for (BasicBlock::iterator BBI = DestBB->begin();
526 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
527 // Remove the incoming value for BB, and remember it.
528 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529
Chris Lattnerc3748562007-04-02 01:35:34 +0000530 // Two options: either the InVal is a phi node defined in BB or it is some
531 // value that dominates BB.
532 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
533 if (InValPhi && InValPhi->getParent() == BB) {
534 // Add all of the input values of the input PHI as inputs of this phi.
535 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
536 PN->addIncoming(InValPhi->getIncomingValue(i),
537 InValPhi->getIncomingBlock(i));
538 } else {
539 // Otherwise, add one instance of the dominating value for each edge that
540 // we will be adding.
541 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
542 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
543 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
544 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000545 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
546 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000547 }
548 }
549 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000550
Chris Lattnerc3748562007-04-02 01:35:34 +0000551 // The PHIs are now updated, change everything that refers to BB to use
552 // DestBB and remove BB.
553 BB->replaceAllUsesWith(DestBB);
554 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000555 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000556
David Greene74e2d492010-01-05 01:27:11 +0000557 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000558}
559
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000560// Computes a map of base pointer relocation instructions to corresponding
561// derived pointer relocation instructions given a vector of all relocate calls
562static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000563 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
564 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
565 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000566 // Collect information in two maps: one primarily for locating the base object
567 // while filling the second map; the second map is the final structure holding
568 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000569 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
570 for (auto *ThisRelocate : AllRelocateCalls) {
571 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
572 ThisRelocate->getDerivedPtrIndex());
573 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000574 }
575 for (auto &Item : RelocateIdxMap) {
576 std::pair<unsigned, unsigned> Key = Item.first;
577 if (Key.first == Key.second)
578 // Base relocation: nothing to insert
579 continue;
580
Manuel Jacob83eefa62016-01-05 04:03:00 +0000581 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000582 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000583
584 // We're iterating over RelocateIdxMap so we cannot modify it.
585 auto MaybeBase = RelocateIdxMap.find(BaseKey);
586 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000587 // TODO: We might want to insert a new base object relocate and gep off
588 // that, if there are enough derived object relocates.
589 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000590
591 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000592 }
593}
594
595// Accepts a GEP and extracts the operands into a vector provided they're all
596// small integer constants
597static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
598 SmallVectorImpl<Value *> &OffsetV) {
599 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
600 // Only accept small constant integer operands
601 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
602 if (!Op || Op->getZExtValue() > 20)
603 return false;
604 }
605
606 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
607 OffsetV.push_back(GEP->getOperand(i));
608 return true;
609}
610
611// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
612// replace, computes a replacement, and affects it.
613static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000614simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
615 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000616 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000617 for (GCRelocateInst *ToReplace : Targets) {
618 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000619 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000620 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000621 // A duplicate relocate call. TODO: coalesce duplicates.
622 continue;
623 }
624
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000625 if (RelocatedBase->getParent() != ToReplace->getParent()) {
626 // Base and derived relocates are in different basic blocks.
627 // In this case transform is only valid when base dominates derived
628 // relocate. However it would be too expensive to check dominance
629 // for each such relocate, so we skip the whole transformation.
630 continue;
631 }
632
Manuel Jacob83eefa62016-01-05 04:03:00 +0000633 Value *Base = ToReplace->getBasePtr();
634 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000635 if (!Derived || Derived->getPointerOperand() != Base)
636 continue;
637
638 SmallVector<Value *, 2> OffsetV;
639 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
640 continue;
641
642 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000643 assert(RelocatedBase->getNextNode() &&
644 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000645
646 // Insert after RelocatedBase
647 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000648 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000649
650 // If gc_relocate does not match the actual type, cast it to the right type.
651 // In theory, there must be a bitcast after gc_relocate if the type does not
652 // match, and we should reuse it to get the derived pointer. But it could be
653 // cases like this:
654 // bb1:
655 // ...
656 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
657 // br label %merge
658 //
659 // bb2:
660 // ...
661 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
662 // br label %merge
663 //
664 // merge:
665 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
666 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
667 //
668 // In this case, we can not find the bitcast any more. So we insert a new bitcast
669 // no matter there is already one or not. In this way, we can handle all cases, and
670 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000671 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000672 if (RelocatedBase->getType() != Base->getType()) {
673 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000674 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000675 }
David Blaikie68d535c2015-03-24 22:38:16 +0000676 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000677 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000678 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000679 // If the newly generated derived pointer's type does not match the original derived
680 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000681 Value *ActualReplacement = Replacement;
682 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000683 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000684 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000685 }
686 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000687 ToReplace->eraseFromParent();
688
689 MadeChange = true;
690 }
691 return MadeChange;
692}
693
694// Turns this:
695//
696// %base = ...
697// %ptr = gep %base + 15
698// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
699// %base' = relocate(%tok, i32 4, i32 4)
700// %ptr' = relocate(%tok, i32 4, i32 5)
701// %val = load %ptr'
702//
703// into this:
704//
705// %base = ...
706// %ptr = gep %base + 15
707// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
708// %base' = gc.relocate(%tok, i32 4, i32 4)
709// %ptr' = gep %base' + 15
710// %val = load %ptr'
711bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
712 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000713 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000714
715 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000716 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000717 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000718 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000719
720 // We need atleast one base pointer relocation + one derived pointer
721 // relocation to mangle
722 if (AllRelocateCalls.size() < 2)
723 return false;
724
725 // RelocateInstMap is a mapping from the base relocate instruction to the
726 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000727 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000728 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
729 if (RelocateInstMap.empty())
730 return false;
731
732 for (auto &Item : RelocateInstMap)
733 // Item.first is the RelocatedBase to offset against
734 // Item.second is the vector of Targets to replace
735 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
736 return MadeChange;
737}
738
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000739/// SinkCast - Sink the specified cast instruction into its user blocks
740static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000741 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000742
Chris Lattnerf2836d12007-03-31 04:06:36 +0000743 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000744 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000745
Chris Lattnerf2836d12007-03-31 04:06:36 +0000746 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000747 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000748 UI != E; ) {
749 Use &TheUse = UI.getUse();
750 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Chris Lattnerf2836d12007-03-31 04:06:36 +0000752 // Figure out which BB this cast is used in. For PHI's this is the
753 // appropriate predecessor block.
754 BasicBlock *UserBB = User->getParent();
755 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000756 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000757 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000758
Chris Lattnerf2836d12007-03-31 04:06:36 +0000759 // Preincrement use iterator so we don't invalidate it.
760 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000761
David Majnemer0c80e2e2016-04-27 19:36:38 +0000762 // The first insertion point of a block containing an EH pad is after the
763 // pad. If the pad is the user, we cannot sink the cast past the pad.
764 if (User->isEHPad())
765 continue;
766
Andrew Kaylord0430e82015-11-23 19:16:15 +0000767 // If the block selected to receive the cast is an EH pad that does not
768 // allow non-PHI instructions before the terminator, we can't sink the
769 // cast.
770 if (UserBB->getTerminator()->isEHPad())
771 continue;
772
Chris Lattnerf2836d12007-03-31 04:06:36 +0000773 // If this user is in the same block as the cast, don't change the cast.
774 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000775
Chris Lattnerf2836d12007-03-31 04:06:36 +0000776 // If we have already inserted a cast into this block, use it.
777 CastInst *&InsertedCast = InsertedCasts[UserBB];
778
779 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000780 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000781 assert(InsertPt != UserBB->end());
782 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
783 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000784 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000785
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000786 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000787 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000788 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000789 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000790 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000791
Chris Lattnerf2836d12007-03-31 04:06:36 +0000792 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000793 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000794 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000795 MadeChange = true;
796 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000797
Chris Lattnerf2836d12007-03-31 04:06:36 +0000798 return MadeChange;
799}
800
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000801/// If the specified cast instruction is a noop copy (e.g. it's casting from
802/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
803/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000804///
805/// Return true if any changes are made.
806///
Mehdi Amini44ede332015-07-09 02:09:04 +0000807static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
808 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000809 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000810 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
811 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000812
813 // This is an fp<->int conversion?
814 if (SrcVT.isInteger() != DstVT.isInteger())
815 return false;
816
817 // If this is an extension, it will be a zero or sign extension, which
818 // isn't a noop.
819 if (SrcVT.bitsLT(DstVT)) return false;
820
821 // If these values will be promoted, find out what they will be promoted
822 // to. This helps us consider truncates on PPC as noop copies when they
823 // are.
824 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
825 TargetLowering::TypePromoteInteger)
826 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
827 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
828 TargetLowering::TypePromoteInteger)
829 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
830
831 // If, after promotion, these are the same types, this is a noop copy.
832 if (SrcVT != DstVT)
833 return false;
834
835 return SinkCast(CI);
836}
837
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000838/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
839/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000840///
841/// Return true if any changes were made.
842static bool CombineUAddWithOverflow(CmpInst *CI) {
843 Value *A, *B;
844 Instruction *AddI;
845 if (!match(CI,
846 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
847 return false;
848
849 Type *Ty = AddI->getType();
850 if (!isa<IntegerType>(Ty))
851 return false;
852
853 // We don't want to move around uses of condition values this late, so we we
854 // check if it is legal to create the call to the intrinsic in the basic
855 // block containing the icmp:
856
857 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
858 return false;
859
860#ifndef NDEBUG
861 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
862 // for now:
863 if (AddI->hasOneUse())
864 assert(*AddI->user_begin() == CI && "expected!");
865#endif
866
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000867 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000868 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
869
870 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
871
872 auto *UAddWithOverflow =
873 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
874 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
875 auto *Overflow =
876 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
877
878 CI->replaceAllUsesWith(Overflow);
879 AddI->replaceAllUsesWith(UAdd);
880 CI->eraseFromParent();
881 AddI->eraseFromParent();
882 return true;
883}
884
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000885/// Sink the given CmpInst into user blocks to reduce the number of virtual
886/// registers that must be created and coalesced. This is a clear win except on
887/// targets with multiple condition code registers (PowerPC), where it might
888/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000889///
890/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000891static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000892 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000893
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000894 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000895 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000896 return false;
897
898 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000899 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000900
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000901 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000902 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000903 UI != E; ) {
904 Use &TheUse = UI.getUse();
905 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000906
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000907 // Preincrement use iterator so we don't invalidate it.
908 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000909
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000910 // Don't bother for PHI nodes.
911 if (isa<PHINode>(User))
912 continue;
913
914 // Figure out which BB this cmp is used in.
915 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000916
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000917 // If this user is in the same block as the cmp, don't change the cmp.
918 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000919
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000920 // If we have already inserted a cmp into this block, use it.
921 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
922
923 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000924 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000925 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000926 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000927 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
928 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000929 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000930
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000931 // Replace a use of the cmp with a use of the new cmp.
932 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000933 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000934 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000935 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000936
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000937 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000938 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000939 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000940 MadeChange = true;
941 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000942
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000943 return MadeChange;
944}
945
Peter Zotovf87e5502016-04-03 17:11:53 +0000946static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +0000947 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000948 return true;
949
950 if (CombineUAddWithOverflow(CI))
951 return true;
952
953 return false;
954}
955
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000956/// Check if the candidates could be combined with a shift instruction, which
957/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000958/// 1. Truncate instruction
959/// 2. And instruction and the imm is a mask of the low bits:
960/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000961static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000962 if (!isa<TruncInst>(User)) {
963 if (User->getOpcode() != Instruction::And ||
964 !isa<ConstantInt>(User->getOperand(1)))
965 return false;
966
Quentin Colombetd4f44692014-04-22 01:20:34 +0000967 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000968
Quentin Colombetd4f44692014-04-22 01:20:34 +0000969 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000970 return false;
971 }
972 return true;
973}
974
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000975/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000976static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000977SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
978 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000979 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000980 BasicBlock *UserBB = User->getParent();
981 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
982 TruncInst *TruncI = dyn_cast<TruncInst>(User);
983 bool MadeChange = false;
984
985 for (Value::user_iterator TruncUI = TruncI->user_begin(),
986 TruncE = TruncI->user_end();
987 TruncUI != TruncE;) {
988
989 Use &TruncTheUse = TruncUI.getUse();
990 Instruction *TruncUser = cast<Instruction>(*TruncUI);
991 // Preincrement use iterator so we don't invalidate it.
992
993 ++TruncUI;
994
995 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
996 if (!ISDOpcode)
997 continue;
998
Tim Northovere2239ff2014-07-29 10:20:22 +0000999 // If the use is actually a legal node, there will not be an
1000 // implicit truncate.
1001 // FIXME: always querying the result type is just an
1002 // approximation; some nodes' legality is determined by the
1003 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001004 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001005 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001006 continue;
1007
1008 // Don't bother for PHI nodes.
1009 if (isa<PHINode>(TruncUser))
1010 continue;
1011
1012 BasicBlock *TruncUserBB = TruncUser->getParent();
1013
1014 if (UserBB == TruncUserBB)
1015 continue;
1016
1017 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1018 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1019
1020 if (!InsertedShift && !InsertedTrunc) {
1021 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001022 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001023 // Sink the shift
1024 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001025 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1026 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001027 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001028 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1029 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001030
1031 // Sink the trunc
1032 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1033 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001034 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001035
1036 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001037 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001038
1039 MadeChange = true;
1040
1041 TruncTheUse = InsertedTrunc;
1042 }
1043 }
1044 return MadeChange;
1045}
1046
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001047/// Sink the shift *right* instruction into user blocks if the uses could
1048/// potentially be combined with this shift instruction and generate BitExtract
1049/// instruction. It will only be applied if the architecture supports BitExtract
1050/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001051/// BB1:
1052/// %x.extract.shift = lshr i64 %arg1, 32
1053/// BB2:
1054/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1055/// ==>
1056///
1057/// BB2:
1058/// %x.extract.shift.1 = lshr i64 %arg1, 32
1059/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1060///
1061/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1062/// instruction.
1063/// Return true if any changes are made.
1064static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001065 const TargetLowering &TLI,
1066 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001067 BasicBlock *DefBB = ShiftI->getParent();
1068
1069 /// Only insert instructions in each block once.
1070 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1071
Mehdi Amini44ede332015-07-09 02:09:04 +00001072 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001073
1074 bool MadeChange = false;
1075 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1076 UI != E;) {
1077 Use &TheUse = UI.getUse();
1078 Instruction *User = cast<Instruction>(*UI);
1079 // Preincrement use iterator so we don't invalidate it.
1080 ++UI;
1081
1082 // Don't bother for PHI nodes.
1083 if (isa<PHINode>(User))
1084 continue;
1085
1086 if (!isExtractBitsCandidateUse(User))
1087 continue;
1088
1089 BasicBlock *UserBB = User->getParent();
1090
1091 if (UserBB == DefBB) {
1092 // If the shift and truncate instruction are in the same BB. The use of
1093 // the truncate(TruncUse) may still introduce another truncate if not
1094 // legal. In this case, we would like to sink both shift and truncate
1095 // instruction to the BB of TruncUse.
1096 // for example:
1097 // BB1:
1098 // i64 shift.result = lshr i64 opnd, imm
1099 // trunc.result = trunc shift.result to i16
1100 //
1101 // BB2:
1102 // ----> We will have an implicit truncate here if the architecture does
1103 // not have i16 compare.
1104 // cmp i16 trunc.result, opnd2
1105 //
1106 if (isa<TruncInst>(User) && shiftIsLegal
1107 // If the type of the truncate is legal, no trucate will be
1108 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001109 &&
1110 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001111 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001112 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001113
1114 continue;
1115 }
1116 // If we have already inserted a shift into this block, use it.
1117 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1118
1119 if (!InsertedShift) {
1120 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001121 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001122
1123 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001124 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1125 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001126 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001127 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1128 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001129
1130 MadeChange = true;
1131 }
1132
1133 // Replace a use of the shift with a use of the new shift.
1134 TheUse = InsertedShift;
1135 }
1136
1137 // If we removed all uses, nuke the shift.
1138 if (ShiftI->use_empty())
1139 ShiftI->eraseFromParent();
1140
1141 return MadeChange;
1142}
1143
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001144// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001145// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1146// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001147// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001148// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001149//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001150// %1 = bitcast i8* %addr to i32*
1151// %2 = extractelement <16 x i1> %mask, i32 0
1152// %3 = icmp eq i1 %2, true
1153// br i1 %3, label %cond.load, label %else
1154//
1155//cond.load: ; preds = %0
1156// %4 = getelementptr i32* %1, i32 0
1157// %5 = load i32* %4
1158// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1159// br label %else
1160//
1161//else: ; preds = %0, %cond.load
1162// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1163// %7 = extractelement <16 x i1> %mask, i32 1
1164// %8 = icmp eq i1 %7, true
1165// br i1 %8, label %cond.load1, label %else2
1166//
1167//cond.load1: ; preds = %else
1168// %9 = getelementptr i32* %1, i32 1
1169// %10 = load i32* %9
1170// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1171// br label %else2
1172//
1173//else2: ; preds = %else, %cond.load1
1174// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1175// %12 = extractelement <16 x i1> %mask, i32 2
1176// %13 = icmp eq i1 %12, true
1177// br i1 %13, label %cond.load4, label %else5
1178//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001179static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001180 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001181 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001182 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001183 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001184
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001185 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1186 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001187 assert(VecType && "Unexpected return type of masked load intrinsic");
1188
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001189 Type *EltTy = CI->getType()->getVectorElementType();
1190
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001191 IRBuilder<> Builder(CI->getContext());
1192 Instruction *InsertPt = CI;
1193 BasicBlock *IfBlock = CI->getParent();
1194 BasicBlock *CondBlock = nullptr;
1195 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001196
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001197 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001198 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1199
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001200 // Short-cut if the mask is all-true.
1201 bool IsAllOnesMask = isa<Constant>(Mask) &&
1202 cast<Constant>(Mask)->isAllOnesValue();
1203
1204 if (IsAllOnesMask) {
1205 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1206 CI->replaceAllUsesWith(NewI);
1207 CI->eraseFromParent();
1208 return;
1209 }
1210
1211 // Adjust alignment for the scalar instruction.
1212 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001213 // Bitcast %addr fron i8* to EltTy*
1214 Type *NewPtrType =
1215 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1216 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001217 unsigned VectorWidth = VecType->getNumElements();
1218
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001219 Value *UndefVal = UndefValue::get(VecType);
1220
1221 // The result vector
1222 Value *VResult = UndefVal;
1223
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001224 if (isa<ConstantVector>(Mask)) {
1225 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1226 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1227 continue;
1228 Value *Gep =
1229 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1230 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1231 VResult = Builder.CreateInsertElement(VResult, Load,
1232 Builder.getInt32(Idx));
1233 }
1234 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1235 CI->replaceAllUsesWith(NewI);
1236 CI->eraseFromParent();
1237 return;
1238 }
1239
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001240 PHINode *Phi = nullptr;
1241 Value *PrevPhi = UndefVal;
1242
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001243 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1244
1245 // Fill the "else" block, created in the previous iteration
1246 //
1247 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1248 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1249 // %to_load = icmp eq i1 %mask_1, true
1250 // br i1 %to_load, label %cond.load, label %else
1251 //
1252 if (Idx > 0) {
1253 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1254 Phi->addIncoming(VResult, CondBlock);
1255 Phi->addIncoming(PrevPhi, PrevIfBlock);
1256 PrevPhi = Phi;
1257 VResult = Phi;
1258 }
1259
1260 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1261 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1262 ConstantInt::get(Predicate->getType(), 1));
1263
1264 // Create "cond" block
1265 //
1266 // %EltAddr = getelementptr i32* %1, i32 0
1267 // %Elt = load i32* %EltAddr
1268 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1269 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001270 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001271 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001272
1273 Value *Gep =
1274 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001275 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001276 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1277
1278 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001279 BasicBlock *NewIfBlock =
1280 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001281 Builder.SetInsertPoint(InsertPt);
1282 Instruction *OldBr = IfBlock->getTerminator();
1283 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1284 OldBr->eraseFromParent();
1285 PrevIfBlock = IfBlock;
1286 IfBlock = NewIfBlock;
1287 }
1288
1289 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1290 Phi->addIncoming(VResult, CondBlock);
1291 Phi->addIncoming(PrevPhi, PrevIfBlock);
1292 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1293 CI->replaceAllUsesWith(NewI);
1294 CI->eraseFromParent();
1295}
1296
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001297// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001298// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1299// <16 x i1> %mask)
1300// to a chain of basic blocks, that stores element one-by-one if
1301// the appropriate mask bit is set
1302//
1303// %1 = bitcast i8* %addr to i32*
1304// %2 = extractelement <16 x i1> %mask, i32 0
1305// %3 = icmp eq i1 %2, true
1306// br i1 %3, label %cond.store, label %else
1307//
1308// cond.store: ; preds = %0
1309// %4 = extractelement <16 x i32> %val, i32 0
1310// %5 = getelementptr i32* %1, i32 0
1311// store i32 %4, i32* %5
1312// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001313//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001314// else: ; preds = %0, %cond.store
1315// %6 = extractelement <16 x i1> %mask, i32 1
1316// %7 = icmp eq i1 %6, true
1317// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001318//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001319// cond.store1: ; preds = %else
1320// %8 = extractelement <16 x i32> %val, i32 1
1321// %9 = getelementptr i32* %1, i32 1
1322// store i32 %8, i32* %9
1323// br label %else2
1324// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001325static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001326 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001327 Value *Ptr = CI->getArgOperand(1);
1328 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001329 Value *Mask = CI->getArgOperand(3);
1330
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001331 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001332 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001333 assert(VecType && "Unexpected data type in masked store intrinsic");
1334
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001335 Type *EltTy = VecType->getElementType();
1336
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001337 IRBuilder<> Builder(CI->getContext());
1338 Instruction *InsertPt = CI;
1339 BasicBlock *IfBlock = CI->getParent();
1340 Builder.SetInsertPoint(InsertPt);
1341 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1342
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001343 // Short-cut if the mask is all-true.
1344 bool IsAllOnesMask = isa<Constant>(Mask) &&
1345 cast<Constant>(Mask)->isAllOnesValue();
1346
1347 if (IsAllOnesMask) {
1348 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1349 CI->eraseFromParent();
1350 return;
1351 }
1352
1353 // Adjust alignment for the scalar instruction.
1354 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001355 // Bitcast %addr fron i8* to EltTy*
1356 Type *NewPtrType =
1357 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1358 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001359 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001360
1361 if (isa<ConstantVector>(Mask)) {
1362 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1363 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1364 continue;
1365 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1366 Value *Gep =
1367 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1368 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1369 }
1370 CI->eraseFromParent();
1371 return;
1372 }
1373
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001374 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1375
1376 // Fill the "else" block, created in the previous iteration
1377 //
1378 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1379 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001380 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001381 //
1382 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1383 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1384 ConstantInt::get(Predicate->getType(), 1));
1385
1386 // Create "cond" block
1387 //
1388 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1389 // %EltAddr = getelementptr i32* %1, i32 0
1390 // %store i32 %OneElt, i32* %EltAddr
1391 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001392 BasicBlock *CondBlock =
1393 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001394 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001395
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001396 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001397 Value *Gep =
1398 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001399 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001400
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 IfBlock = NewIfBlock;
1409 }
1410 CI->eraseFromParent();
1411}
1412
Elena Demikhovsky09285852015-10-25 15:37:55 +00001413// Translate a masked gather intrinsic like
1414// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1415// <16 x i1> %Mask, <16 x i32> %Src)
1416// to a chain of basic blocks, with loading element one-by-one if
1417// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001418//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001419// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1420// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1421// % ToLoad0 = icmp eq i1 % Mask0, true
1422// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001423//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001424// cond.load:
1425// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1426// % Load0 = load i32, i32* % Ptr0, align 4
1427// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1428// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001429//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001430// else:
1431// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1432// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1433// % ToLoad1 = icmp eq i1 % Mask1, true
1434// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001435//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001436// cond.load1:
1437// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1438// % Load1 = load i32, i32* % Ptr1, align 4
1439// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1440// br label %else2
1441// . . .
1442// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1443// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001444static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001445 Value *Ptrs = CI->getArgOperand(0);
1446 Value *Alignment = CI->getArgOperand(1);
1447 Value *Mask = CI->getArgOperand(2);
1448 Value *Src0 = CI->getArgOperand(3);
1449
1450 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1451
1452 assert(VecType && "Unexpected return type of masked load intrinsic");
1453
1454 IRBuilder<> Builder(CI->getContext());
1455 Instruction *InsertPt = CI;
1456 BasicBlock *IfBlock = CI->getParent();
1457 BasicBlock *CondBlock = nullptr;
1458 BasicBlock *PrevIfBlock = CI->getParent();
1459 Builder.SetInsertPoint(InsertPt);
1460 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1461
1462 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1463
1464 Value *UndefVal = UndefValue::get(VecType);
1465
1466 // The result vector
1467 Value *VResult = UndefVal;
1468 unsigned VectorWidth = VecType->getNumElements();
1469
1470 // Shorten the way if the mask is a vector of constants.
1471 bool IsConstMask = isa<ConstantVector>(Mask);
1472
1473 if (IsConstMask) {
1474 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1475 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1476 continue;
1477 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1478 "Ptr" + Twine(Idx));
1479 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1480 "Load" + Twine(Idx));
1481 VResult = Builder.CreateInsertElement(VResult, Load,
1482 Builder.getInt32(Idx),
1483 "Res" + Twine(Idx));
1484 }
1485 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1486 CI->replaceAllUsesWith(NewI);
1487 CI->eraseFromParent();
1488 return;
1489 }
1490
1491 PHINode *Phi = nullptr;
1492 Value *PrevPhi = UndefVal;
1493
1494 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1495
1496 // Fill the "else" block, created in the previous iteration
1497 //
1498 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1499 // %ToLoad1 = icmp eq i1 %Mask1, true
1500 // br i1 %ToLoad1, label %cond.load, label %else
1501 //
1502 if (Idx > 0) {
1503 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1504 Phi->addIncoming(VResult, CondBlock);
1505 Phi->addIncoming(PrevPhi, PrevIfBlock);
1506 PrevPhi = Phi;
1507 VResult = Phi;
1508 }
1509
1510 Value *Predicate = Builder.CreateExtractElement(Mask,
1511 Builder.getInt32(Idx),
1512 "Mask" + Twine(Idx));
1513 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1514 ConstantInt::get(Predicate->getType(), 1),
1515 "ToLoad" + Twine(Idx));
1516
1517 // Create "cond" block
1518 //
1519 // %EltAddr = getelementptr i32* %1, i32 0
1520 // %Elt = load i32* %EltAddr
1521 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1522 //
1523 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1524 Builder.SetInsertPoint(InsertPt);
1525
1526 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1527 "Ptr" + Twine(Idx));
1528 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1529 "Load" + Twine(Idx));
1530 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1531 "Res" + Twine(Idx));
1532
1533 // Create "else" block, fill it in the next iteration
1534 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1535 Builder.SetInsertPoint(InsertPt);
1536 Instruction *OldBr = IfBlock->getTerminator();
1537 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1538 OldBr->eraseFromParent();
1539 PrevIfBlock = IfBlock;
1540 IfBlock = NewIfBlock;
1541 }
1542
1543 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1544 Phi->addIncoming(VResult, CondBlock);
1545 Phi->addIncoming(PrevPhi, PrevIfBlock);
1546 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1547 CI->replaceAllUsesWith(NewI);
1548 CI->eraseFromParent();
1549}
1550
1551// Translate a masked scatter intrinsic, like
1552// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1553// <16 x i1> %Mask)
1554// to a chain of basic blocks, that stores element one-by-one if
1555// the appropriate mask bit is set.
1556//
1557// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1558// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1559// % ToStore0 = icmp eq i1 % Mask0, true
1560// br i1 %ToStore0, label %cond.store, label %else
1561//
1562// cond.store:
1563// % Elt0 = extractelement <16 x i32> %Src, i32 0
1564// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1565// store i32 %Elt0, i32* % Ptr0, align 4
1566// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001567//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001568// else:
1569// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1570// % ToStore1 = icmp eq i1 % Mask1, true
1571// br i1 % ToStore1, label %cond.store1, label %else2
1572//
1573// cond.store1:
1574// % Elt1 = extractelement <16 x i32> %Src, i32 1
1575// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1576// store i32 % Elt1, i32* % Ptr1, align 4
1577// br label %else2
1578// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001579static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001580 Value *Src = CI->getArgOperand(0);
1581 Value *Ptrs = CI->getArgOperand(1);
1582 Value *Alignment = CI->getArgOperand(2);
1583 Value *Mask = CI->getArgOperand(3);
1584
1585 assert(isa<VectorType>(Src->getType()) &&
1586 "Unexpected data type in masked scatter intrinsic");
1587 assert(isa<VectorType>(Ptrs->getType()) &&
1588 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1589 "Vector of pointers is expected in masked scatter intrinsic");
1590
1591 IRBuilder<> Builder(CI->getContext());
1592 Instruction *InsertPt = CI;
1593 BasicBlock *IfBlock = CI->getParent();
1594 Builder.SetInsertPoint(InsertPt);
1595 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1596
1597 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1598 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1599
1600 // Shorten the way if the mask is a vector of constants.
1601 bool IsConstMask = isa<ConstantVector>(Mask);
1602
1603 if (IsConstMask) {
1604 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1605 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1606 continue;
1607 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1608 "Elt" + Twine(Idx));
1609 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1610 "Ptr" + Twine(Idx));
1611 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1612 }
1613 CI->eraseFromParent();
1614 return;
1615 }
1616 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1617 // Fill the "else" block, created in the previous iteration
1618 //
1619 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1620 // % ToStore = icmp eq i1 % Mask1, true
1621 // br i1 % ToStore, label %cond.store, label %else
1622 //
1623 Value *Predicate = Builder.CreateExtractElement(Mask,
1624 Builder.getInt32(Idx),
1625 "Mask" + Twine(Idx));
1626 Value *Cmp =
1627 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1628 ConstantInt::get(Predicate->getType(), 1),
1629 "ToStore" + Twine(Idx));
1630
1631 // Create "cond" block
1632 //
1633 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1634 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1635 // %store i32 % Elt1, i32* % Ptr1
1636 //
1637 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1638 Builder.SetInsertPoint(InsertPt);
1639
1640 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1641 "Elt" + Twine(Idx));
1642 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1643 "Ptr" + Twine(Idx));
1644 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1645
1646 // Create "else" block, fill it in the next iteration
1647 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1648 Builder.SetInsertPoint(InsertPt);
1649 Instruction *OldBr = IfBlock->getTerminator();
1650 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1651 OldBr->eraseFromParent();
1652 IfBlock = NewIfBlock;
1653 }
1654 CI->eraseFromParent();
1655}
1656
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001657/// If counting leading or trailing zeros is an expensive operation and a zero
1658/// input is defined, add a check for zero to avoid calling the intrinsic.
1659///
1660/// We want to transform:
1661/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1662///
1663/// into:
1664/// entry:
1665/// %cmpz = icmp eq i64 %A, 0
1666/// br i1 %cmpz, label %cond.end, label %cond.false
1667/// cond.false:
1668/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1669/// br label %cond.end
1670/// cond.end:
1671/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1672///
1673/// If the transform is performed, return true and set ModifiedDT to true.
1674static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1675 const TargetLowering *TLI,
1676 const DataLayout *DL,
1677 bool &ModifiedDT) {
1678 if (!TLI || !DL)
1679 return false;
1680
1681 // If a zero input is undefined, it doesn't make sense to despeculate that.
1682 if (match(CountZeros->getOperand(1), m_One()))
1683 return false;
1684
1685 // If it's cheap to speculate, there's nothing to do.
1686 auto IntrinsicID = CountZeros->getIntrinsicID();
1687 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1688 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1689 return false;
1690
1691 // Only handle legal scalar cases. Anything else requires too much work.
1692 Type *Ty = CountZeros->getType();
1693 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001694 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001695 return false;
1696
1697 // The intrinsic will be sunk behind a compare against zero and branch.
1698 BasicBlock *StartBlock = CountZeros->getParent();
1699 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1700
1701 // Create another block after the count zero intrinsic. A PHI will be added
1702 // in this block to select the result of the intrinsic or the bit-width
1703 // constant if the input to the intrinsic is zero.
1704 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1705 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1706
1707 // Set up a builder to create a compare, conditional branch, and PHI.
1708 IRBuilder<> Builder(CountZeros->getContext());
1709 Builder.SetInsertPoint(StartBlock->getTerminator());
1710 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1711
1712 // Replace the unconditional branch that was created by the first split with
1713 // a compare against zero and a conditional branch.
1714 Value *Zero = Constant::getNullValue(Ty);
1715 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1716 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1717 StartBlock->getTerminator()->eraseFromParent();
1718
1719 // Create a PHI in the end block to select either the output of the intrinsic
1720 // or the bit width of the operand.
1721 Builder.SetInsertPoint(&EndBlock->front());
1722 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1723 CountZeros->replaceAllUsesWith(PN);
1724 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1725 PN->addIncoming(BitWidth, StartBlock);
1726 PN->addIncoming(CountZeros, CallBlock);
1727
1728 // We are explicitly handling the zero case, so we can set the intrinsic's
1729 // undefined zero argument to 'true'. This will also prevent reprocessing the
1730 // intrinsic; we only despeculate when a zero input is defined.
1731 CountZeros->setArgOperand(1, Builder.getTrue());
1732 ModifiedDT = true;
1733 return true;
1734}
1735
Sanjay Patelfc580a62015-09-21 23:03:16 +00001736bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001737 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001738
Chris Lattner7a277142011-01-15 07:14:54 +00001739 // Lower inline assembly if we can.
1740 // If we found an inline asm expession, and if the target knows how to
1741 // lower it to normal LLVM code, do so now.
1742 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1743 if (TLI->ExpandInlineAsm(CI)) {
1744 // Avoid invalidating the iterator.
1745 CurInstIterator = BB->begin();
1746 // Avoid processing instructions out of order, which could cause
1747 // reuse before a value is defined.
1748 SunkAddrs.clear();
1749 return true;
1750 }
1751 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001752 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001753 return true;
1754 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001755
John Brawn0dbcd652015-03-18 12:01:59 +00001756 // Align the pointer arguments to this call if the target thinks it's a good
1757 // idea
1758 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001759 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001760 for (auto &Arg : CI->arg_operands()) {
1761 // We want to align both objects whose address is used directly and
1762 // objects whose address is used in casts and GEPs, though it only makes
1763 // sense for GEPs if the offset is a multiple of the desired alignment and
1764 // if size - offset meets the size threshold.
1765 if (!Arg->getType()->isPointerTy())
1766 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001767 APInt Offset(DL->getPointerSizeInBits(
1768 cast<PointerType>(Arg->getType())->getAddressSpace()),
1769 0);
1770 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001771 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001772 if ((Offset2 & (PrefAlign-1)) != 0)
1773 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001774 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001775 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1776 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001777 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001778 // Global variables can only be aligned if they are defined in this
1779 // object (i.e. they are uniquely initialized in this object), and
1780 // over-aligning global variables that have an explicit section is
1781 // forbidden.
1782 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001783 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001784 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001785 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001786 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001787 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001788 }
1789 // If this is a memcpy (or similar) then we may be able to improve the
1790 // alignment
1791 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001792 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001793 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001794 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001795 if (Align > MI->getAlignment())
1796 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001797 }
1798 }
1799
Philip Reamesac115ed2016-03-09 23:13:12 +00001800 // If we have a cold call site, try to sink addressing computation into the
1801 // cold block. This interacts with our handling for loads and stores to
1802 // ensure that we can fold all uses of a potential addressing computation
1803 // into their uses. TODO: generalize this to work over profiling data
1804 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1805 for (auto &Arg : CI->arg_operands()) {
1806 if (!Arg->getType()->isPointerTy())
1807 continue;
1808 unsigned AS = Arg->getType()->getPointerAddressSpace();
1809 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1810 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001811
Eric Christopher4b7948e2010-03-11 02:41:03 +00001812 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001813 if (II) {
1814 switch (II->getIntrinsicID()) {
1815 default: break;
1816 case Intrinsic::objectsize: {
1817 // Lower all uses of llvm.objectsize.*
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001818 uint64_t Size;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001819 Type *ReturnTy = CI->getType();
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001820 Constant *RetVal = nullptr;
1821 ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
1822 ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
1823 if (getObjectSize(II->getArgOperand(0),
1824 Size, *DL, TLInfo, false, Mode)) {
1825 RetVal = ConstantInt::get(ReturnTy, Size);
1826 } else {
1827 RetVal = ConstantInt::get(ReturnTy,
1828 Mode == ObjSizeMode::Min ? 0 : -1ULL);
1829 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001830 // Substituting this can cause recursive simplifications, which can
1831 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1832 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001833 Value *CurValue = &*CurInstIterator;
1834 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001835
Sanjay Patel545a4562016-01-20 18:59:16 +00001836 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001837
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001838 // If the iterator instruction was recursively deleted, start over at the
1839 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001840 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001841 CurInstIterator = BB->begin();
1842 SunkAddrs.clear();
1843 }
1844 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001845 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001846 case Intrinsic::masked_load: {
1847 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001848 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001849 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001850 ModifiedDT = true;
1851 return true;
1852 }
1853 return false;
1854 }
1855 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001856 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001857 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001858 ModifiedDT = true;
1859 return true;
1860 }
1861 return false;
1862 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001863 case Intrinsic::masked_gather: {
1864 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001865 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001866 ModifiedDT = true;
1867 return true;
1868 }
1869 return false;
1870 }
1871 case Intrinsic::masked_scatter: {
1872 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001873 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001874 ModifiedDT = true;
1875 return true;
1876 }
1877 return false;
1878 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001879 case Intrinsic::aarch64_stlxr:
1880 case Intrinsic::aarch64_stxr: {
1881 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1882 if (!ExtVal || !ExtVal->hasOneUse() ||
1883 ExtVal->getParent() == CI->getParent())
1884 return false;
1885 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1886 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001887 // Mark this instruction as "inserted by CGP", so that other
1888 // optimizations don't touch it.
1889 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001890 return true;
1891 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001892 case Intrinsic::invariant_group_barrier:
1893 II->replaceAllUsesWith(II->getArgOperand(0));
1894 II->eraseFromParent();
1895 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001896
1897 case Intrinsic::cttz:
1898 case Intrinsic::ctlz:
1899 // If counting zeros is expensive, try to avoid it.
1900 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001901 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001902
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001903 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001904 // Unknown address space.
1905 // TODO: Target hook to pick which address space the intrinsic cares
1906 // about?
1907 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001908 SmallVector<Value*, 2> PtrOps;
1909 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001910 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001911 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001912 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001913 return true;
1914 }
Pete Cooper615fd892012-03-13 20:59:56 +00001915 }
1916
Eric Christopher4b7948e2010-03-11 02:41:03 +00001917 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001918 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001919
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001920 // Lower all default uses of _chk calls. This is very similar
1921 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001922 // to fortified library functions (e.g. __memcpy_chk) that have the default
1923 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001924 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001925 if (Value *V = Simplifier.optimizeCall(CI)) {
1926 CI->replaceAllUsesWith(V);
1927 CI->eraseFromParent();
1928 return true;
1929 }
1930 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001931}
Chris Lattner1b93be52011-01-15 07:25:29 +00001932
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001933/// Look for opportunities to duplicate return instructions to the predecessor
1934/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001935/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001936/// bb0:
1937/// %tmp0 = tail call i32 @f0()
1938/// br label %return
1939/// bb1:
1940/// %tmp1 = tail call i32 @f1()
1941/// br label %return
1942/// bb2:
1943/// %tmp2 = tail call i32 @f2()
1944/// br label %return
1945/// return:
1946/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1947/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001948/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001949///
1950/// =>
1951///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001952/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001953/// bb0:
1954/// %tmp0 = tail call i32 @f0()
1955/// ret i32 %tmp0
1956/// bb1:
1957/// %tmp1 = tail call i32 @f1()
1958/// ret i32 %tmp1
1959/// bb2:
1960/// %tmp2 = tail call i32 @f2()
1961/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001962/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001963bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001964 if (!TLI)
1965 return false;
1966
Michael Kuperstein71321562016-09-07 20:29:49 +00001967 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1968 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001969 return false;
1970
Craig Topperc0196b12014-04-14 00:51:57 +00001971 PHINode *PN = nullptr;
1972 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001973 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001974 if (V) {
1975 BCI = dyn_cast<BitCastInst>(V);
1976 if (BCI)
1977 V = BCI->getOperand(0);
1978
1979 PN = dyn_cast<PHINode>(V);
1980 if (!PN)
1981 return false;
1982 }
Evan Cheng0663f232011-03-21 01:19:09 +00001983
Cameron Zwarich4649f172011-03-24 04:52:10 +00001984 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001985 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001986
Cameron Zwarich4649f172011-03-24 04:52:10 +00001987 // Make sure there are no instructions between the PHI and return, or that the
1988 // return is the first instruction in the block.
1989 if (PN) {
1990 BasicBlock::iterator BI = BB->begin();
1991 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001992 if (&*BI == BCI)
1993 // Also skip over the bitcast.
1994 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001995 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001996 return false;
1997 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001998 BasicBlock::iterator BI = BB->begin();
1999 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002000 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002001 return false;
2002 }
Evan Cheng0663f232011-03-21 01:19:09 +00002003
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002004 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2005 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002006 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002007 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002008 if (PN) {
2009 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2010 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2011 // Make sure the phi value is indeed produced by the tail call.
2012 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002013 TLI->mayBeEmittedAsTailCall(CI) &&
2014 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002015 TailCalls.push_back(CI);
2016 }
2017 } else {
2018 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002019 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002020 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002021 continue;
2022
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002023 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002024 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2025 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002026 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2027 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002028 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002029
Cameron Zwarich4649f172011-03-24 04:52:10 +00002030 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002031 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2032 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002033 TailCalls.push_back(CI);
2034 }
Evan Cheng0663f232011-03-21 01:19:09 +00002035 }
2036
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002037 bool Changed = false;
2038 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2039 CallInst *CI = TailCalls[i];
2040 CallSite CS(CI);
2041
2042 // Conservatively require the attributes of the call to match those of the
2043 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002044 AttributeSet CalleeAttrs = CS.getAttributes();
2045 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002046 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002047 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002048 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002049 continue;
2050
2051 // Make sure the call instruction is followed by an unconditional branch to
2052 // the return block.
2053 BasicBlock *CallBB = CI->getParent();
2054 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2055 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2056 continue;
2057
2058 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002059 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002060 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002061 ++NumRetsDup;
2062 }
2063
2064 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002065 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002066 BB->eraseFromParent();
2067
2068 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002069}
2070
Chris Lattner728f9022008-11-25 07:09:13 +00002071//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002072// Memory Optimization
2073//===----------------------------------------------------------------------===//
2074
Chandler Carruthc8925912013-01-05 02:09:22 +00002075namespace {
2076
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002077/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002078/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002079struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002080 Value *BaseReg;
2081 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002082 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002083 void print(raw_ostream &OS) const;
2084 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002085
Chandler Carruthc8925912013-01-05 02:09:22 +00002086 bool operator==(const ExtAddrMode& O) const {
2087 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2088 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2089 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2090 }
2091};
2092
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002093#ifndef NDEBUG
2094static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2095 AM.print(OS);
2096 return OS;
2097}
2098#endif
2099
Chandler Carruthc8925912013-01-05 02:09:22 +00002100void ExtAddrMode::print(raw_ostream &OS) const {
2101 bool NeedPlus = false;
2102 OS << "[";
2103 if (BaseGV) {
2104 OS << (NeedPlus ? " + " : "")
2105 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002106 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002107 NeedPlus = true;
2108 }
2109
Richard Trieuc0f91212014-05-30 03:15:17 +00002110 if (BaseOffs) {
2111 OS << (NeedPlus ? " + " : "")
2112 << BaseOffs;
2113 NeedPlus = true;
2114 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002115
2116 if (BaseReg) {
2117 OS << (NeedPlus ? " + " : "")
2118 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002119 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002120 NeedPlus = true;
2121 }
2122 if (Scale) {
2123 OS << (NeedPlus ? " + " : "")
2124 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002125 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002126 }
2127
2128 OS << ']';
2129}
2130
2131#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002132LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002133 print(dbgs());
2134 dbgs() << '\n';
2135}
2136#endif
2137
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002138/// \brief This class provides transaction based operation on the IR.
2139/// Every change made through this class is recorded in the internal state and
2140/// can be undone (rollback) until commit is called.
2141class TypePromotionTransaction {
2142
2143 /// \brief This represents the common interface of the individual transaction.
2144 /// Each class implements the logic for doing one specific modification on
2145 /// the IR via the TypePromotionTransaction.
2146 class TypePromotionAction {
2147 protected:
2148 /// The Instruction modified.
2149 Instruction *Inst;
2150
2151 public:
2152 /// \brief Constructor of the action.
2153 /// The constructor performs the related action on the IR.
2154 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2155
2156 virtual ~TypePromotionAction() {}
2157
2158 /// \brief Undo the modification done by this action.
2159 /// When this method is called, the IR must be in the same state as it was
2160 /// before this action was applied.
2161 /// \pre Undoing the action works if and only if the IR is in the exact same
2162 /// state as it was directly after this action was applied.
2163 virtual void undo() = 0;
2164
2165 /// \brief Advocate every change made by this action.
2166 /// When the results on the IR of the action are to be kept, it is important
2167 /// to call this function, otherwise hidden information may be kept forever.
2168 virtual void commit() {
2169 // Nothing to be done, this action is not doing anything.
2170 }
2171 };
2172
2173 /// \brief Utility to remember the position of an instruction.
2174 class InsertionHandler {
2175 /// Position of an instruction.
2176 /// Either an instruction:
2177 /// - Is the first in a basic block: BB is used.
2178 /// - Has a previous instructon: PrevInst is used.
2179 union {
2180 Instruction *PrevInst;
2181 BasicBlock *BB;
2182 } Point;
2183 /// Remember whether or not the instruction had a previous instruction.
2184 bool HasPrevInstruction;
2185
2186 public:
2187 /// \brief Record the position of \p Inst.
2188 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002189 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002190 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2191 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002192 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002193 else
2194 Point.BB = Inst->getParent();
2195 }
2196
2197 /// \brief Insert \p Inst at the recorded position.
2198 void insert(Instruction *Inst) {
2199 if (HasPrevInstruction) {
2200 if (Inst->getParent())
2201 Inst->removeFromParent();
2202 Inst->insertAfter(Point.PrevInst);
2203 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002204 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002205 if (Inst->getParent())
2206 Inst->moveBefore(Position);
2207 else
2208 Inst->insertBefore(Position);
2209 }
2210 }
2211 };
2212
2213 /// \brief Move an instruction before another.
2214 class InstructionMoveBefore : public TypePromotionAction {
2215 /// Original position of the instruction.
2216 InsertionHandler Position;
2217
2218 public:
2219 /// \brief Move \p Inst before \p Before.
2220 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2221 : TypePromotionAction(Inst), Position(Inst) {
2222 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2223 Inst->moveBefore(Before);
2224 }
2225
2226 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002227 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002228 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2229 Position.insert(Inst);
2230 }
2231 };
2232
2233 /// \brief Set the operand of an instruction with a new value.
2234 class OperandSetter : public TypePromotionAction {
2235 /// Original operand of the instruction.
2236 Value *Origin;
2237 /// Index of the modified instruction.
2238 unsigned Idx;
2239
2240 public:
2241 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2242 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2243 : TypePromotionAction(Inst), Idx(Idx) {
2244 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2245 << "for:" << *Inst << "\n"
2246 << "with:" << *NewVal << "\n");
2247 Origin = Inst->getOperand(Idx);
2248 Inst->setOperand(Idx, NewVal);
2249 }
2250
2251 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002252 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002253 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2254 << "for: " << *Inst << "\n"
2255 << "with: " << *Origin << "\n");
2256 Inst->setOperand(Idx, Origin);
2257 }
2258 };
2259
2260 /// \brief Hide the operands of an instruction.
2261 /// Do as if this instruction was not using any of its operands.
2262 class OperandsHider : public TypePromotionAction {
2263 /// The list of original operands.
2264 SmallVector<Value *, 4> OriginalValues;
2265
2266 public:
2267 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2268 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2269 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2270 unsigned NumOpnds = Inst->getNumOperands();
2271 OriginalValues.reserve(NumOpnds);
2272 for (unsigned It = 0; It < NumOpnds; ++It) {
2273 // Save the current operand.
2274 Value *Val = Inst->getOperand(It);
2275 OriginalValues.push_back(Val);
2276 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002277 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002278 // that we are not willing to pay.
2279 Inst->setOperand(It, UndefValue::get(Val->getType()));
2280 }
2281 }
2282
2283 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002284 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002285 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2286 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2287 Inst->setOperand(It, OriginalValues[It]);
2288 }
2289 };
2290
2291 /// \brief Build a truncate instruction.
2292 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002293 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002294 public:
2295 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2296 /// result.
2297 /// trunc Opnd to Ty.
2298 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2299 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002300 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2301 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002302 }
2303
Quentin Colombetac55b152014-09-16 22:36:07 +00002304 /// \brief Get the built value.
2305 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002306
2307 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002308 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002309 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2310 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2311 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 }
2313 };
2314
2315 /// \brief Build a sign extension instruction.
2316 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002317 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002318 public:
2319 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2320 /// result.
2321 /// sext Opnd to Ty.
2322 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002323 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002324 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002325 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2326 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002327 }
2328
Quentin Colombetac55b152014-09-16 22:36:07 +00002329 /// \brief Get the built value.
2330 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002331
2332 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002333 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002334 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2335 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2336 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002337 }
2338 };
2339
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002340 /// \brief Build a zero extension instruction.
2341 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002342 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002343 public:
2344 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2345 /// result.
2346 /// zext Opnd to Ty.
2347 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002348 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002349 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002350 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2351 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002352 }
2353
Quentin Colombetac55b152014-09-16 22:36:07 +00002354 /// \brief Get the built value.
2355 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002356
2357 /// \brief Remove the built instruction.
2358 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002359 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2360 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2361 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002362 }
2363 };
2364
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002365 /// \brief Mutate an instruction to another type.
2366 class TypeMutator : public TypePromotionAction {
2367 /// Record the original type.
2368 Type *OrigTy;
2369
2370 public:
2371 /// \brief Mutate the type of \p Inst into \p NewTy.
2372 TypeMutator(Instruction *Inst, Type *NewTy)
2373 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2374 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2375 << "\n");
2376 Inst->mutateType(NewTy);
2377 }
2378
2379 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002380 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002381 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2382 << "\n");
2383 Inst->mutateType(OrigTy);
2384 }
2385 };
2386
2387 /// \brief Replace the uses of an instruction by another instruction.
2388 class UsesReplacer : public TypePromotionAction {
2389 /// Helper structure to keep track of the replaced uses.
2390 struct InstructionAndIdx {
2391 /// The instruction using the instruction.
2392 Instruction *Inst;
2393 /// The index where this instruction is used for Inst.
2394 unsigned Idx;
2395 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2396 : Inst(Inst), Idx(Idx) {}
2397 };
2398
2399 /// Keep track of the original uses (pair Instruction, Index).
2400 SmallVector<InstructionAndIdx, 4> OriginalUses;
2401 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2402
2403 public:
2404 /// \brief Replace all the use of \p Inst by \p New.
2405 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2406 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2407 << "\n");
2408 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002409 for (Use &U : Inst->uses()) {
2410 Instruction *UserI = cast<Instruction>(U.getUser());
2411 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002412 }
2413 // Now, we can replace the uses.
2414 Inst->replaceAllUsesWith(New);
2415 }
2416
2417 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002418 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002419 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2420 for (use_iterator UseIt = OriginalUses.begin(),
2421 EndIt = OriginalUses.end();
2422 UseIt != EndIt; ++UseIt) {
2423 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2424 }
2425 }
2426 };
2427
2428 /// \brief Remove an instruction from the IR.
2429 class InstructionRemover : public TypePromotionAction {
2430 /// Original position of the instruction.
2431 InsertionHandler Inserter;
2432 /// Helper structure to hide all the link to the instruction. In other
2433 /// words, this helps to do as if the instruction was removed.
2434 OperandsHider Hider;
2435 /// Keep track of the uses replaced, if any.
2436 UsesReplacer *Replacer;
2437
2438 public:
2439 /// \brief Remove all reference of \p Inst and optinally replace all its
2440 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002441 /// \pre If !Inst->use_empty(), then New != nullptr
2442 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002444 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 if (New)
2446 Replacer = new UsesReplacer(Inst, New);
2447 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2448 Inst->removeFromParent();
2449 }
2450
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002451 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002452
2453 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002454 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455
2456 /// \brief Resurrect the instruction and reassign it to the proper uses if
2457 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002458 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2460 Inserter.insert(Inst);
2461 if (Replacer)
2462 Replacer->undo();
2463 Hider.undo();
2464 }
2465 };
2466
2467public:
2468 /// Restoration point.
2469 /// The restoration point is a pointer to an action instead of an iterator
2470 /// because the iterator may be invalidated but not the pointer.
2471 typedef const TypePromotionAction *ConstRestorationPt;
2472 /// Advocate every changes made in that transaction.
2473 void commit();
2474 /// Undo all the changes made after the given point.
2475 void rollback(ConstRestorationPt Point);
2476 /// Get the current restoration point.
2477 ConstRestorationPt getRestorationPoint() const;
2478
2479 /// \name API for IR modification with state keeping to support rollback.
2480 /// @{
2481 /// Same as Instruction::setOperand.
2482 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2483 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002484 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002485 /// Same as Value::replaceAllUsesWith.
2486 void replaceAllUsesWith(Instruction *Inst, Value *New);
2487 /// Same as Value::mutateType.
2488 void mutateType(Instruction *Inst, Type *NewTy);
2489 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002490 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002491 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002492 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002493 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002494 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002495 /// Same as Instruction::moveBefore.
2496 void moveBefore(Instruction *Inst, Instruction *Before);
2497 /// @}
2498
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002499private:
2500 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002501 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2502 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002503};
2504
2505void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2506 Value *NewVal) {
2507 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002508 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002509}
2510
2511void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2512 Value *NewVal) {
2513 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002514 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515}
2516
2517void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2518 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002519 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002520}
2521
2522void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002523 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524}
2525
Quentin Colombetac55b152014-09-16 22:36:07 +00002526Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2527 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002528 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002529 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002530 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002531 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002532}
2533
Quentin Colombetac55b152014-09-16 22:36:07 +00002534Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2535 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002536 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002537 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002538 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002539 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002540}
2541
Quentin Colombetac55b152014-09-16 22:36:07 +00002542Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2543 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002544 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002545 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002546 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002547 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002548}
2549
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002550void TypePromotionTransaction::moveBefore(Instruction *Inst,
2551 Instruction *Before) {
2552 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002553 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002554}
2555
2556TypePromotionTransaction::ConstRestorationPt
2557TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002558 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002559}
2560
2561void TypePromotionTransaction::commit() {
2562 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002563 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002565 Actions.clear();
2566}
2567
2568void TypePromotionTransaction::rollback(
2569 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002570 while (!Actions.empty() && Point != Actions.back().get()) {
2571 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002572 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002573 }
2574}
2575
Chandler Carruthc8925912013-01-05 02:09:22 +00002576/// \brief A helper class for matching addressing modes.
2577///
2578/// This encapsulates the logic for matching the target-legal addressing modes.
2579class AddressingModeMatcher {
2580 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002581 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002583 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002584
2585 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2586 /// the memory instruction that we're computing this address for.
2587 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002588 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002589 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002590
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002591 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002592 /// part of the return value of this addressing mode matching stuff.
2593 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002594
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002595 /// The instructions inserted by other CodeGenPrepare optimizations.
2596 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002597 /// A map from the instructions to their type before promotion.
2598 InstrToOrigTy &PromotedInsts;
2599 /// The ongoing transaction where every action should be registered.
2600 TypePromotionTransaction &TPT;
2601
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002602 /// This is set to true when we should not do profitability checks.
2603 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002604 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002605
Eric Christopherd75c00c2015-02-26 22:38:34 +00002606 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002607 const TargetMachine &TM, Type *AT, unsigned AS,
2608 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002609 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002610 InstrToOrigTy &PromotedInsts,
2611 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002612 : AddrModeInsts(AMI), TM(TM),
2613 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2614 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002615 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2616 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2617 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002618 IgnoreProfitability = false;
2619 }
2620public:
Stephen Lin837bba12013-07-15 17:55:02 +00002621
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002622 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002623 /// give an access type of AccessTy. This returns a list of involved
2624 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002625 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002626 /// optimizations.
2627 /// \p PromotedInsts maps the instructions to their type before promotion.
2628 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002629 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002630 Instruction *MemoryInst,
2631 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002632 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002633 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002634 InstrToOrigTy &PromotedInsts,
2635 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002636 ExtAddrMode Result;
2637
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002638 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002639 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002640 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002641 (void)Success; assert(Success && "Couldn't select *anything*?");
2642 return Result;
2643 }
2644private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002645 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2646 bool matchAddr(Value *V, unsigned Depth);
2647 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002648 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002649 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002650 ExtAddrMode &AMBefore,
2651 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002652 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2653 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002654 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002655};
2656
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002657/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002658/// Return true and update AddrMode if this addr mode is legal for the target,
2659/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002660bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002661 unsigned Depth) {
2662 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2663 // mode. Just process that directly.
2664 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002665 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002666
Chandler Carruthc8925912013-01-05 02:09:22 +00002667 // If the scale is 0, it takes nothing to add this.
2668 if (Scale == 0)
2669 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002670
Chandler Carruthc8925912013-01-05 02:09:22 +00002671 // If we already have a scale of this value, we can add to it, otherwise, we
2672 // need an available scale field.
2673 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2674 return false;
2675
2676 ExtAddrMode TestAddrMode = AddrMode;
2677
2678 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2679 // [A+B + A*7] -> [B+A*8].
2680 TestAddrMode.Scale += Scale;
2681 TestAddrMode.ScaledReg = ScaleReg;
2682
2683 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002684 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002685 return false;
2686
2687 // It was legal, so commit it.
2688 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002689
Chandler Carruthc8925912013-01-05 02:09:22 +00002690 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2691 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2692 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002693 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002694 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2695 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2696 TestAddrMode.ScaledReg = AddLHS;
2697 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002698
Chandler Carruthc8925912013-01-05 02:09:22 +00002699 // If this addressing mode is legal, commit it and remember that we folded
2700 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002701 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002702 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2703 AddrMode = TestAddrMode;
2704 return true;
2705 }
2706 }
2707
2708 // Otherwise, not (x+c)*scale, just return what we have.
2709 return true;
2710}
2711
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002712/// This is a little filter, which returns true if an addressing computation
2713/// involving I might be folded into a load/store accessing it.
2714/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002715/// the set of instructions that MatchOperationAddr can.
2716static bool MightBeFoldableInst(Instruction *I) {
2717 switch (I->getOpcode()) {
2718 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002719 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002720 // Don't touch identity bitcasts.
2721 if (I->getType() == I->getOperand(0)->getType())
2722 return false;
2723 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2724 case Instruction::PtrToInt:
2725 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2726 return true;
2727 case Instruction::IntToPtr:
2728 // We know the input is intptr_t, so this is foldable.
2729 return true;
2730 case Instruction::Add:
2731 return true;
2732 case Instruction::Mul:
2733 case Instruction::Shl:
2734 // Can only handle X*C and X << C.
2735 return isa<ConstantInt>(I->getOperand(1));
2736 case Instruction::GetElementPtr:
2737 return true;
2738 default:
2739 return false;
2740 }
2741}
2742
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002743/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2744/// \note \p Val is assumed to be the product of some type promotion.
2745/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2746/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002747static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2748 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002749 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2750 if (!PromotedInst)
2751 return false;
2752 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2753 // If the ISDOpcode is undefined, it was undefined before the promotion.
2754 if (!ISDOpcode)
2755 return true;
2756 // Otherwise, check if the promoted instruction is legal or not.
2757 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002758 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002759}
2760
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002761/// \brief Hepler class to perform type promotion.
2762class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002763 /// \brief Utility function to check whether or not a sign or zero extension
2764 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2765 /// either using the operands of \p Inst or promoting \p Inst.
2766 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002767 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002768 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002769 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002770 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002771 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002772 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002773 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002774 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2775 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002776
2777 /// \brief Utility function to determine if \p OpIdx should be promoted when
2778 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002779 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002780 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002781 }
2782
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002783 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002784 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002785 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002786 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002787 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002788 /// Newly added extensions are inserted in \p Exts.
2789 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002790 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002791 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002792 static Value *promoteOperandForTruncAndAnyExt(
2793 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002794 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002795 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002796 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002797
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002798 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002799 /// operand is promotable and is not a supported trunc or sext.
2800 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002801 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002802 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002803 /// Newly added extensions are inserted in \p Exts.
2804 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002805 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002806 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002807 static Value *promoteOperandForOther(Instruction *Ext,
2808 TypePromotionTransaction &TPT,
2809 InstrToOrigTy &PromotedInsts,
2810 unsigned &CreatedInstsCost,
2811 SmallVectorImpl<Instruction *> *Exts,
2812 SmallVectorImpl<Instruction *> *Truncs,
2813 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002814
2815 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002816 static Value *signExtendOperandForOther(
2817 Instruction *Ext, TypePromotionTransaction &TPT,
2818 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2819 SmallVectorImpl<Instruction *> *Exts,
2820 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2821 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2822 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002823 }
2824
2825 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002826 static Value *zeroExtendOperandForOther(
2827 Instruction *Ext, TypePromotionTransaction &TPT,
2828 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2829 SmallVectorImpl<Instruction *> *Exts,
2830 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2831 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2832 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002833 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002834
2835public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002836 /// Type for the utility function that promotes the operand of Ext.
2837 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002838 InstrToOrigTy &PromotedInsts,
2839 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002840 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002841 SmallVectorImpl<Instruction *> *Truncs,
2842 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002843 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2844 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002845 /// \return NULL if no promotable action is possible with the current
2846 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002847 /// \p InsertedInsts keeps track of all the instructions inserted by the
2848 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002849 /// because we do not want to promote these instructions as CodeGenPrepare
2850 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2851 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002852 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002853 const TargetLowering &TLI,
2854 const InstrToOrigTy &PromotedInsts);
2855};
2856
2857bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002858 Type *ConsideredExtType,
2859 const InstrToOrigTy &PromotedInsts,
2860 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002861 // The promotion helper does not know how to deal with vector types yet.
2862 // To be able to fix that, we would need to fix the places where we
2863 // statically extend, e.g., constants and such.
2864 if (Inst->getType()->isVectorTy())
2865 return false;
2866
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002867 // We can always get through zext.
2868 if (isa<ZExtInst>(Inst))
2869 return true;
2870
2871 // sext(sext) is ok too.
2872 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002873 return true;
2874
2875 // We can get through binary operator, if it is legal. In other words, the
2876 // binary operator must have a nuw or nsw flag.
2877 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2878 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002879 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2880 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002881 return true;
2882
2883 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002884 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002885 if (!isa<TruncInst>(Inst))
2886 return false;
2887
2888 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002889 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002890 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002891 if (!OpndVal->getType()->isIntegerTy() ||
2892 OpndVal->getType()->getIntegerBitWidth() >
2893 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002894 return false;
2895
2896 // If the operand of the truncate is not an instruction, we will not have
2897 // any information on the dropped bits.
2898 // (Actually we could for constant but it is not worth the extra logic).
2899 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2900 if (!Opnd)
2901 return false;
2902
2903 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002904 // I.e., check that trunc just drops extended bits of the same kind of
2905 // the extension.
2906 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002907 const Type *OpndType;
2908 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002909 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2910 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002911 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2912 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002913 else
2914 return false;
2915
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002916 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002917 return Inst->getType()->getIntegerBitWidth() >=
2918 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002919}
2920
2921TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002922 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002923 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002924 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2925 "Unexpected instruction type");
2926 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2927 Type *ExtTy = Ext->getType();
2928 bool IsSExt = isa<SExtInst>(Ext);
2929 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002930 // get through.
2931 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002932 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002933 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002934
2935 // Do not promote if the operand has been added by codegenprepare.
2936 // Otherwise, it means we are undoing an optimization that is likely to be
2937 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002938 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002939 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002940
2941 // SExt or Trunc instructions.
2942 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002943 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2944 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002945 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002946
2947 // Regular instruction.
2948 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002949 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002950 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002951 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002952}
2953
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002954Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002955 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002956 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002957 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002958 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002959 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2960 // get through it and this method should not be called.
2961 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002962 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002963 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002964 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002965 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002966 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002967 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002968 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002969 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2970 TPT.replaceAllUsesWith(SExt, ZExt);
2971 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002972 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002973 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002974 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2975 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002976 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2977 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002978 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002979
2980 // Remove dead code.
2981 if (SExtOpnd->use_empty())
2982 TPT.eraseInstruction(SExtOpnd);
2983
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002984 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002985 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002986 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002987 if (ExtInst) {
2988 if (Exts)
2989 Exts->push_back(ExtInst);
2990 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2991 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002992 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002993 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002994
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002995 // At this point we have: ext ty opnd to ty.
2996 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2997 Value *NextVal = ExtInst->getOperand(0);
2998 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002999 return NextVal;
3000}
3001
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003002Value *TypePromotionHelper::promoteOperandForOther(
3003 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003004 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003005 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003006 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3007 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003008 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003009 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003010 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003011 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003012 if (!ExtOpnd->hasOneUse()) {
3013 // ExtOpnd will be promoted.
3014 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003015 // promoted version.
3016 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003017 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003018 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3019 ITrunc->removeFromParent();
3020 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003021 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003022 if (Truncs)
3023 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003024 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003025
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003026 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003027 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003028 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003029 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003030 }
3031
3032 // Get through the Instruction:
3033 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003034 // 2. Replace the uses of Ext by Inst.
3035 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036
3037 // Remember the original type of the instruction before promotion.
3038 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003039 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3040 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003041 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003042 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003043 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003044 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003045 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003046 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003047
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003048 DEBUG(dbgs() << "Propagate Ext to operands\n");
3049 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003050 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003051 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3052 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3053 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003054 DEBUG(dbgs() << "No need to propagate\n");
3055 continue;
3056 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003057 // Check if we can statically extend the operand.
3058 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003059 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003060 DEBUG(dbgs() << "Statically extend\n");
3061 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3062 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3063 : Cst->getValue().zext(BitWidth);
3064 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003065 continue;
3066 }
3067 // UndefValue are typed, so we have to statically sign extend them.
3068 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003069 DEBUG(dbgs() << "Statically extend\n");
3070 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003071 continue;
3072 }
3073
3074 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003075 // Check if Ext was reused to extend an operand.
3076 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003077 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003078 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003079 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3080 : TPT.createZExt(Ext, Opnd, Ext->getType());
3081 if (!isa<Instruction>(ValForExtOpnd)) {
3082 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3083 continue;
3084 }
3085 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003086 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003087 if (Exts)
3088 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003089 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003090
3091 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003092 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3093 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003094 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003095 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003096 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003097 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003098 if (ExtForOpnd == Ext) {
3099 DEBUG(dbgs() << "Extension is useless now\n");
3100 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003101 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003102 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003103}
3104
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003105/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003106/// \p NewCost gives the cost of extension instructions created by the
3107/// promotion.
3108/// \p OldCost gives the cost of extension instructions before the promotion
3109/// plus the number of instructions that have been
3110/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003111/// \p PromotedOperand is the value that has been promoted.
3112/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003113bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003114 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3115 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3116 // The cost of the new extensions is greater than the cost of the
3117 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003118 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003119 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003120 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003121 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003122 return true;
3123 // The promotion is neutral but it may help folding the sign extension in
3124 // loads for instance.
3125 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003126 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003127}
3128
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003129/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003130/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003131/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003132/// If \p MovedAway is not NULL, it contains the information of whether or
3133/// not AddrInst has to be folded into the addressing mode on success.
3134/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3135/// because it has been moved away.
3136/// Thus AddrInst must not be added in the matched instructions.
3137/// This state can happen when AddrInst is a sext, since it may be moved away.
3138/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3139/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003140bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003141 unsigned Depth,
3142 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003143 // Avoid exponential behavior on extremely deep expression trees.
3144 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003145
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003146 // By default, all matched instructions stay in place.
3147 if (MovedAway)
3148 *MovedAway = false;
3149
Chandler Carruthc8925912013-01-05 02:09:22 +00003150 switch (Opcode) {
3151 case Instruction::PtrToInt:
3152 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003153 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003154 case Instruction::IntToPtr: {
3155 auto AS = AddrInst->getType()->getPointerAddressSpace();
3156 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003157 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003158 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003159 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003160 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003161 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003162 case Instruction::BitCast:
3163 // BitCast is always a noop, and we can handle it as long as it is
3164 // int->int or pointer->pointer (we don't want int<->fp or something).
3165 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3166 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3167 // Don't touch identity bitcasts. These were probably put here by LSR,
3168 // and we don't want to mess around with them. Assume it knows what it
3169 // is doing.
3170 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003171 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003172 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003173 case Instruction::AddrSpaceCast: {
3174 unsigned SrcAS
3175 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3176 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3177 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003178 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003179 return false;
3180 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003181 case Instruction::Add: {
3182 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3183 ExtAddrMode BackupAddrMode = AddrMode;
3184 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003185 // Start a transaction at this point.
3186 // The LHS may match but not the RHS.
3187 // Therefore, we need a higher level restoration point to undo partially
3188 // matched operation.
3189 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3190 TPT.getRestorationPoint();
3191
Sanjay Patelfc580a62015-09-21 23:03:16 +00003192 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3193 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003194 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003195
Chandler Carruthc8925912013-01-05 02:09:22 +00003196 // Restore the old addr mode info.
3197 AddrMode = BackupAddrMode;
3198 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003199 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003200
Chandler Carruthc8925912013-01-05 02:09:22 +00003201 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003202 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3203 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003204 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003205
Chandler Carruthc8925912013-01-05 02:09:22 +00003206 // Otherwise we definitely can't merge the ADD in.
3207 AddrMode = BackupAddrMode;
3208 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003209 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003210 break;
3211 }
3212 //case Instruction::Or:
3213 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3214 //break;
3215 case Instruction::Mul:
3216 case Instruction::Shl: {
3217 // Can only handle X*C and X << C.
3218 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003219 if (!RHS)
3220 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003221 int64_t Scale = RHS->getSExtValue();
3222 if (Opcode == Instruction::Shl)
3223 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003224
Sanjay Patelfc580a62015-09-21 23:03:16 +00003225 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003226 }
3227 case Instruction::GetElementPtr: {
3228 // Scan the GEP. We check it if it contains constant offsets and at most
3229 // one variable offset.
3230 int VariableOperand = -1;
3231 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003232
Chandler Carruthc8925912013-01-05 02:09:22 +00003233 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003234 gep_type_iterator GTI = gep_type_begin(AddrInst);
3235 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3236 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003237 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003238 unsigned Idx =
3239 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3240 ConstantOffset += SL->getElementOffset(Idx);
3241 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003242 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003243 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3244 ConstantOffset += CI->getSExtValue()*TypeSize;
3245 } else if (TypeSize) { // Scales of zero don't do anything.
3246 // We only allow one variable index at the moment.
3247 if (VariableOperand != -1)
3248 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003249
Chandler Carruthc8925912013-01-05 02:09:22 +00003250 // Remember the variable index.
3251 VariableOperand = i;
3252 VariableScale = TypeSize;
3253 }
3254 }
3255 }
Stephen Lin837bba12013-07-15 17:55:02 +00003256
Chandler Carruthc8925912013-01-05 02:09:22 +00003257 // A common case is for the GEP to only do a constant offset. In this case,
3258 // just add it to the disp field and check validity.
3259 if (VariableOperand == -1) {
3260 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003261 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003262 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003263 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003264 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003265 return true;
3266 }
3267 AddrMode.BaseOffs -= ConstantOffset;
3268 return false;
3269 }
3270
3271 // Save the valid addressing mode in case we can't match.
3272 ExtAddrMode BackupAddrMode = AddrMode;
3273 unsigned OldSize = AddrModeInsts.size();
3274
3275 // See if the scale and offset amount is valid for this target.
3276 AddrMode.BaseOffs += ConstantOffset;
3277
3278 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003279 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003280 // If it couldn't be matched, just stuff the value in a register.
3281 if (AddrMode.HasBaseReg) {
3282 AddrMode = BackupAddrMode;
3283 AddrModeInsts.resize(OldSize);
3284 return false;
3285 }
3286 AddrMode.HasBaseReg = true;
3287 AddrMode.BaseReg = AddrInst->getOperand(0);
3288 }
3289
3290 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003291 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003292 Depth)) {
3293 // If it couldn't be matched, try stuffing the base into a register
3294 // instead of matching it, and retrying the match of the scale.
3295 AddrMode = BackupAddrMode;
3296 AddrModeInsts.resize(OldSize);
3297 if (AddrMode.HasBaseReg)
3298 return false;
3299 AddrMode.HasBaseReg = true;
3300 AddrMode.BaseReg = AddrInst->getOperand(0);
3301 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003302 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003303 VariableScale, Depth)) {
3304 // If even that didn't work, bail.
3305 AddrMode = BackupAddrMode;
3306 AddrModeInsts.resize(OldSize);
3307 return false;
3308 }
3309 }
3310
3311 return true;
3312 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003313 case Instruction::SExt:
3314 case Instruction::ZExt: {
3315 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3316 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003317 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003318
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003319 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003320 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003321 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003322 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003323 if (!TPH)
3324 return false;
3325
3326 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3327 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003328 unsigned CreatedInstsCost = 0;
3329 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003330 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003331 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003332 // SExt has been moved away.
3333 // Thus either it will be rematched later in the recursive calls or it is
3334 // gone. Anyway, we must not fold it into the addressing mode at this point.
3335 // E.g.,
3336 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003337 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003338 // addr = gep base, idx
3339 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003340 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003341 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3342 // addr = gep base, op <- match
3343 if (MovedAway)
3344 *MovedAway = true;
3345
3346 assert(PromotedOperand &&
3347 "TypePromotionHelper should have filtered out those cases");
3348
3349 ExtAddrMode BackupAddrMode = AddrMode;
3350 unsigned OldSize = AddrModeInsts.size();
3351
Sanjay Patelfc580a62015-09-21 23:03:16 +00003352 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003353 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003354 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003355 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003356 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003357 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003358 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003359 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003360 AddrMode = BackupAddrMode;
3361 AddrModeInsts.resize(OldSize);
3362 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3363 TPT.rollback(LastKnownGood);
3364 return false;
3365 }
3366 return true;
3367 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003368 }
3369 return false;
3370}
3371
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003372/// If we can, try to add the value of 'Addr' into the current addressing mode.
3373/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3374/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3375/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003376///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003377bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003378 // Start a transaction at this point that we will rollback if the matching
3379 // fails.
3380 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3381 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003382 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3383 // Fold in immediates if legal for the target.
3384 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003385 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003386 return true;
3387 AddrMode.BaseOffs -= CI->getSExtValue();
3388 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3389 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003390 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003391 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003392 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003393 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003394 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003395 }
3396 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3397 ExtAddrMode BackupAddrMode = AddrMode;
3398 unsigned OldSize = AddrModeInsts.size();
3399
3400 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003401 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003402 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003403 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003404 // to check here.
3405 if (MovedAway)
3406 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003407 // Okay, it's possible to fold this. Check to see if it is actually
3408 // *profitable* to do so. We use a simple cost model to avoid increasing
3409 // register pressure too much.
3410 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003411 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003412 AddrModeInsts.push_back(I);
3413 return true;
3414 }
Stephen Lin837bba12013-07-15 17:55:02 +00003415
Chandler Carruthc8925912013-01-05 02:09:22 +00003416 // It isn't profitable to do this, roll back.
3417 //cerr << "NOT FOLDING: " << *I;
3418 AddrMode = BackupAddrMode;
3419 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003420 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003421 }
3422 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003423 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003424 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003425 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003426 } else if (isa<ConstantPointerNull>(Addr)) {
3427 // Null pointer gets folded without affecting the addressing mode.
3428 return true;
3429 }
3430
3431 // Worse case, the target should support [reg] addressing modes. :)
3432 if (!AddrMode.HasBaseReg) {
3433 AddrMode.HasBaseReg = true;
3434 AddrMode.BaseReg = Addr;
3435 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003436 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003437 return true;
3438 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003439 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003440 }
3441
3442 // If the base register is already taken, see if we can do [r+r].
3443 if (AddrMode.Scale == 0) {
3444 AddrMode.Scale = 1;
3445 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003446 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003447 return true;
3448 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003449 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003450 }
3451 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003452 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003453 return false;
3454}
3455
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003456/// Check to see if all uses of OpVal by the specified inline asm call are due
3457/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003458static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003459 const TargetMachine &TM) {
3460 const Function *F = CI->getParent()->getParent();
3461 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3462 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003463 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003464 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3465 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003466 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3467 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003468
Chandler Carruthc8925912013-01-05 02:09:22 +00003469 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003470 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003471
3472 // If this asm operand is our Value*, and if it isn't an indirect memory
3473 // operand, we can't fold it!
3474 if (OpInfo.CallOperandVal == OpVal &&
3475 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3476 !OpInfo.isIndirect))
3477 return false;
3478 }
3479
3480 return true;
3481}
3482
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003483/// Recursively walk all the uses of I until we find a memory use.
3484/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003485/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003486static bool FindAllMemoryUses(
3487 Instruction *I,
3488 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3489 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003490 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003491 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003492 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003493
Chandler Carruthc8925912013-01-05 02:09:22 +00003494 // If this is an obviously unfoldable instruction, bail out.
3495 if (!MightBeFoldableInst(I))
3496 return true;
3497
Philip Reamesac115ed2016-03-09 23:13:12 +00003498 const bool OptSize = I->getFunction()->optForSize();
3499
Chandler Carruthc8925912013-01-05 02:09:22 +00003500 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003501 for (Use &U : I->uses()) {
3502 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003503
Chandler Carruthcdf47882014-03-09 03:16:01 +00003504 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3505 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003506 continue;
3507 }
Stephen Lin837bba12013-07-15 17:55:02 +00003508
Chandler Carruthcdf47882014-03-09 03:16:01 +00003509 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3510 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003511 if (opNo == 0) return true; // Storing addr, not into addr.
3512 MemoryUses.push_back(std::make_pair(SI, opNo));
3513 continue;
3514 }
Stephen Lin837bba12013-07-15 17:55:02 +00003515
Chandler Carruthcdf47882014-03-09 03:16:01 +00003516 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003517 // If this is a cold call, we can sink the addressing calculation into
3518 // the cold path. See optimizeCallInst
3519 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3520 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003521
Chandler Carruthc8925912013-01-05 02:09:22 +00003522 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3523 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003524
Chandler Carruthc8925912013-01-05 02:09:22 +00003525 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003526 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003527 return true;
3528 continue;
3529 }
Stephen Lin837bba12013-07-15 17:55:02 +00003530
Eric Christopher11e4df72015-02-26 22:38:43 +00003531 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003532 return true;
3533 }
3534
3535 return false;
3536}
3537
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003538/// Return true if Val is already known to be live at the use site that we're
3539/// folding it into. If so, there is no cost to include it in the addressing
3540/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3541/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003542bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003543 Value *KnownLive2) {
3544 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003545 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003546 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003547
Chandler Carruthc8925912013-01-05 02:09:22 +00003548 // All values other than instructions and arguments (e.g. constants) are live.
3549 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003550
Chandler Carruthc8925912013-01-05 02:09:22 +00003551 // If Val is a constant sized alloca in the entry block, it is live, this is
3552 // true because it is just a reference to the stack/frame pointer, which is
3553 // live for the whole function.
3554 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3555 if (AI->isStaticAlloca())
3556 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003557
Chandler Carruthc8925912013-01-05 02:09:22 +00003558 // Check to see if this value is already used in the memory instruction's
3559 // block. If so, it's already live into the block at the very least, so we
3560 // can reasonably fold it.
3561 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3562}
3563
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003564/// It is possible for the addressing mode of the machine to fold the specified
3565/// instruction into a load or store that ultimately uses it.
3566/// However, the specified instruction has multiple uses.
3567/// Given this, it may actually increase register pressure to fold it
3568/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003569///
3570/// X = ...
3571/// Y = X+1
3572/// use(Y) -> nonload/store
3573/// Z = Y+1
3574/// load Z
3575///
3576/// In this case, Y has multiple uses, and can be folded into the load of Z
3577/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3578/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3579/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3580/// number of computations either.
3581///
3582/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3583/// X was live across 'load Z' for other reasons, we actually *would* want to
3584/// fold the addressing mode in the Z case. This would make Y die earlier.
3585bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003586isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003587 ExtAddrMode &AMAfter) {
3588 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003589
Chandler Carruthc8925912013-01-05 02:09:22 +00003590 // AMBefore is the addressing mode before this instruction was folded into it,
3591 // and AMAfter is the addressing mode after the instruction was folded. Get
3592 // the set of registers referenced by AMAfter and subtract out those
3593 // referenced by AMBefore: this is the set of values which folding in this
3594 // address extends the lifetime of.
3595 //
3596 // Note that there are only two potential values being referenced here,
3597 // BaseReg and ScaleReg (global addresses are always available, as are any
3598 // folded immediates).
3599 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003600
Chandler Carruthc8925912013-01-05 02:09:22 +00003601 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3602 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003603 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003604 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003605 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003606 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003607
3608 // If folding this instruction (and it's subexprs) didn't extend any live
3609 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003610 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003611 return true;
3612
Philip Reamesac115ed2016-03-09 23:13:12 +00003613 // If all uses of this instruction can have the address mode sunk into them,
3614 // we can remove the addressing mode and effectively trade one live register
3615 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003616 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003617 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3618 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003619 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003620 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003621
Chandler Carruthc8925912013-01-05 02:09:22 +00003622 // Now that we know that all uses of this instruction are part of a chain of
3623 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003624 // into a memory use, loop over each of these memory operation uses and see
3625 // if they could *actually* fold the instruction. The assumption is that
3626 // addressing modes are cheap and that duplicating the computation involved
3627 // many times is worthwhile, even on a fastpath. For sinking candidates
3628 // (i.e. cold call sites), this serves as a way to prevent excessive code
3629 // growth since most architectures have some reasonable small and fast way to
3630 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003631 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3632 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3633 Instruction *User = MemoryUses[i].first;
3634 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003635
Chandler Carruthc8925912013-01-05 02:09:22 +00003636 // Get the access type of this use. If the use isn't a pointer, we don't
3637 // know what it accesses.
3638 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003639 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3640 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003641 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003642 Type *AddressAccessTy = AddrTy->getElementType();
3643 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003644
Chandler Carruthc8925912013-01-05 02:09:22 +00003645 // Do a match against the root of this address, ignoring profitability. This
3646 // will tell us if the addressing mode for the memory operation will
3647 // *actually* cover the shared instruction.
3648 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003649 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3650 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003651 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003652 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003653 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003654 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003655 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003656 (void)Success; assert(Success && "Couldn't select *anything*?");
3657
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003658 // The match was to check the profitability, the changes made are not
3659 // part of the original matcher. Therefore, they should be dropped
3660 // otherwise the original matcher will not present the right state.
3661 TPT.rollback(LastKnownGood);
3662
Chandler Carruthc8925912013-01-05 02:09:22 +00003663 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003664 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003665 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003666
Chandler Carruthc8925912013-01-05 02:09:22 +00003667 MatchedAddrModeInsts.clear();
3668 }
Stephen Lin837bba12013-07-15 17:55:02 +00003669
Chandler Carruthc8925912013-01-05 02:09:22 +00003670 return true;
3671}
3672
3673} // end anonymous namespace
3674
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003675/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003676/// different basic block than BB.
3677static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3678 if (Instruction *I = dyn_cast<Instruction>(V))
3679 return I->getParent() != BB;
3680 return false;
3681}
3682
Philip Reamesac115ed2016-03-09 23:13:12 +00003683/// Sink addressing mode computation immediate before MemoryInst if doing so
3684/// can be done without increasing register pressure. The need for the
3685/// register pressure constraint means this can end up being an all or nothing
3686/// decision for all uses of the same addressing computation.
3687///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003688/// Load and Store Instructions often have addressing modes that can do
3689/// significant amounts of computation. As such, instruction selection will try
3690/// to get the load or store to do as much computation as possible for the
3691/// program. The problem is that isel can only see within a single block. As
3692/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003693///
3694/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003695/// operands. It's also used to sink addressing computations feeding into cold
3696/// call sites into their (cold) basic block.
3697///
3698/// The motivation for handling sinking into cold blocks is that doing so can
3699/// both enable other address mode sinking (by satisfying the register pressure
3700/// constraint above), and reduce register pressure globally (by removing the
3701/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003702bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003703 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003704 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003705
3706 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003707 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003708 SmallVector<Value*, 8> worklist;
3709 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003710 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003711
Owen Anderson8ba5f392010-11-27 08:15:55 +00003712 // Use a worklist to iteratively look through PHI nodes, and ensure that
3713 // the addressing mode obtained from the non-PHI roots of the graph
3714 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003715 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003716 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003717 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003718 SmallVector<Instruction*, 16> AddrModeInsts;
3719 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003720 TypePromotionTransaction TPT;
3721 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3722 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003723 while (!worklist.empty()) {
3724 Value *V = worklist.back();
3725 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003726
Owen Anderson8ba5f392010-11-27 08:15:55 +00003727 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003728 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003729 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003730 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003731 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003732
Owen Anderson8ba5f392010-11-27 08:15:55 +00003733 // For a PHI node, push all of its incoming values.
3734 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003735 for (Value *IncValue : P->incoming_values())
3736 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003737 continue;
3738 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003739
Philip Reamesac115ed2016-03-09 23:13:12 +00003740 // For non-PHIs, determine the addressing mode being computed. Note that
3741 // the result may differ depending on what other uses our candidate
3742 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003743 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003744 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003745 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003746 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003747
3748 // This check is broken into two cases with very similar code to avoid using
3749 // getNumUses() as much as possible. Some values have a lot of uses, so
3750 // calling getNumUses() unconditionally caused a significant compile-time
3751 // regression.
3752 if (!Consensus) {
3753 Consensus = V;
3754 AddrMode = NewAddrMode;
3755 AddrModeInsts = NewAddrModeInsts;
3756 continue;
3757 } else if (NewAddrMode == AddrMode) {
3758 if (!IsNumUsesConsensusValid) {
3759 NumUsesConsensus = Consensus->getNumUses();
3760 IsNumUsesConsensusValid = true;
3761 }
3762
3763 // Ensure that the obtained addressing mode is equivalent to that obtained
3764 // for all other roots of the PHI traversal. Also, when choosing one
3765 // such root as representative, select the one with the most uses in order
3766 // to keep the cost modeling heuristics in AddressingModeMatcher
3767 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003768 unsigned NumUses = V->getNumUses();
3769 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003770 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003771 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003772 AddrModeInsts = NewAddrModeInsts;
3773 }
3774 continue;
3775 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003776
Craig Topperc0196b12014-04-14 00:51:57 +00003777 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003778 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003779 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003780
Owen Anderson8ba5f392010-11-27 08:15:55 +00003781 // If the addressing mode couldn't be determined, or if multiple different
3782 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003783 if (!Consensus) {
3784 TPT.rollback(LastKnownGood);
3785 return false;
3786 }
3787 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003788
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003789 // Check to see if any of the instructions supersumed by this addr mode are
3790 // non-local to I's BB.
3791 bool AnyNonLocal = false;
3792 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003793 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003794 AnyNonLocal = true;
3795 break;
3796 }
3797 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003798
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003799 // If all the instructions matched are already in this BB, don't do anything.
3800 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003801 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003802 return false;
3803 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003804
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003805 // Insert this computation right after this user. Since our caller is
3806 // scanning from the top of the BB to the bottom, reuse of the expr are
3807 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003808 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003809
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003810 // Now that we determined the addressing expression we want to use and know
3811 // that we have to sink it into this block. Check to see if we have already
3812 // done this for some other load/store instr in this block. If so, reuse the
3813 // computation.
3814 Value *&SunkAddr = SunkAddrs[Addr];
3815 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003816 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003817 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003818 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003819 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003820 } else if (AddrSinkUsingGEPs ||
3821 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003822 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3823 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003824 // By default, we use the GEP-based method when AA is used later. This
3825 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3826 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003827 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003828 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003829 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003830
3831 // First, find the pointer.
3832 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3833 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003834 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003835 }
3836
3837 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3838 // We can't add more than one pointer together, nor can we scale a
3839 // pointer (both of which seem meaningless).
3840 if (ResultPtr || AddrMode.Scale != 1)
3841 return false;
3842
3843 ResultPtr = AddrMode.ScaledReg;
3844 AddrMode.Scale = 0;
3845 }
3846
3847 if (AddrMode.BaseGV) {
3848 if (ResultPtr)
3849 return false;
3850
3851 ResultPtr = AddrMode.BaseGV;
3852 }
3853
3854 // If the real base value actually came from an inttoptr, then the matcher
3855 // will look through it and provide only the integer value. In that case,
3856 // use it here.
3857 if (!ResultPtr && AddrMode.BaseReg) {
3858 ResultPtr =
3859 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003860 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003861 } else if (!ResultPtr && AddrMode.Scale == 1) {
3862 ResultPtr =
3863 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3864 AddrMode.Scale = 0;
3865 }
3866
3867 if (!ResultPtr &&
3868 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3869 SunkAddr = Constant::getNullValue(Addr->getType());
3870 } else if (!ResultPtr) {
3871 return false;
3872 } else {
3873 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003874 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3875 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003876
3877 // Start with the base register. Do this first so that subsequent address
3878 // matching finds it last, which will prevent it from trying to match it
3879 // as the scaled value in case it happens to be a mul. That would be
3880 // problematic if we've sunk a different mul for the scale, because then
3881 // we'd end up sinking both muls.
3882 if (AddrMode.BaseReg) {
3883 Value *V = AddrMode.BaseReg;
3884 if (V->getType() != IntPtrTy)
3885 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3886
3887 ResultIndex = V;
3888 }
3889
3890 // Add the scale value.
3891 if (AddrMode.Scale) {
3892 Value *V = AddrMode.ScaledReg;
3893 if (V->getType() == IntPtrTy) {
3894 // done.
3895 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3896 cast<IntegerType>(V->getType())->getBitWidth()) {
3897 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3898 } else {
3899 // It is only safe to sign extend the BaseReg if we know that the math
3900 // required to create it did not overflow before we extend it. Since
3901 // the original IR value was tossed in favor of a constant back when
3902 // the AddrMode was created we need to bail out gracefully if widths
3903 // do not match instead of extending it.
3904 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3905 if (I && (ResultIndex != AddrMode.BaseReg))
3906 I->eraseFromParent();
3907 return false;
3908 }
3909
3910 if (AddrMode.Scale != 1)
3911 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3912 "sunkaddr");
3913 if (ResultIndex)
3914 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3915 else
3916 ResultIndex = V;
3917 }
3918
3919 // Add in the Base Offset if present.
3920 if (AddrMode.BaseOffs) {
3921 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3922 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003923 // We need to add this separately from the scale above to help with
3924 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003925 if (ResultPtr->getType() != I8PtrTy)
3926 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003927 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003928 }
3929
3930 ResultIndex = V;
3931 }
3932
3933 if (!ResultIndex) {
3934 SunkAddr = ResultPtr;
3935 } else {
3936 if (ResultPtr->getType() != I8PtrTy)
3937 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003938 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003939 }
3940
3941 if (SunkAddr->getType() != Addr->getType())
3942 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3943 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003944 } else {
David Greene74e2d492010-01-05 01:27:11 +00003945 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003946 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003947 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003948 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003949
3950 // Start with the base register. Do this first so that subsequent address
3951 // matching finds it last, which will prevent it from trying to match it
3952 // as the scaled value in case it happens to be a mul. That would be
3953 // problematic if we've sunk a different mul for the scale, because then
3954 // we'd end up sinking both muls.
3955 if (AddrMode.BaseReg) {
3956 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003957 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003958 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003959 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003960 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003961 Result = V;
3962 }
3963
3964 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003965 if (AddrMode.Scale) {
3966 Value *V = AddrMode.ScaledReg;
3967 if (V->getType() == IntPtrTy) {
3968 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003969 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003970 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003971 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3972 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003973 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003974 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003975 // It is only safe to sign extend the BaseReg if we know that the math
3976 // required to create it did not overflow before we extend it. Since
3977 // the original IR value was tossed in favor of a constant back when
3978 // the AddrMode was created we need to bail out gracefully if widths
3979 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003980 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003981 if (I && (Result != AddrMode.BaseReg))
3982 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003983 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003984 }
3985 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003986 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3987 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003988 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003989 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003990 else
3991 Result = V;
3992 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003993
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003994 // Add in the BaseGV if present.
3995 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003996 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003997 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003998 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003999 else
4000 Result = V;
4001 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004002
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004003 // Add in the Base Offset if present.
4004 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004005 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004006 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004007 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004008 else
4009 Result = V;
4010 }
4011
Craig Topperc0196b12014-04-14 00:51:57 +00004012 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004013 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004014 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004015 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004016 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004017
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004018 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004019
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004020 // If we have no uses, recursively delete the value and all dead instructions
4021 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004022 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004023 // This can cause recursive deletion, which can invalidate our iterator.
4024 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004025 Value *CurValue = &*CurInstIterator;
4026 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004027 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004028
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004029 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004030
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004031 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004032 // If the iterator instruction was recursively deleted, start over at the
4033 // start of the block.
4034 CurInstIterator = BB->begin();
4035 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004036 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004037 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004038 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004039 return true;
4040}
4041
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004042/// If there are any memory operands, use OptimizeMemoryInst to sink their
4043/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004044bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004045 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004046
Eric Christopher11e4df72015-02-26 22:38:43 +00004047 const TargetRegisterInfo *TRI =
4048 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004049 TargetLowering::AsmOperandInfoVector TargetConstraints =
4050 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004051 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004052 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4053 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004054
Evan Cheng1da25002008-02-26 02:42:37 +00004055 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004056 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004057
Eli Friedman666bbe32008-02-26 18:37:49 +00004058 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4059 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004060 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004061 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004062 } else if (OpInfo.Type == InlineAsm::isInput)
4063 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004064 }
4065
4066 return MadeChange;
4067}
4068
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004069/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4070/// sign extensions.
4071static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4072 assert(!Inst->use_empty() && "Input must have at least one use");
4073 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4074 bool IsSExt = isa<SExtInst>(FirstUser);
4075 Type *ExtTy = FirstUser->getType();
4076 for (const User *U : Inst->users()) {
4077 const Instruction *UI = cast<Instruction>(U);
4078 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4079 return false;
4080 Type *CurTy = UI->getType();
4081 // Same input and output types: Same instruction after CSE.
4082 if (CurTy == ExtTy)
4083 continue;
4084
4085 // If IsSExt is true, we are in this situation:
4086 // a = Inst
4087 // b = sext ty1 a to ty2
4088 // c = sext ty1 a to ty3
4089 // Assuming ty2 is shorter than ty3, this could be turned into:
4090 // a = Inst
4091 // b = sext ty1 a to ty2
4092 // c = sext ty2 b to ty3
4093 // However, the last sext is not free.
4094 if (IsSExt)
4095 return false;
4096
4097 // This is a ZExt, maybe this is free to extend from one type to another.
4098 // In that case, we would not account for a different use.
4099 Type *NarrowTy;
4100 Type *LargeTy;
4101 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4102 CurTy->getScalarType()->getIntegerBitWidth()) {
4103 NarrowTy = CurTy;
4104 LargeTy = ExtTy;
4105 } else {
4106 NarrowTy = ExtTy;
4107 LargeTy = CurTy;
4108 }
4109
4110 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4111 return false;
4112 }
4113 // All uses are the same or can be derived from one another for free.
4114 return true;
4115}
4116
4117/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4118/// load instruction.
4119/// If an ext(load) can be formed, it is returned via \p LI for the load
4120/// and \p Inst for the extension.
4121/// Otherwise LI == nullptr and Inst == nullptr.
4122/// When some promotion happened, \p TPT contains the proper state to
4123/// revert them.
4124///
4125/// \return true when promoting was necessary to expose the ext(load)
4126/// opportunity, false otherwise.
4127///
4128/// Example:
4129/// \code
4130/// %ld = load i32* %addr
4131/// %add = add nuw i32 %ld, 4
4132/// %zext = zext i32 %add to i64
4133/// \endcode
4134/// =>
4135/// \code
4136/// %ld = load i32* %addr
4137/// %zext = zext i32 %ld to i64
4138/// %add = add nuw i64 %zext, 4
4139/// \encode
4140/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004141bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004142 LoadInst *&LI, Instruction *&Inst,
4143 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004144 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004145 // Iterate over all the extensions to see if one form an ext(load).
4146 for (auto I : Exts) {
4147 // Check if we directly have ext(load).
4148 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4149 Inst = I;
4150 // No promotion happened here.
4151 return false;
4152 }
4153 // Check whether or not we want to do any promotion.
4154 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4155 continue;
4156 // Get the action to perform the promotion.
4157 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004158 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004159 // Check if we can promote.
4160 if (!TPH)
4161 continue;
4162 // Save the current state.
4163 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4164 TPT.getRestorationPoint();
4165 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004166 unsigned NewCreatedInstsCost = 0;
4167 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004168 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004169 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4170 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004171 assert(PromotedVal &&
4172 "TypePromotionHelper should have filtered out those cases");
4173
4174 // We would be able to merge only one extension in a load.
4175 // Therefore, if we have more than 1 new extension we heuristically
4176 // cut this search path, because it means we degrade the code quality.
4177 // With exactly 2, the transformation is neutral, because we will merge
4178 // one extension but leave one. However, we optimistically keep going,
4179 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004180 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4181 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004182 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004183 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004184 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004185 // The promotion is not profitable, rollback to the previous state.
4186 TPT.rollback(LastKnownGood);
4187 continue;
4188 }
4189 // The promotion is profitable.
4190 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004191 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004192 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004193 // If we have created a new extension, i.e., now we have two
4194 // extensions. We must make sure one of them is merged with
4195 // the load, otherwise we may degrade the code quality.
4196 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4197 // Promotion happened.
4198 return true;
4199 // If this does not help to expose an ext(load) then, rollback.
4200 TPT.rollback(LastKnownGood);
4201 }
4202 // None of the extension can form an ext(load).
4203 LI = nullptr;
4204 Inst = nullptr;
4205 return false;
4206}
4207
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004208/// Move a zext or sext fed by a load into the same basic block as the load,
4209/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4210/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004211/// \p I[in/out] the extension may be modified during the process if some
4212/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004213///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004214bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004215 // Try to promote a chain of computation if it allows to form
4216 // an extended load.
4217 TypePromotionTransaction TPT;
4218 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4219 TPT.getRestorationPoint();
4220 SmallVector<Instruction *, 1> Exts;
4221 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004222 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004223 LoadInst *LI = nullptr;
4224 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004225 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004226 if (!LI || !I) {
4227 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4228 "the code must remain the same");
4229 I = OldExt;
4230 return false;
4231 }
Dan Gohman99429a02009-10-16 20:59:35 +00004232
4233 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004234 // Make the cheap checks first if we did not promote.
4235 // If we promoted, we need to check if it is indeed profitable.
4236 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004237 return false;
4238
Mehdi Amini44ede332015-07-09 02:09:04 +00004239 EVT VT = TLI->getValueType(*DL, I->getType());
4240 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004241
Dan Gohman99429a02009-10-16 20:59:35 +00004242 // If the load has other users and the truncate is not free, this probably
4243 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004244 if (!LI->hasOneUse() && TLI &&
4245 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004246 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4247 I = OldExt;
4248 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004249 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004250 }
Dan Gohman99429a02009-10-16 20:59:35 +00004251
4252 // Check whether the target supports casts folded into loads.
4253 unsigned LType;
4254 if (isa<ZExtInst>(I))
4255 LType = ISD::ZEXTLOAD;
4256 else {
4257 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4258 LType = ISD::SEXTLOAD;
4259 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004260 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004261 I = OldExt;
4262 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004263 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004264 }
Dan Gohman99429a02009-10-16 20:59:35 +00004265
4266 // Move the extend into the same block as the load, so that SelectionDAG
4267 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004268 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004269 I->removeFromParent();
4270 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004271 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004272 return true;
4273}
4274
Sanjay Patelfc580a62015-09-21 23:03:16 +00004275bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004276 BasicBlock *DefBB = I->getParent();
4277
Bob Wilsonff714f92010-09-21 21:44:14 +00004278 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004279 // other uses of the source with result of extension.
4280 Value *Src = I->getOperand(0);
4281 if (Src->hasOneUse())
4282 return false;
4283
Evan Cheng2011df42007-12-13 07:50:36 +00004284 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004285 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004286 return false;
4287
Evan Cheng7bc89422007-12-12 00:51:06 +00004288 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004289 // this block.
4290 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004291 return false;
4292
Evan Chengd3d80172007-12-05 23:58:20 +00004293 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004294 for (User *U : I->users()) {
4295 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004296
4297 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004298 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004299 if (UserBB == DefBB) continue;
4300 DefIsLiveOut = true;
4301 break;
4302 }
4303 if (!DefIsLiveOut)
4304 return false;
4305
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004306 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004307 for (User *U : Src->users()) {
4308 Instruction *UI = cast<Instruction>(U);
4309 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004310 if (UserBB == DefBB) continue;
4311 // Be conservative. We don't want this xform to end up introducing
4312 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004313 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004314 return false;
4315 }
4316
Evan Chengd3d80172007-12-05 23:58:20 +00004317 // InsertedTruncs - Only insert one trunc in each block once.
4318 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4319
4320 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004321 for (Use &U : Src->uses()) {
4322 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004323
4324 // Figure out which BB this ext is used in.
4325 BasicBlock *UserBB = User->getParent();
4326 if (UserBB == DefBB) continue;
4327
4328 // Both src and def are live in this block. Rewrite the use.
4329 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4330
4331 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004332 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004333 assert(InsertPt != UserBB->end());
4334 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004335 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004336 }
4337
4338 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004339 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004340 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004341 MadeChange = true;
4342 }
4343
4344 return MadeChange;
4345}
4346
Geoff Berry5256fca2015-11-20 22:34:39 +00004347// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4348// just after the load if the target can fold this into one extload instruction,
4349// with the hope of eliminating some of the other later "and" instructions using
4350// the loaded value. "and"s that are made trivially redundant by the insertion
4351// of the new "and" are removed by this function, while others (e.g. those whose
4352// path from the load goes through a phi) are left for isel to potentially
4353// remove.
4354//
4355// For example:
4356//
4357// b0:
4358// x = load i32
4359// ...
4360// b1:
4361// y = and x, 0xff
4362// z = use y
4363//
4364// becomes:
4365//
4366// b0:
4367// x = load i32
4368// x' = and x, 0xff
4369// ...
4370// b1:
4371// z = use x'
4372//
4373// whereas:
4374//
4375// b0:
4376// x1 = load i32
4377// ...
4378// b1:
4379// x2 = load i32
4380// ...
4381// b2:
4382// x = phi x1, x2
4383// y = and x, 0xff
4384//
4385// becomes (after a call to optimizeLoadExt for each load):
4386//
4387// b0:
4388// x1 = load i32
4389// x1' = and x1, 0xff
4390// ...
4391// b1:
4392// x2 = load i32
4393// x2' = and x2, 0xff
4394// ...
4395// b2:
4396// x = phi x1', x2'
4397// y = and x, 0xff
4398//
4399
4400bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4401
4402 if (!Load->isSimple() ||
4403 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4404 return false;
4405
4406 // Skip loads we've already transformed or have no reason to transform.
4407 if (Load->hasOneUse()) {
4408 User *LoadUser = *Load->user_begin();
4409 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4410 !dyn_cast<PHINode>(LoadUser))
4411 return false;
4412 }
4413
4414 // Look at all uses of Load, looking through phis, to determine how many bits
4415 // of the loaded value are needed.
4416 SmallVector<Instruction *, 8> WorkList;
4417 SmallPtrSet<Instruction *, 16> Visited;
4418 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4419 for (auto *U : Load->users())
4420 WorkList.push_back(cast<Instruction>(U));
4421
4422 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4423 unsigned BitWidth = LoadResultVT.getSizeInBits();
4424 APInt DemandBits(BitWidth, 0);
4425 APInt WidestAndBits(BitWidth, 0);
4426
4427 while (!WorkList.empty()) {
4428 Instruction *I = WorkList.back();
4429 WorkList.pop_back();
4430
4431 // Break use-def graph loops.
4432 if (!Visited.insert(I).second)
4433 continue;
4434
4435 // For a PHI node, push all of its users.
4436 if (auto *Phi = dyn_cast<PHINode>(I)) {
4437 for (auto *U : Phi->users())
4438 WorkList.push_back(cast<Instruction>(U));
4439 continue;
4440 }
4441
4442 switch (I->getOpcode()) {
4443 case llvm::Instruction::And: {
4444 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4445 if (!AndC)
4446 return false;
4447 APInt AndBits = AndC->getValue();
4448 DemandBits |= AndBits;
4449 // Keep track of the widest and mask we see.
4450 if (AndBits.ugt(WidestAndBits))
4451 WidestAndBits = AndBits;
4452 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4453 AndsToMaybeRemove.push_back(I);
4454 break;
4455 }
4456
4457 case llvm::Instruction::Shl: {
4458 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4459 if (!ShlC)
4460 return false;
4461 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4462 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4463 DemandBits |= ShlDemandBits;
4464 break;
4465 }
4466
4467 case llvm::Instruction::Trunc: {
4468 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4469 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4470 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4471 DemandBits |= TruncBits;
4472 break;
4473 }
4474
4475 default:
4476 return false;
4477 }
4478 }
4479
4480 uint32_t ActiveBits = DemandBits.getActiveBits();
4481 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4482 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4483 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4484 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4485 // followed by an AND.
4486 // TODO: Look into removing this restriction by fixing backends to either
4487 // return false for isLoadExtLegal for i1 or have them select this pattern to
4488 // a single instruction.
4489 //
4490 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4491 // mask, since these are the only ands that will be removed by isel.
4492 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4493 WidestAndBits != DemandBits)
4494 return false;
4495
4496 LLVMContext &Ctx = Load->getType()->getContext();
4497 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4498 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4499
4500 // Reject cases that won't be matched as extloads.
4501 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4502 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4503 return false;
4504
4505 IRBuilder<> Builder(Load->getNextNode());
4506 auto *NewAnd = dyn_cast<Instruction>(
4507 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4508
4509 // Replace all uses of load with new and (except for the use of load in the
4510 // new and itself).
4511 Load->replaceAllUsesWith(NewAnd);
4512 NewAnd->setOperand(0, Load);
4513
4514 // Remove any and instructions that are now redundant.
4515 for (auto *And : AndsToMaybeRemove)
4516 // Check that the and mask is the same as the one we decided to put on the
4517 // new and.
4518 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4519 And->replaceAllUsesWith(NewAnd);
4520 if (&*CurInstIterator == And)
4521 CurInstIterator = std::next(And->getIterator());
4522 And->eraseFromParent();
4523 ++NumAndUses;
4524 }
4525
4526 ++NumAndsAdded;
4527 return true;
4528}
4529
Sanjay Patel69a50a12015-10-19 21:59:12 +00004530/// Check if V (an operand of a select instruction) is an expensive instruction
4531/// that is only used once.
4532static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4533 auto *I = dyn_cast<Instruction>(V);
4534 // If it's safe to speculatively execute, then it should not have side
4535 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004536 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4537 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004538}
4539
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004540/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004541static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004542 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004543 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004544 // If even a predictable select is cheap, then a branch can't be cheaper.
4545 if (!TLI->isPredictableSelectExpensive())
4546 return false;
4547
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004548 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004549 // whether a select is better represented as a branch.
4550
4551 // If metadata tells us that the select condition is obviously predictable,
4552 // then we want to replace the select with a branch.
4553 uint64_t TrueWeight, FalseWeight;
4554 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4555 uint64_t Max = std::max(TrueWeight, FalseWeight);
4556 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004557 if (Sum != 0) {
4558 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4559 if (Probability > TLI->getPredictableBranchThreshold())
4560 return true;
4561 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004562 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004563
4564 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4565
Sanjay Patel4e652762015-09-28 22:14:51 +00004566 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4567 // comparison condition. If the compare has more than one use, there's
4568 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004569 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004570 return false;
4571
Sanjay Patel69a50a12015-10-19 21:59:12 +00004572 // If either operand of the select is expensive and only needed on one side
4573 // of the select, we should form a branch.
4574 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4575 sinkSelectOperand(TTI, SI->getFalseValue()))
4576 return true;
4577
4578 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004579}
4580
Dehao Chen9bbb9412016-09-12 20:23:28 +00004581/// If \p isTrue is true, return the true value of \p SI, otherwise return
4582/// false value of \p SI. If the true/false value of \p SI is defined by any
4583/// select instructions in \p Selects, look through the defining select
4584/// instruction until the true/false value is not defined in \p Selects.
4585static Value *getTrueOrFalseValue(
4586 SelectInst *SI, bool isTrue,
4587 const SmallPtrSet<const Instruction *, 2> &Selects) {
4588 Value *V;
4589
4590 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4591 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004592 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004593 "The condition of DefSI does not match with SI");
4594 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4595 }
4596 return V;
4597}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004598
Nadav Rotem9d832022012-09-02 12:10:19 +00004599/// If we have a SelectInst that will likely profit from branch prediction,
4600/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004601bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004602 // Find all consecutive select instructions that share the same condition.
4603 SmallVector<SelectInst *, 2> ASI;
4604 ASI.push_back(SI);
4605 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4606 It != SI->getParent()->end(); ++It) {
4607 SelectInst *I = dyn_cast<SelectInst>(&*It);
4608 if (I && SI->getCondition() == I->getCondition()) {
4609 ASI.push_back(I);
4610 } else {
4611 break;
4612 }
4613 }
4614
4615 SelectInst *LastSI = ASI.back();
4616 // Increment the current iterator to skip all the rest of select instructions
4617 // because they will be either "not lowered" or "all lowered" to branch.
4618 CurInstIterator = std::next(LastSI->getIterator());
4619
Nadav Rotem9d832022012-09-02 12:10:19 +00004620 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4621
4622 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004623 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4624 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004625 return false;
4626
Nadav Rotem9d832022012-09-02 12:10:19 +00004627 TargetLowering::SelectSupportKind SelectKind;
4628 if (VectorCond)
4629 SelectKind = TargetLowering::VectorMaskSelect;
4630 else if (SI->getType()->isVectorTy())
4631 SelectKind = TargetLowering::ScalarCondVectorVal;
4632 else
4633 SelectKind = TargetLowering::ScalarValSelect;
4634
Sanjay Pateld66607b2016-04-26 17:11:17 +00004635 if (TLI->isSelectSupported(SelectKind) &&
4636 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4637 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004638
4639 ModifiedDT = true;
4640
Sanjay Patel69a50a12015-10-19 21:59:12 +00004641 // Transform a sequence like this:
4642 // start:
4643 // %cmp = cmp uge i32 %a, %b
4644 // %sel = select i1 %cmp, i32 %c, i32 %d
4645 //
4646 // Into:
4647 // start:
4648 // %cmp = cmp uge i32 %a, %b
4649 // br i1 %cmp, label %select.true, label %select.false
4650 // select.true:
4651 // br label %select.end
4652 // select.false:
4653 // br label %select.end
4654 // select.end:
4655 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4656 //
4657 // In addition, we may sink instructions that produce %c or %d from
4658 // the entry block into the destination(s) of the new branch.
4659 // If the true or false blocks do not contain a sunken instruction, that
4660 // block and its branch may be optimized away. In that case, one side of the
4661 // first branch will point directly to select.end, and the corresponding PHI
4662 // predecessor block will be the start block.
4663
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004664 // First, we split the block containing the select into 2 blocks.
4665 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004666 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004667 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004668
Sanjay Patel69a50a12015-10-19 21:59:12 +00004669 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004670 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004671
4672 // These are the new basic blocks for the conditional branch.
4673 // At least one will become an actual new basic block.
4674 BasicBlock *TrueBlock = nullptr;
4675 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004676 BranchInst *TrueBranch = nullptr;
4677 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004678
4679 // Sink expensive instructions into the conditional blocks to avoid executing
4680 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004681 for (SelectInst *SI : ASI) {
4682 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4683 if (TrueBlock == nullptr) {
4684 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4685 EndBlock->getParent(), EndBlock);
4686 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4687 }
4688 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4689 TrueInst->moveBefore(TrueBranch);
4690 }
4691 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4692 if (FalseBlock == nullptr) {
4693 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4694 EndBlock->getParent(), EndBlock);
4695 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4696 }
4697 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4698 FalseInst->moveBefore(FalseBranch);
4699 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004700 }
4701
4702 // If there was nothing to sink, then arbitrarily choose the 'false' side
4703 // for a new input value to the PHI.
4704 if (TrueBlock == FalseBlock) {
4705 assert(TrueBlock == nullptr &&
4706 "Unexpected basic block transform while optimizing select");
4707
4708 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4709 EndBlock->getParent(), EndBlock);
4710 BranchInst::Create(EndBlock, FalseBlock);
4711 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004712
4713 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004714 // If we did not create a new block for one of the 'true' or 'false' paths
4715 // of the condition, it means that side of the branch goes to the end block
4716 // directly and the path originates from the start block from the point of
4717 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004718 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004719 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004720 TT = EndBlock;
4721 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004722 TrueBlock = StartBlock;
4723 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004724 TT = TrueBlock;
4725 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004726 FalseBlock = StartBlock;
4727 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004728 TT = TrueBlock;
4729 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004730 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004731 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004732
Dehao Chen9bbb9412016-09-12 20:23:28 +00004733 SmallPtrSet<const Instruction *, 2> INS;
4734 INS.insert(ASI.begin(), ASI.end());
4735 // Use reverse iterator because later select may use the value of the
4736 // earlier select, and we need to propagate value through earlier select
4737 // to get the PHI operand.
4738 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4739 SelectInst *SI = *It;
4740 // The select itself is replaced with a PHI Node.
4741 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4742 PN->takeName(SI);
4743 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4744 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004745
Dehao Chen9bbb9412016-09-12 20:23:28 +00004746 SI->replaceAllUsesWith(PN);
4747 SI->eraseFromParent();
4748 INS.erase(SI);
4749 ++NumSelectsExpanded;
4750 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004751
4752 // Instruct OptimizeBlock to skip to the next block.
4753 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004754 return true;
4755}
4756
Benjamin Kramer573ff362014-03-01 17:24:40 +00004757static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004758 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4759 int SplatElem = -1;
4760 for (unsigned i = 0; i < Mask.size(); ++i) {
4761 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4762 return false;
4763 SplatElem = Mask[i];
4764 }
4765
4766 return true;
4767}
4768
4769/// Some targets have expensive vector shifts if the lanes aren't all the same
4770/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4771/// it's often worth sinking a shufflevector splat down to its use so that
4772/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004773bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004774 BasicBlock *DefBB = SVI->getParent();
4775
4776 // Only do this xform if variable vector shifts are particularly expensive.
4777 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4778 return false;
4779
4780 // We only expect better codegen by sinking a shuffle if we can recognise a
4781 // constant splat.
4782 if (!isBroadcastShuffle(SVI))
4783 return false;
4784
4785 // InsertedShuffles - Only insert a shuffle in each block once.
4786 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4787
4788 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004789 for (User *U : SVI->users()) {
4790 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004791
4792 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004793 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004794 if (UserBB == DefBB) continue;
4795
4796 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004797 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004798
4799 // Everything checks out, sink the shuffle if the user's block doesn't
4800 // already have a copy.
4801 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4802
4803 if (!InsertedShuffle) {
4804 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004805 assert(InsertPt != UserBB->end());
4806 InsertedShuffle =
4807 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4808 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004809 }
4810
Chandler Carruthcdf47882014-03-09 03:16:01 +00004811 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004812 MadeChange = true;
4813 }
4814
4815 // If we removed all uses, nuke the shuffle.
4816 if (SVI->use_empty()) {
4817 SVI->eraseFromParent();
4818 MadeChange = true;
4819 }
4820
4821 return MadeChange;
4822}
4823
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004824bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4825 if (!TLI || !DL)
4826 return false;
4827
4828 Value *Cond = SI->getCondition();
4829 Type *OldType = Cond->getType();
4830 LLVMContext &Context = Cond->getContext();
4831 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4832 unsigned RegWidth = RegType.getSizeInBits();
4833
4834 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4835 return false;
4836
4837 // If the register width is greater than the type width, expand the condition
4838 // of the switch instruction and each case constant to the width of the
4839 // register. By widening the type of the switch condition, subsequent
4840 // comparisons (for case comparisons) will not need to be extended to the
4841 // preferred register width, so we will potentially eliminate N-1 extends,
4842 // where N is the number of cases in the switch.
4843 auto *NewType = Type::getIntNTy(Context, RegWidth);
4844
4845 // Zero-extend the switch condition and case constants unless the switch
4846 // condition is a function argument that is already being sign-extended.
4847 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4848 // everything instead.
4849 Instruction::CastOps ExtType = Instruction::ZExt;
4850 if (auto *Arg = dyn_cast<Argument>(Cond))
4851 if (Arg->hasSExtAttr())
4852 ExtType = Instruction::SExt;
4853
4854 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4855 ExtInst->insertBefore(SI);
4856 SI->setCondition(ExtInst);
4857 for (SwitchInst::CaseIt Case : SI->cases()) {
4858 APInt NarrowConst = Case.getCaseValue()->getValue();
4859 APInt WideConst = (ExtType == Instruction::ZExt) ?
4860 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4861 Case.setValue(ConstantInt::get(Context, WideConst));
4862 }
4863
4864 return true;
4865}
4866
Quentin Colombetc32615d2014-10-31 17:52:53 +00004867namespace {
4868/// \brief Helper class to promote a scalar operation to a vector one.
4869/// This class is used to move downward extractelement transition.
4870/// E.g.,
4871/// a = vector_op <2 x i32>
4872/// b = extractelement <2 x i32> a, i32 0
4873/// c = scalar_op b
4874/// store c
4875///
4876/// =>
4877/// a = vector_op <2 x i32>
4878/// c = vector_op a (equivalent to scalar_op on the related lane)
4879/// * d = extractelement <2 x i32> c, i32 0
4880/// * store d
4881/// Assuming both extractelement and store can be combine, we get rid of the
4882/// transition.
4883class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004884 /// DataLayout associated with the current module.
4885 const DataLayout &DL;
4886
Quentin Colombetc32615d2014-10-31 17:52:53 +00004887 /// Used to perform some checks on the legality of vector operations.
4888 const TargetLowering &TLI;
4889
4890 /// Used to estimated the cost of the promoted chain.
4891 const TargetTransformInfo &TTI;
4892
4893 /// The transition being moved downwards.
4894 Instruction *Transition;
4895 /// The sequence of instructions to be promoted.
4896 SmallVector<Instruction *, 4> InstsToBePromoted;
4897 /// Cost of combining a store and an extract.
4898 unsigned StoreExtractCombineCost;
4899 /// Instruction that will be combined with the transition.
4900 Instruction *CombineInst;
4901
4902 /// \brief The instruction that represents the current end of the transition.
4903 /// Since we are faking the promotion until we reach the end of the chain
4904 /// of computation, we need a way to get the current end of the transition.
4905 Instruction *getEndOfTransition() const {
4906 if (InstsToBePromoted.empty())
4907 return Transition;
4908 return InstsToBePromoted.back();
4909 }
4910
4911 /// \brief Return the index of the original value in the transition.
4912 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4913 /// c, is at index 0.
4914 unsigned getTransitionOriginalValueIdx() const {
4915 assert(isa<ExtractElementInst>(Transition) &&
4916 "Other kind of transitions are not supported yet");
4917 return 0;
4918 }
4919
4920 /// \brief Return the index of the index in the transition.
4921 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4922 /// is at index 1.
4923 unsigned getTransitionIdx() const {
4924 assert(isa<ExtractElementInst>(Transition) &&
4925 "Other kind of transitions are not supported yet");
4926 return 1;
4927 }
4928
4929 /// \brief Get the type of the transition.
4930 /// This is the type of the original value.
4931 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4932 /// transition is <2 x i32>.
4933 Type *getTransitionType() const {
4934 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4935 }
4936
4937 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4938 /// I.e., we have the following sequence:
4939 /// Def = Transition <ty1> a to <ty2>
4940 /// b = ToBePromoted <ty2> Def, ...
4941 /// =>
4942 /// b = ToBePromoted <ty1> a, ...
4943 /// Def = Transition <ty1> ToBePromoted to <ty2>
4944 void promoteImpl(Instruction *ToBePromoted);
4945
4946 /// \brief Check whether or not it is profitable to promote all the
4947 /// instructions enqueued to be promoted.
4948 bool isProfitableToPromote() {
4949 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4950 unsigned Index = isa<ConstantInt>(ValIdx)
4951 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4952 : -1;
4953 Type *PromotedType = getTransitionType();
4954
4955 StoreInst *ST = cast<StoreInst>(CombineInst);
4956 unsigned AS = ST->getPointerAddressSpace();
4957 unsigned Align = ST->getAlignment();
4958 // Check if this store is supported.
4959 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004960 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4961 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004962 // If this is not supported, there is no way we can combine
4963 // the extract with the store.
4964 return false;
4965 }
4966
4967 // The scalar chain of computation has to pay for the transition
4968 // scalar to vector.
4969 // The vector chain has to account for the combining cost.
4970 uint64_t ScalarCost =
4971 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4972 uint64_t VectorCost = StoreExtractCombineCost;
4973 for (const auto &Inst : InstsToBePromoted) {
4974 // Compute the cost.
4975 // By construction, all instructions being promoted are arithmetic ones.
4976 // Moreover, one argument is a constant that can be viewed as a splat
4977 // constant.
4978 Value *Arg0 = Inst->getOperand(0);
4979 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4980 isa<ConstantFP>(Arg0);
4981 TargetTransformInfo::OperandValueKind Arg0OVK =
4982 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4983 : TargetTransformInfo::OK_AnyValue;
4984 TargetTransformInfo::OperandValueKind Arg1OVK =
4985 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4986 : TargetTransformInfo::OK_AnyValue;
4987 ScalarCost += TTI.getArithmeticInstrCost(
4988 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4989 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4990 Arg0OVK, Arg1OVK);
4991 }
4992 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4993 << ScalarCost << "\nVector: " << VectorCost << '\n');
4994 return ScalarCost > VectorCost;
4995 }
4996
4997 /// \brief Generate a constant vector with \p Val with the same
4998 /// number of elements as the transition.
4999 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005000 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005001 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5002 /// otherwise we generate a vector with as many undef as possible:
5003 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5004 /// used at the index of the extract.
5005 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5006 unsigned ExtractIdx = UINT_MAX;
5007 if (!UseSplat) {
5008 // If we cannot determine where the constant must be, we have to
5009 // use a splat constant.
5010 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5011 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5012 ExtractIdx = CstVal->getSExtValue();
5013 else
5014 UseSplat = true;
5015 }
5016
5017 unsigned End = getTransitionType()->getVectorNumElements();
5018 if (UseSplat)
5019 return ConstantVector::getSplat(End, Val);
5020
5021 SmallVector<Constant *, 4> ConstVec;
5022 UndefValue *UndefVal = UndefValue::get(Val->getType());
5023 for (unsigned Idx = 0; Idx != End; ++Idx) {
5024 if (Idx == ExtractIdx)
5025 ConstVec.push_back(Val);
5026 else
5027 ConstVec.push_back(UndefVal);
5028 }
5029 return ConstantVector::get(ConstVec);
5030 }
5031
5032 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5033 /// in \p Use can trigger undefined behavior.
5034 static bool canCauseUndefinedBehavior(const Instruction *Use,
5035 unsigned OperandIdx) {
5036 // This is not safe to introduce undef when the operand is on
5037 // the right hand side of a division-like instruction.
5038 if (OperandIdx != 1)
5039 return false;
5040 switch (Use->getOpcode()) {
5041 default:
5042 return false;
5043 case Instruction::SDiv:
5044 case Instruction::UDiv:
5045 case Instruction::SRem:
5046 case Instruction::URem:
5047 return true;
5048 case Instruction::FDiv:
5049 case Instruction::FRem:
5050 return !Use->hasNoNaNs();
5051 }
5052 llvm_unreachable(nullptr);
5053 }
5054
5055public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005056 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5057 const TargetTransformInfo &TTI, Instruction *Transition,
5058 unsigned CombineCost)
5059 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005060 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5061 assert(Transition && "Do not know how to promote null");
5062 }
5063
5064 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5065 bool canPromote(const Instruction *ToBePromoted) const {
5066 // We could support CastInst too.
5067 return isa<BinaryOperator>(ToBePromoted);
5068 }
5069
5070 /// \brief Check if it is profitable to promote \p ToBePromoted
5071 /// by moving downward the transition through.
5072 bool shouldPromote(const Instruction *ToBePromoted) const {
5073 // Promote only if all the operands can be statically expanded.
5074 // Indeed, we do not want to introduce any new kind of transitions.
5075 for (const Use &U : ToBePromoted->operands()) {
5076 const Value *Val = U.get();
5077 if (Val == getEndOfTransition()) {
5078 // If the use is a division and the transition is on the rhs,
5079 // we cannot promote the operation, otherwise we may create a
5080 // division by zero.
5081 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5082 return false;
5083 continue;
5084 }
5085 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5086 !isa<ConstantFP>(Val))
5087 return false;
5088 }
5089 // Check that the resulting operation is legal.
5090 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5091 if (!ISDOpcode)
5092 return false;
5093 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005094 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005095 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005096 }
5097
5098 /// \brief Check whether or not \p Use can be combined
5099 /// with the transition.
5100 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5101 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5102
5103 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5104 void enqueueForPromotion(Instruction *ToBePromoted) {
5105 InstsToBePromoted.push_back(ToBePromoted);
5106 }
5107
5108 /// \brief Set the instruction that will be combined with the transition.
5109 void recordCombineInstruction(Instruction *ToBeCombined) {
5110 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5111 CombineInst = ToBeCombined;
5112 }
5113
5114 /// \brief Promote all the instructions enqueued for promotion if it is
5115 /// is profitable.
5116 /// \return True if the promotion happened, false otherwise.
5117 bool promote() {
5118 // Check if there is something to promote.
5119 // Right now, if we do not have anything to combine with,
5120 // we assume the promotion is not profitable.
5121 if (InstsToBePromoted.empty() || !CombineInst)
5122 return false;
5123
5124 // Check cost.
5125 if (!StressStoreExtract && !isProfitableToPromote())
5126 return false;
5127
5128 // Promote.
5129 for (auto &ToBePromoted : InstsToBePromoted)
5130 promoteImpl(ToBePromoted);
5131 InstsToBePromoted.clear();
5132 return true;
5133 }
5134};
5135} // End of anonymous namespace.
5136
5137void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5138 // At this point, we know that all the operands of ToBePromoted but Def
5139 // can be statically promoted.
5140 // For Def, we need to use its parameter in ToBePromoted:
5141 // b = ToBePromoted ty1 a
5142 // Def = Transition ty1 b to ty2
5143 // Move the transition down.
5144 // 1. Replace all uses of the promoted operation by the transition.
5145 // = ... b => = ... Def.
5146 assert(ToBePromoted->getType() == Transition->getType() &&
5147 "The type of the result of the transition does not match "
5148 "the final type");
5149 ToBePromoted->replaceAllUsesWith(Transition);
5150 // 2. Update the type of the uses.
5151 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5152 Type *TransitionTy = getTransitionType();
5153 ToBePromoted->mutateType(TransitionTy);
5154 // 3. Update all the operands of the promoted operation with promoted
5155 // operands.
5156 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5157 for (Use &U : ToBePromoted->operands()) {
5158 Value *Val = U.get();
5159 Value *NewVal = nullptr;
5160 if (Val == Transition)
5161 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5162 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5163 isa<ConstantFP>(Val)) {
5164 // Use a splat constant if it is not safe to use undef.
5165 NewVal = getConstantVector(
5166 cast<Constant>(Val),
5167 isa<UndefValue>(Val) ||
5168 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5169 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005170 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5171 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005172 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5173 }
5174 Transition->removeFromParent();
5175 Transition->insertAfter(ToBePromoted);
5176 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5177}
5178
5179/// Some targets can do store(extractelement) with one instruction.
5180/// Try to push the extractelement towards the stores when the target
5181/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005182bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005183 unsigned CombineCost = UINT_MAX;
5184 if (DisableStoreExtract || !TLI ||
5185 (!StressStoreExtract &&
5186 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5187 Inst->getOperand(1), CombineCost)))
5188 return false;
5189
5190 // At this point we know that Inst is a vector to scalar transition.
5191 // Try to move it down the def-use chain, until:
5192 // - We can combine the transition with its single use
5193 // => we got rid of the transition.
5194 // - We escape the current basic block
5195 // => we would need to check that we are moving it at a cheaper place and
5196 // we do not do that for now.
5197 BasicBlock *Parent = Inst->getParent();
5198 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005199 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005200 // If the transition has more than one use, assume this is not going to be
5201 // beneficial.
5202 while (Inst->hasOneUse()) {
5203 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5204 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5205
5206 if (ToBePromoted->getParent() != Parent) {
5207 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5208 << ToBePromoted->getParent()->getName()
5209 << ") than the transition (" << Parent->getName() << ").\n");
5210 return false;
5211 }
5212
5213 if (VPH.canCombine(ToBePromoted)) {
5214 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5215 << "will be combined with: " << *ToBePromoted << '\n');
5216 VPH.recordCombineInstruction(ToBePromoted);
5217 bool Changed = VPH.promote();
5218 NumStoreExtractExposed += Changed;
5219 return Changed;
5220 }
5221
5222 DEBUG(dbgs() << "Try promoting.\n");
5223 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5224 return false;
5225
5226 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5227
5228 VPH.enqueueForPromotion(ToBePromoted);
5229 Inst = ToBePromoted;
5230 }
5231 return false;
5232}
5233
Sanjay Patelfc580a62015-09-21 23:03:16 +00005234bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005235 // Bail out if we inserted the instruction to prevent optimizations from
5236 // stepping on each other's toes.
5237 if (InsertedInsts.count(I))
5238 return false;
5239
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005240 if (PHINode *P = dyn_cast<PHINode>(I)) {
5241 // It is possible for very late stage optimizations (such as SimplifyCFG)
5242 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5243 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005244 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005245 P->replaceAllUsesWith(V);
5246 P->eraseFromParent();
5247 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005248 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005249 }
Chris Lattneree588de2011-01-15 07:29:01 +00005250 return false;
5251 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005252
Chris Lattneree588de2011-01-15 07:29:01 +00005253 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005254 // If the source of the cast is a constant, then this should have
5255 // already been constant folded. The only reason NOT to constant fold
5256 // it is if something (e.g. LSR) was careful to place the constant
5257 // evaluation in a block other than then one that uses it (e.g. to hoist
5258 // the address of globals out of a loop). If this is the case, we don't
5259 // want to forward-subst the cast.
5260 if (isa<Constant>(CI->getOperand(0)))
5261 return false;
5262
Mehdi Amini44ede332015-07-09 02:09:04 +00005263 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005264 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005265
Chris Lattneree588de2011-01-15 07:29:01 +00005266 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005267 /// Sink a zext or sext into its user blocks if the target type doesn't
5268 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005269 if (TLI &&
5270 TLI->getTypeAction(CI->getContext(),
5271 TLI->getValueType(*DL, CI->getType())) ==
5272 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005273 return SinkCast(CI);
5274 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005275 bool MadeChange = moveExtToFormExtLoad(I);
5276 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005277 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005278 }
Chris Lattneree588de2011-01-15 07:29:01 +00005279 return false;
5280 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005281
Chris Lattneree588de2011-01-15 07:29:01 +00005282 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005283 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005284 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005285
Chris Lattneree588de2011-01-15 07:29:01 +00005286 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005287 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005288 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005289 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005290 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005291 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5292 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005293 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005294 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005295 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005296
Chris Lattneree588de2011-01-15 07:29:01 +00005297 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005298 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005299 if (TLI) {
5300 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005301 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005302 SI->getOperand(0)->getType(), AS);
5303 }
Chris Lattneree588de2011-01-15 07:29:01 +00005304 return false;
5305 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005306
Yi Jiangd069f632014-04-21 19:34:27 +00005307 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5308
5309 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5310 BinOp->getOpcode() == Instruction::LShr)) {
5311 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5312 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005313 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005314
5315 return false;
5316 }
5317
Chris Lattneree588de2011-01-15 07:29:01 +00005318 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005319 if (GEPI->hasAllZeroIndices()) {
5320 /// The GEP operand must be a pointer, so must its result -> BitCast
5321 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5322 GEPI->getName(), GEPI);
5323 GEPI->replaceAllUsesWith(NC);
5324 GEPI->eraseFromParent();
5325 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005326 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005327 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005328 }
Chris Lattneree588de2011-01-15 07:29:01 +00005329 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005330 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005331
Chris Lattneree588de2011-01-15 07:29:01 +00005332 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005333 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005334
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005335 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005336 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005337
Tim Northoveraeb8e062014-02-19 10:02:43 +00005338 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005339 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005340
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005341 if (auto *Switch = dyn_cast<SwitchInst>(I))
5342 return optimizeSwitchInst(Switch);
5343
Quentin Colombetc32615d2014-10-31 17:52:53 +00005344 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005345 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005346
Chris Lattneree588de2011-01-15 07:29:01 +00005347 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005348}
5349
James Molloyf01488e2016-01-15 09:20:19 +00005350/// Given an OR instruction, check to see if this is a bitreverse
5351/// idiom. If so, insert the new intrinsic and return true.
5352static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5353 const TargetLowering &TLI) {
5354 if (!I.getType()->isIntegerTy() ||
5355 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5356 TLI.getValueType(DL, I.getType(), true)))
5357 return false;
5358
5359 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005360 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005361 return false;
5362 Instruction *LastInst = Insts.back();
5363 I.replaceAllUsesWith(LastInst);
5364 RecursivelyDeleteTriviallyDeadInstructions(&I);
5365 return true;
5366}
5367
Chris Lattnerf2836d12007-03-31 04:06:36 +00005368// In this pass we look for GEP and cast instructions that are used
5369// across basic blocks and rewrite them to improve basic-block-at-a-time
5370// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005371bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005372 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005373 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005374
Chris Lattner7a277142011-01-15 07:14:54 +00005375 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005376 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005377 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005378 if (ModifiedDT)
5379 return true;
5380 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005381
James Molloyf01488e2016-01-15 09:20:19 +00005382 bool MadeBitReverse = true;
5383 while (TLI && MadeBitReverse) {
5384 MadeBitReverse = false;
5385 for (auto &I : reverse(BB)) {
5386 if (makeBitReverse(I, *DL, *TLI)) {
5387 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005388 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005389 break;
5390 }
5391 }
5392 }
James Molloy3ef84c42016-01-15 10:36:01 +00005393 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005394
Chris Lattnerf2836d12007-03-31 04:06:36 +00005395 return MadeChange;
5396}
Devang Patel53771ba2011-08-18 00:50:51 +00005397
5398// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005399// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005400// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005401bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005402 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005403 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005404 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005405 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005406 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005407 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005408 // Leave dbg.values that refer to an alloca alone. These
5409 // instrinsics describe the address of a variable (= the alloca)
5410 // being taken. They should not be moved next to the alloca
5411 // (and to the beginning of the scope), but rather stay close to
5412 // where said address is used.
5413 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005414 PrevNonDbgInst = Insn;
5415 continue;
5416 }
5417
5418 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5419 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005420 // If VI is a phi in a block with an EHPad terminator, we can't insert
5421 // after it.
5422 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5423 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005424 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5425 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005426 if (isa<PHINode>(VI))
5427 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5428 else
5429 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005430 MadeChange = true;
5431 ++NumDbgValueMoved;
5432 }
5433 }
5434 }
5435 return MadeChange;
5436}
Tim Northovercea0abb2014-03-29 08:22:29 +00005437
5438// If there is a sequence that branches based on comparing a single bit
5439// against zero that can be combined into a single instruction, and the
5440// target supports folding these into a single instruction, sink the
5441// mask and compare into the branch uses. Do this before OptimizeBlock ->
5442// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5443// searched for.
5444bool CodeGenPrepare::sinkAndCmp(Function &F) {
5445 if (!EnableAndCmpSinking)
5446 return false;
5447 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5448 return false;
5449 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005450 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005451 // Does this BB end with the following?
5452 // %andVal = and %val, #single-bit-set
5453 // %icmpVal = icmp %andResult, 0
5454 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005455 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005456 if (!Brcc || !Brcc->isConditional())
5457 continue;
5458 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005459 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005460 continue;
5461 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5462 if (!Zero || !Zero->isZero())
5463 continue;
5464 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005465 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005466 continue;
5467 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5468 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5469 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005470 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005471
5472 // Push the "and; icmp" for any users that are conditional branches.
5473 // Since there can only be one branch use per BB, we don't need to keep
5474 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005475 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005476 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005477 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005478 if (!BrccUser || !BrccUser->isConditional())
5479 continue;
5480 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005481 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005482 DEBUG(dbgs() << "found Brcc use\n");
5483
5484 // Sink the "and; icmp" to use.
5485 MadeChange = true;
5486 BinaryOperator *NewAnd =
5487 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5488 BrccUser);
5489 CmpInst *NewCmp =
5490 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5491 "", BrccUser);
5492 TheUse = NewCmp;
5493 ++NumAndCmpsMoved;
5494 DEBUG(BrccUser->getParent()->dump());
5495 }
5496 }
5497 return MadeChange;
5498}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005499
5500/// \brief Scale down both weights to fit into uint32_t.
5501static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5502 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5503 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5504 NewTrue = NewTrue / Scale;
5505 NewFalse = NewFalse / Scale;
5506}
5507
5508/// \brief Some targets prefer to split a conditional branch like:
5509/// \code
5510/// %0 = icmp ne i32 %a, 0
5511/// %1 = icmp ne i32 %b, 0
5512/// %or.cond = or i1 %0, %1
5513/// br i1 %or.cond, label %TrueBB, label %FalseBB
5514/// \endcode
5515/// into multiple branch instructions like:
5516/// \code
5517/// bb1:
5518/// %0 = icmp ne i32 %a, 0
5519/// br i1 %0, label %TrueBB, label %bb2
5520/// bb2:
5521/// %1 = icmp ne i32 %b, 0
5522/// br i1 %1, label %TrueBB, label %FalseBB
5523/// \endcode
5524/// This usually allows instruction selection to do even further optimizations
5525/// and combine the compare with the branch instruction. Currently this is
5526/// applied for targets which have "cheap" jump instructions.
5527///
5528/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5529///
5530bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005531 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005532 return false;
5533
5534 bool MadeChange = false;
5535 for (auto &BB : F) {
5536 // Does this BB end with the following?
5537 // %cond1 = icmp|fcmp|binary instruction ...
5538 // %cond2 = icmp|fcmp|binary instruction ...
5539 // %cond.or = or|and i1 %cond1, cond2
5540 // br i1 %cond.or label %dest1, label %dest2"
5541 BinaryOperator *LogicOp;
5542 BasicBlock *TBB, *FBB;
5543 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5544 continue;
5545
Sanjay Patel42574202015-09-02 19:23:23 +00005546 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5547 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5548 continue;
5549
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005550 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005551 Value *Cond1, *Cond2;
5552 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5553 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005554 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005555 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5556 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005557 Opc = Instruction::Or;
5558 else
5559 continue;
5560
5561 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5562 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5563 continue;
5564
5565 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5566
5567 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005568 auto TmpBB =
5569 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5570 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005571
5572 // Update original basic block by using the first condition directly by the
5573 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005574 Br1->setCondition(Cond1);
5575 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005576
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005577 // Depending on the conditon we have to either replace the true or the false
5578 // successor of the original branch instruction.
5579 if (Opc == Instruction::And)
5580 Br1->setSuccessor(0, TmpBB);
5581 else
5582 Br1->setSuccessor(1, TmpBB);
5583
5584 // Fill in the new basic block.
5585 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005586 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5587 I->removeFromParent();
5588 I->insertBefore(Br2);
5589 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005590
5591 // Update PHI nodes in both successors. The original BB needs to be
5592 // replaced in one succesor's PHI nodes, because the branch comes now from
5593 // the newly generated BB (NewBB). In the other successor we need to add one
5594 // incoming edge to the PHI nodes, because both branch instructions target
5595 // now the same successor. Depending on the original branch condition
5596 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5597 // we perfrom the correct update for the PHI nodes.
5598 // This doesn't change the successor order of the just created branch
5599 // instruction (or any other instruction).
5600 if (Opc == Instruction::Or)
5601 std::swap(TBB, FBB);
5602
5603 // Replace the old BB with the new BB.
5604 for (auto &I : *TBB) {
5605 PHINode *PN = dyn_cast<PHINode>(&I);
5606 if (!PN)
5607 break;
5608 int i;
5609 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5610 PN->setIncomingBlock(i, TmpBB);
5611 }
5612
5613 // Add another incoming edge form the new BB.
5614 for (auto &I : *FBB) {
5615 PHINode *PN = dyn_cast<PHINode>(&I);
5616 if (!PN)
5617 break;
5618 auto *Val = PN->getIncomingValueForBlock(&BB);
5619 PN->addIncoming(Val, TmpBB);
5620 }
5621
5622 // Update the branch weights (from SelectionDAGBuilder::
5623 // FindMergedConditions).
5624 if (Opc == Instruction::Or) {
5625 // Codegen X | Y as:
5626 // BB1:
5627 // jmp_if_X TBB
5628 // jmp TmpBB
5629 // TmpBB:
5630 // jmp_if_Y TBB
5631 // jmp FBB
5632 //
5633
5634 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5635 // The requirement is that
5636 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5637 // = TrueProb for orignal BB.
5638 // Assuming the orignal weights are A and B, one choice is to set BB1's
5639 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5640 // assumes that
5641 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5642 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5643 // TmpBB, but the math is more complicated.
5644 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005645 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005646 uint64_t NewTrueWeight = TrueWeight;
5647 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5648 scaleWeights(NewTrueWeight, NewFalseWeight);
5649 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5650 .createBranchWeights(TrueWeight, FalseWeight));
5651
5652 NewTrueWeight = TrueWeight;
5653 NewFalseWeight = 2 * FalseWeight;
5654 scaleWeights(NewTrueWeight, NewFalseWeight);
5655 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5656 .createBranchWeights(TrueWeight, FalseWeight));
5657 }
5658 } else {
5659 // Codegen X & Y as:
5660 // BB1:
5661 // jmp_if_X TmpBB
5662 // jmp FBB
5663 // TmpBB:
5664 // jmp_if_Y TBB
5665 // jmp FBB
5666 //
5667 // This requires creation of TmpBB after CurBB.
5668
5669 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5670 // The requirement is that
5671 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5672 // = FalseProb for orignal BB.
5673 // Assuming the orignal weights are A and B, one choice is to set BB1's
5674 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5675 // assumes that
5676 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5677 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005678 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005679 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5680 uint64_t NewFalseWeight = FalseWeight;
5681 scaleWeights(NewTrueWeight, NewFalseWeight);
5682 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5683 .createBranchWeights(TrueWeight, FalseWeight));
5684
5685 NewTrueWeight = 2 * TrueWeight;
5686 NewFalseWeight = FalseWeight;
5687 scaleWeights(NewTrueWeight, NewFalseWeight);
5688 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5689 .createBranchWeights(TrueWeight, FalseWeight));
5690 }
5691 }
5692
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005693 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005694 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005695 ModifiedDT = true;
5696
5697 MadeChange = true;
5698
5699 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5700 TmpBB->dump());
5701 }
5702 return MadeChange;
5703}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005704
5705void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005706 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005707 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5708}