blob: 894cc814a01a52b92d78bb148b8102d4db5a2807 [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"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000024#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000030#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000035#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000037#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000038#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000039#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000040#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000041#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000042#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000044#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000045#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000048#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000050#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000051using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000052using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000053
Chandler Carruth1b9dde02014-04-22 02:02:50 +000054#define DEBUG_TYPE "codegenprepare"
55
Cameron Zwarichced753f2011-01-05 17:27:27 +000056STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000057STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
58STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000059STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
60 "sunken Cmps");
61STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
62 "of sunken Casts");
63STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
64 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000065STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
66STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
67STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000068STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000069STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000070STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000071STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000072
Cameron Zwarich338d3622011-03-11 21:52:04 +000073static cl::opt<bool> DisableBranchOpts(
74 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
75 cl::desc("Disable branch optimizations in CodeGenPrepare"));
76
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000077static cl::opt<bool>
78 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
79 cl::desc("Disable GC optimizations in CodeGenPrepare"));
80
Benjamin Kramer3d38c172012-05-06 14:25:16 +000081static cl::opt<bool> DisableSelectToBranch(
82 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
83 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000084
Hal Finkelc3998302014-04-12 00:59:48 +000085static cl::opt<bool> AddrSinkUsingGEPs(
86 "addr-sink-using-gep", cl::Hidden, cl::init(false),
87 cl::desc("Address sinking in CGP using GEPs."));
88
Tim Northovercea0abb2014-03-29 08:22:29 +000089static cl::opt<bool> EnableAndCmpSinking(
90 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
91 cl::desc("Enable sinkinig and/cmp into branches."));
92
Quentin Colombetc32615d2014-10-31 17:52:53 +000093static cl::opt<bool> DisableStoreExtract(
94 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
95 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
96
97static cl::opt<bool> StressStoreExtract(
98 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
99 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
100
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000101static cl::opt<bool> DisableExtLdPromotion(
102 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
103 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
104 "CodeGenPrepare"));
105
106static cl::opt<bool> StressExtLdPromotion(
107 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
108 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
109 "optimization in CodeGenPrepare"));
110
Eric Christopherc1ea1492008-09-24 05:32:41 +0000111namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000112typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000113typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000114typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000115class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000116
Chris Lattner2dd09db2009-09-02 06:11:42 +0000117 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000118 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000119 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000120 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000121 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000122
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000123 /// As we scan instructions optimizing them, this is the next instruction
124 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000125 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000126
Evan Cheng0663f232011-03-21 01:19:09 +0000127 /// Keeps track of non-local addresses that have been sunk into a block.
128 /// This allows us to avoid inserting duplicate code for blocks with
129 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000130 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000131
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000132 /// Keeps track of all instructions inserted for the current function.
133 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000134 /// Keeps track of the type of the related instruction before their
135 /// promotion for the current function.
136 InstrToOrigTy PromotedInsts;
137
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000138 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000139 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000140
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000141 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000142 bool OptSize;
143
Mehdi Amini4fe37982015-07-07 18:45:17 +0000144 /// DataLayout for the Function being processed.
145 const DataLayout *DL;
146
Chris Lattnerf2836d12007-03-31 04:06:36 +0000147 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000148 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000149 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000150 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000151 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
152 }
Craig Topper4584cd52014-03-07 09:26:03 +0000153 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000154
Craig Topper4584cd52014-03-07 09:26:03 +0000155 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000156
Craig Topper4584cd52014-03-07 09:26:03 +0000157 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000158 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000159 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000160 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000161 }
162
Chris Lattnerf2836d12007-03-31 04:06:36 +0000163 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000164 bool eliminateFallThrough(Function &F);
165 bool eliminateMostlyEmptyBlocks(Function &F);
166 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
167 void eliminateMostlyEmptyBlock(BasicBlock *BB);
168 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
169 bool optimizeInst(Instruction *I, bool& ModifiedDT);
170 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000171 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000172 bool optimizeInlineAsmInst(CallInst *CS);
173 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
174 bool moveExtToFormExtLoad(Instruction *&I);
175 bool optimizeExtUses(Instruction *I);
176 bool optimizeSelectInst(SelectInst *SI);
177 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000178 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000179 bool optimizeExtractElementInst(Instruction *Inst);
180 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
181 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000182 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000183 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000184 Instruction *&Inst,
185 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000186 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000187 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000188 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000189 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000190 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000191}
Devang Patel09f162c2007-05-01 21:15:47 +0000192
Devang Patel8c78a0b2007-05-03 01:11:54 +0000193char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000194INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
195 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000196
Bill Wendling7a639ea2013-06-19 21:07:11 +0000197FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
198 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000199}
200
Chris Lattnerf2836d12007-03-31 04:06:36 +0000201bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000202 if (skipOptnoneFunction(F))
203 return false;
204
Mehdi Amini4fe37982015-07-07 18:45:17 +0000205 DL = &F.getParent()->getDataLayout();
206
Chris Lattnerf2836d12007-03-31 04:06:36 +0000207 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000208 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000209 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000210 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000211
Devang Patel8f606d72011-03-24 15:35:25 +0000212 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000213 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000214 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000215 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000216 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000217 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000218
Preston Gurdcdf540d2012-09-04 18:22:17 +0000219 /// This optimization identifies DIV instructions that can be
220 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000221 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000222 const DenseMap<unsigned int, unsigned int> &BypassWidths =
223 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000224 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000225 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000226 }
227
228 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000229 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000230 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000231
Devang Patel53771ba2011-08-18 00:50:51 +0000232 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000233 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000234 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000235 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000236
Tim Northovercea0abb2014-03-29 08:22:29 +0000237 // If there is a mask, compare against zero, and branch that can be combined
238 // into a single target instruction, push the mask and compare into branch
239 // users. Do this before OptimizeBlock -> OptimizeInst ->
240 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000241 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000242 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000243 EverMadeChange |= splitBranchCondition(F);
244 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000245
Chris Lattnerc3748562007-04-02 01:35:34 +0000246 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000247 while (MadeChange) {
248 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000249 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000250 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000251 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000252 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000253
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000254 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000255 if (ModifiedDTOnIteration)
256 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000257 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000258 EverMadeChange |= MadeChange;
259 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000260
261 SunkAddrs.clear();
262
Cameron Zwarich338d3622011-03-11 21:52:04 +0000263 if (!DisableBranchOpts) {
264 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000265 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000266 for (BasicBlock &BB : F) {
267 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
268 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000269 if (!MadeChange) continue;
270
271 for (SmallVectorImpl<BasicBlock*>::iterator
272 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
273 if (pred_begin(*II) == pred_end(*II))
274 WorkList.insert(*II);
275 }
276
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000277 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000278 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000279 while (!WorkList.empty()) {
280 BasicBlock *BB = *WorkList.begin();
281 WorkList.erase(BB);
282 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
283
284 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000285
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000286 for (SmallVectorImpl<BasicBlock*>::iterator
287 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
288 if (pred_begin(*II) == pred_end(*II))
289 WorkList.insert(*II);
290 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000291
Nadav Rotem70409992012-08-14 05:19:07 +0000292 // Merge pairs of basic blocks with unconditional branches, connected by
293 // a single edge.
294 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000295 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000296
Cameron Zwarich338d3622011-03-11 21:52:04 +0000297 EverMadeChange |= MadeChange;
298 }
299
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000300 if (!DisableGCOpts) {
301 SmallVector<Instruction *, 2> Statepoints;
302 for (BasicBlock &BB : F)
303 for (Instruction &I : BB)
304 if (isStatepoint(I))
305 Statepoints.push_back(&I);
306 for (auto &I : Statepoints)
307 EverMadeChange |= simplifyOffsetableRelocate(*I);
308 }
309
Chris Lattnerf2836d12007-03-31 04:06:36 +0000310 return EverMadeChange;
311}
312
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000313/// Merge basic blocks which are connected by a single edge, where one of the
314/// basic blocks has a single successor pointing to the other basic block,
315/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000316bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000317 bool Changed = false;
318 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000319 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000320 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000321 // If the destination block has a single pred, then this is a trivial
322 // edge, just collapse it.
323 BasicBlock *SinglePred = BB->getSinglePredecessor();
324
Evan Cheng64a223a2012-09-28 23:58:57 +0000325 // Don't merge if BB's address is taken.
326 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000327
328 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
329 if (Term && !Term->isConditional()) {
330 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000331 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000332 // Remember if SinglePred was the entry block of the function.
333 // If so, we will need to move BB back to the entry position.
334 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000335 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000336
337 if (isEntry && BB != &BB->getParent()->getEntryBlock())
338 BB->moveBefore(&BB->getParent()->getEntryBlock());
339
340 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000341 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000342 }
343 }
344 return Changed;
345}
346
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000347/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
348/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
349/// edges in ways that are non-optimal for isel. Start by eliminating these
350/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000351bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000352 bool MadeChange = false;
353 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000354 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000355 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000356
357 // If this block doesn't end with an uncond branch, ignore it.
358 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
359 if (!BI || !BI->isUnconditional())
360 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000361
Dale Johannesen4026b042009-03-27 01:13:37 +0000362 // If the instruction before the branch (skipping debug info) isn't a phi
363 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000364 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000365 if (BBI != BB->begin()) {
366 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000367 while (isa<DbgInfoIntrinsic>(BBI)) {
368 if (BBI == BB->begin())
369 break;
370 --BBI;
371 }
372 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
373 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000374 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000375
Chris Lattnerc3748562007-04-02 01:35:34 +0000376 // Do not break infinite loops.
377 BasicBlock *DestBB = BI->getSuccessor(0);
378 if (DestBB == BB)
379 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000380
Sanjay Patelfc580a62015-09-21 23:03:16 +0000381 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000382 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000383
Sanjay Patelfc580a62015-09-21 23:03:16 +0000384 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000385 MadeChange = true;
386 }
387 return MadeChange;
388}
389
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000390/// Return true if we can merge BB into DestBB if there is a single
391/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000392/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000393bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000394 const BasicBlock *DestBB) const {
395 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
396 // the successor. If there are more complex condition (e.g. preheaders),
397 // don't mess around with them.
398 BasicBlock::const_iterator BBI = BB->begin();
399 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000400 for (const User *U : PN->users()) {
401 const Instruction *UI = cast<Instruction>(U);
402 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000403 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000404 // If User is inside DestBB block and it is a PHINode then check
405 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000406 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000407 if (UI->getParent() == DestBB) {
408 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000409 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
410 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
411 if (Insn && Insn->getParent() == BB &&
412 Insn->getParent() != UPN->getIncomingBlock(I))
413 return false;
414 }
415 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000416 }
417 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000418
Chris Lattnerc3748562007-04-02 01:35:34 +0000419 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
420 // and DestBB may have conflicting incoming values for the block. If so, we
421 // can't merge the block.
422 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
423 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000424
Chris Lattnerc3748562007-04-02 01:35:34 +0000425 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000426 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000427 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
428 // It is faster to get preds from a PHI than with pred_iterator.
429 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
430 BBPreds.insert(BBPN->getIncomingBlock(i));
431 } else {
432 BBPreds.insert(pred_begin(BB), pred_end(BB));
433 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000434
Chris Lattnerc3748562007-04-02 01:35:34 +0000435 // Walk the preds of DestBB.
436 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
437 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
438 if (BBPreds.count(Pred)) { // Common predecessor?
439 BBI = DestBB->begin();
440 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
441 const Value *V1 = PN->getIncomingValueForBlock(Pred);
442 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000443
Chris Lattnerc3748562007-04-02 01:35:34 +0000444 // If V2 is a phi node in BB, look up what the mapped value will be.
445 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
446 if (V2PN->getParent() == BB)
447 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000448
Chris Lattnerc3748562007-04-02 01:35:34 +0000449 // If there is a conflict, bail out.
450 if (V1 != V2) return false;
451 }
452 }
453 }
454
455 return true;
456}
457
458
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000459/// Eliminate a basic block that has only phi's and an unconditional branch in
460/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000461void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000462 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
463 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000464
David Greene74e2d492010-01-05 01:27:11 +0000465 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000466
Chris Lattnerc3748562007-04-02 01:35:34 +0000467 // If the destination block has a single pred, then this is a trivial edge,
468 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000469 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000470 if (SinglePred != DestBB) {
471 // Remember if SinglePred was the entry block of the function. If so, we
472 // will need to move BB back to the entry position.
473 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000474 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000475
Chris Lattner8a172da2008-11-28 19:54:49 +0000476 if (isEntry && BB != &BB->getParent()->getEntryBlock())
477 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000478
David Greene74e2d492010-01-05 01:27:11 +0000479 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000480 return;
481 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000483
Chris Lattnerc3748562007-04-02 01:35:34 +0000484 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
485 // to handle the new incoming edges it is about to have.
486 PHINode *PN;
487 for (BasicBlock::iterator BBI = DestBB->begin();
488 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
489 // Remove the incoming value for BB, and remember it.
490 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000491
Chris Lattnerc3748562007-04-02 01:35:34 +0000492 // Two options: either the InVal is a phi node defined in BB or it is some
493 // value that dominates BB.
494 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
495 if (InValPhi && InValPhi->getParent() == BB) {
496 // Add all of the input values of the input PHI as inputs of this phi.
497 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
498 PN->addIncoming(InValPhi->getIncomingValue(i),
499 InValPhi->getIncomingBlock(i));
500 } else {
501 // Otherwise, add one instance of the dominating value for each edge that
502 // we will be adding.
503 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
504 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
505 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
506 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000507 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
508 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000509 }
510 }
511 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000512
Chris Lattnerc3748562007-04-02 01:35:34 +0000513 // The PHIs are now updated, change everything that refers to BB to use
514 // DestBB and remove BB.
515 BB->replaceAllUsesWith(DestBB);
516 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000517 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000518
David Greene74e2d492010-01-05 01:27:11 +0000519 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000520}
521
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000522// Computes a map of base pointer relocation instructions to corresponding
523// derived pointer relocation instructions given a vector of all relocate calls
524static void computeBaseDerivedRelocateMap(
525 const SmallVectorImpl<User *> &AllRelocateCalls,
526 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
527 RelocateInstMap) {
528 // Collect information in two maps: one primarily for locating the base object
529 // while filling the second map; the second map is the final structure holding
530 // a mapping between Base and corresponding Derived relocate calls
531 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
532 for (auto &U : AllRelocateCalls) {
533 GCRelocateOperands ThisRelocate(U);
534 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000535 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
536 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000537 RelocateIdxMap.insert(std::make_pair(K, I));
538 }
539 for (auto &Item : RelocateIdxMap) {
540 std::pair<unsigned, unsigned> Key = Item.first;
541 if (Key.first == Key.second)
542 // Base relocation: nothing to insert
543 continue;
544
545 IntrinsicInst *I = Item.second;
546 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000547
548 // We're iterating over RelocateIdxMap so we cannot modify it.
549 auto MaybeBase = RelocateIdxMap.find(BaseKey);
550 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000551 // TODO: We might want to insert a new base object relocate and gep off
552 // that, if there are enough derived object relocates.
553 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000554
555 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000556 }
557}
558
559// Accepts a GEP and extracts the operands into a vector provided they're all
560// small integer constants
561static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
562 SmallVectorImpl<Value *> &OffsetV) {
563 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
564 // Only accept small constant integer operands
565 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
566 if (!Op || Op->getZExtValue() > 20)
567 return false;
568 }
569
570 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
571 OffsetV.push_back(GEP->getOperand(i));
572 return true;
573}
574
575// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
576// replace, computes a replacement, and affects it.
577static bool
578simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
579 const SmallVectorImpl<IntrinsicInst *> &Targets) {
580 bool MadeChange = false;
581 for (auto &ToReplace : Targets) {
582 GCRelocateOperands MasterRelocate(RelocatedBase);
583 GCRelocateOperands ThisRelocate(ToReplace);
584
Sanjoy Das499d7032015-05-06 02:36:26 +0000585 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000586 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000587 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000588 // A duplicate relocate call. TODO: coalesce duplicates.
589 continue;
590 }
591
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000592 if (RelocatedBase->getParent() != ToReplace->getParent()) {
593 // Base and derived relocates are in different basic blocks.
594 // In this case transform is only valid when base dominates derived
595 // relocate. However it would be too expensive to check dominance
596 // for each such relocate, so we skip the whole transformation.
597 continue;
598 }
599
Sanjoy Das499d7032015-05-06 02:36:26 +0000600 Value *Base = ThisRelocate.getBasePtr();
601 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000602 if (!Derived || Derived->getPointerOperand() != Base)
603 continue;
604
605 SmallVector<Value *, 2> OffsetV;
606 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
607 continue;
608
609 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000610 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
611
612 // Insert after RelocatedBase
613 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000614 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000615
616 // If gc_relocate does not match the actual type, cast it to the right type.
617 // In theory, there must be a bitcast after gc_relocate if the type does not
618 // match, and we should reuse it to get the derived pointer. But it could be
619 // cases like this:
620 // bb1:
621 // ...
622 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
623 // br label %merge
624 //
625 // bb2:
626 // ...
627 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
628 // br label %merge
629 //
630 // merge:
631 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
632 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
633 //
634 // In this case, we can not find the bitcast any more. So we insert a new bitcast
635 // no matter there is already one or not. In this way, we can handle all cases, and
636 // the extra bitcast should be optimized away in later passes.
637 Instruction *ActualRelocatedBase = RelocatedBase;
638 if (RelocatedBase->getType() != Base->getType()) {
639 ActualRelocatedBase =
640 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000641 }
David Blaikie68d535c2015-03-24 22:38:16 +0000642 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000643 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000644 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000645 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000646 // If the newly generated derived pointer's type does not match the original derived
647 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
648 Instruction *ActualReplacement = ReplacementInst;
649 if (ReplacementInst->getType() != ToReplace->getType()) {
650 ActualReplacement =
651 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000652 }
653 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000654 ToReplace->eraseFromParent();
655
656 MadeChange = true;
657 }
658 return MadeChange;
659}
660
661// Turns this:
662//
663// %base = ...
664// %ptr = gep %base + 15
665// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
666// %base' = relocate(%tok, i32 4, i32 4)
667// %ptr' = relocate(%tok, i32 4, i32 5)
668// %val = load %ptr'
669//
670// into this:
671//
672// %base = ...
673// %ptr = gep %base + 15
674// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
675// %base' = gc.relocate(%tok, i32 4, i32 4)
676// %ptr' = gep %base' + 15
677// %val = load %ptr'
678bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
679 bool MadeChange = false;
680 SmallVector<User *, 2> AllRelocateCalls;
681
682 for (auto *U : I.users())
683 if (isGCRelocate(dyn_cast<Instruction>(U)))
684 // Collect all the relocate calls associated with a statepoint
685 AllRelocateCalls.push_back(U);
686
687 // We need atleast one base pointer relocation + one derived pointer
688 // relocation to mangle
689 if (AllRelocateCalls.size() < 2)
690 return false;
691
692 // RelocateInstMap is a mapping from the base relocate instruction to the
693 // corresponding derived relocate instructions
694 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
695 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
696 if (RelocateInstMap.empty())
697 return false;
698
699 for (auto &Item : RelocateInstMap)
700 // Item.first is the RelocatedBase to offset against
701 // Item.second is the vector of Targets to replace
702 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
703 return MadeChange;
704}
705
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000706/// SinkCast - Sink the specified cast instruction into its user blocks
707static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000708 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000709
Chris Lattnerf2836d12007-03-31 04:06:36 +0000710 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000711 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000712
Chris Lattnerf2836d12007-03-31 04:06:36 +0000713 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000714 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000715 UI != E; ) {
716 Use &TheUse = UI.getUse();
717 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000718
Chris Lattnerf2836d12007-03-31 04:06:36 +0000719 // Figure out which BB this cast is used in. For PHI's this is the
720 // appropriate predecessor block.
721 BasicBlock *UserBB = User->getParent();
722 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000723 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000724 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000725
Chris Lattnerf2836d12007-03-31 04:06:36 +0000726 // Preincrement use iterator so we don't invalidate it.
727 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000728
Chris Lattnerf2836d12007-03-31 04:06:36 +0000729 // If this user is in the same block as the cast, don't change the cast.
730 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000731
Chris Lattnerf2836d12007-03-31 04:06:36 +0000732 // If we have already inserted a cast into this block, use it.
733 CastInst *&InsertedCast = InsertedCasts[UserBB];
734
735 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000736 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000737 assert(InsertPt != UserBB->end());
738 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
739 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000740 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000741
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000742 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000743 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000744 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000745 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000746 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000747
Chris Lattnerf2836d12007-03-31 04:06:36 +0000748 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000749 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000750 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000751 MadeChange = true;
752 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000753
Chris Lattnerf2836d12007-03-31 04:06:36 +0000754 return MadeChange;
755}
756
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000757/// If the specified cast instruction is a noop copy (e.g. it's casting from
758/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
759/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000760///
761/// Return true if any changes are made.
762///
Mehdi Amini44ede332015-07-09 02:09:04 +0000763static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
764 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000765 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000766 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
767 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000768
769 // This is an fp<->int conversion?
770 if (SrcVT.isInteger() != DstVT.isInteger())
771 return false;
772
773 // If this is an extension, it will be a zero or sign extension, which
774 // isn't a noop.
775 if (SrcVT.bitsLT(DstVT)) return false;
776
777 // If these values will be promoted, find out what they will be promoted
778 // to. This helps us consider truncates on PPC as noop copies when they
779 // are.
780 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
781 TargetLowering::TypePromoteInteger)
782 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
783 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
784 TargetLowering::TypePromoteInteger)
785 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
786
787 // If, after promotion, these are the same types, this is a noop copy.
788 if (SrcVT != DstVT)
789 return false;
790
791 return SinkCast(CI);
792}
793
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000794/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
795/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000796///
797/// Return true if any changes were made.
798static bool CombineUAddWithOverflow(CmpInst *CI) {
799 Value *A, *B;
800 Instruction *AddI;
801 if (!match(CI,
802 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
803 return false;
804
805 Type *Ty = AddI->getType();
806 if (!isa<IntegerType>(Ty))
807 return false;
808
809 // We don't want to move around uses of condition values this late, so we we
810 // check if it is legal to create the call to the intrinsic in the basic
811 // block containing the icmp:
812
813 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
814 return false;
815
816#ifndef NDEBUG
817 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
818 // for now:
819 if (AddI->hasOneUse())
820 assert(*AddI->user_begin() == CI && "expected!");
821#endif
822
823 Module *M = CI->getParent()->getParent()->getParent();
824 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
825
826 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
827
828 auto *UAddWithOverflow =
829 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
830 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
831 auto *Overflow =
832 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
833
834 CI->replaceAllUsesWith(Overflow);
835 AddI->replaceAllUsesWith(UAdd);
836 CI->eraseFromParent();
837 AddI->eraseFromParent();
838 return true;
839}
840
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000841/// Sink the given CmpInst into user blocks to reduce the number of virtual
842/// registers that must be created and coalesced. This is a clear win except on
843/// targets with multiple condition code registers (PowerPC), where it might
844/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000845///
846/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000847static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000848 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000849
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000850 /// Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000851 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000852
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000853 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000854 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000855 UI != E; ) {
856 Use &TheUse = UI.getUse();
857 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000858
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000859 // Preincrement use iterator so we don't invalidate it.
860 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000861
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000862 // Don't bother for PHI nodes.
863 if (isa<PHINode>(User))
864 continue;
865
866 // Figure out which BB this cmp is used in.
867 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000868
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000869 // If this user is in the same block as the cmp, don't change the cmp.
870 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000871
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000872 // If we have already inserted a cmp into this block, use it.
873 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
874
875 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000876 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000877 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000878 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000879 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
880 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000881 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000882
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000883 // Replace a use of the cmp with a use of the new cmp.
884 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000885 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000886 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000887 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000888
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000889 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000890 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000891 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000892 MadeChange = true;
893 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000894
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000895 return MadeChange;
896}
897
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000898static bool OptimizeCmpExpression(CmpInst *CI) {
899 if (SinkCmpExpression(CI))
900 return true;
901
902 if (CombineUAddWithOverflow(CI))
903 return true;
904
905 return false;
906}
907
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000908/// Check if the candidates could be combined with a shift instruction, which
909/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000910/// 1. Truncate instruction
911/// 2. And instruction and the imm is a mask of the low bits:
912/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000913static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000914 if (!isa<TruncInst>(User)) {
915 if (User->getOpcode() != Instruction::And ||
916 !isa<ConstantInt>(User->getOperand(1)))
917 return false;
918
Quentin Colombetd4f44692014-04-22 01:20:34 +0000919 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000920
Quentin Colombetd4f44692014-04-22 01:20:34 +0000921 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000922 return false;
923 }
924 return true;
925}
926
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000927/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000928static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000929SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
930 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000931 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000932 BasicBlock *UserBB = User->getParent();
933 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
934 TruncInst *TruncI = dyn_cast<TruncInst>(User);
935 bool MadeChange = false;
936
937 for (Value::user_iterator TruncUI = TruncI->user_begin(),
938 TruncE = TruncI->user_end();
939 TruncUI != TruncE;) {
940
941 Use &TruncTheUse = TruncUI.getUse();
942 Instruction *TruncUser = cast<Instruction>(*TruncUI);
943 // Preincrement use iterator so we don't invalidate it.
944
945 ++TruncUI;
946
947 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
948 if (!ISDOpcode)
949 continue;
950
Tim Northovere2239ff2014-07-29 10:20:22 +0000951 // If the use is actually a legal node, there will not be an
952 // implicit truncate.
953 // FIXME: always querying the result type is just an
954 // approximation; some nodes' legality is determined by the
955 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000956 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000957 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000958 continue;
959
960 // Don't bother for PHI nodes.
961 if (isa<PHINode>(TruncUser))
962 continue;
963
964 BasicBlock *TruncUserBB = TruncUser->getParent();
965
966 if (UserBB == TruncUserBB)
967 continue;
968
969 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
970 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
971
972 if (!InsertedShift && !InsertedTrunc) {
973 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000974 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000975 // Sink the shift
976 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000977 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
978 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000979 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000980 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
981 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000982
983 // Sink the trunc
984 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
985 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000986 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000987
988 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000989 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000990
991 MadeChange = true;
992
993 TruncTheUse = InsertedTrunc;
994 }
995 }
996 return MadeChange;
997}
998
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000999/// Sink the shift *right* instruction into user blocks if the uses could
1000/// potentially be combined with this shift instruction and generate BitExtract
1001/// instruction. It will only be applied if the architecture supports BitExtract
1002/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001003/// BB1:
1004/// %x.extract.shift = lshr i64 %arg1, 32
1005/// BB2:
1006/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1007/// ==>
1008///
1009/// BB2:
1010/// %x.extract.shift.1 = lshr i64 %arg1, 32
1011/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1012///
1013/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1014/// instruction.
1015/// Return true if any changes are made.
1016static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001017 const TargetLowering &TLI,
1018 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001019 BasicBlock *DefBB = ShiftI->getParent();
1020
1021 /// Only insert instructions in each block once.
1022 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1023
Mehdi Amini44ede332015-07-09 02:09:04 +00001024 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001025
1026 bool MadeChange = false;
1027 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1028 UI != E;) {
1029 Use &TheUse = UI.getUse();
1030 Instruction *User = cast<Instruction>(*UI);
1031 // Preincrement use iterator so we don't invalidate it.
1032 ++UI;
1033
1034 // Don't bother for PHI nodes.
1035 if (isa<PHINode>(User))
1036 continue;
1037
1038 if (!isExtractBitsCandidateUse(User))
1039 continue;
1040
1041 BasicBlock *UserBB = User->getParent();
1042
1043 if (UserBB == DefBB) {
1044 // If the shift and truncate instruction are in the same BB. The use of
1045 // the truncate(TruncUse) may still introduce another truncate if not
1046 // legal. In this case, we would like to sink both shift and truncate
1047 // instruction to the BB of TruncUse.
1048 // for example:
1049 // BB1:
1050 // i64 shift.result = lshr i64 opnd, imm
1051 // trunc.result = trunc shift.result to i16
1052 //
1053 // BB2:
1054 // ----> We will have an implicit truncate here if the architecture does
1055 // not have i16 compare.
1056 // cmp i16 trunc.result, opnd2
1057 //
1058 if (isa<TruncInst>(User) && shiftIsLegal
1059 // If the type of the truncate is legal, no trucate will be
1060 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001061 &&
1062 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001063 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001064 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001065
1066 continue;
1067 }
1068 // If we have already inserted a shift into this block, use it.
1069 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1070
1071 if (!InsertedShift) {
1072 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001073 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001074
1075 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001076 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1077 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001078 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001079 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1080 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001081
1082 MadeChange = true;
1083 }
1084
1085 // Replace a use of the shift with a use of the new shift.
1086 TheUse = InsertedShift;
1087 }
1088
1089 // If we removed all uses, nuke the shift.
1090 if (ShiftI->use_empty())
1091 ShiftI->eraseFromParent();
1092
1093 return MadeChange;
1094}
1095
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001096// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001097// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1098// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001099// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001100// the appropriate mask bit is set
1101//
1102// %1 = bitcast i8* %addr to i32*
1103// %2 = extractelement <16 x i1> %mask, i32 0
1104// %3 = icmp eq i1 %2, true
1105// br i1 %3, label %cond.load, label %else
1106//
1107//cond.load: ; preds = %0
1108// %4 = getelementptr i32* %1, i32 0
1109// %5 = load i32* %4
1110// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1111// br label %else
1112//
1113//else: ; preds = %0, %cond.load
1114// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1115// %7 = extractelement <16 x i1> %mask, i32 1
1116// %8 = icmp eq i1 %7, true
1117// br i1 %8, label %cond.load1, label %else2
1118//
1119//cond.load1: ; preds = %else
1120// %9 = getelementptr i32* %1, i32 1
1121// %10 = load i32* %9
1122// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1123// br label %else2
1124//
1125//else2: ; preds = %else, %cond.load1
1126// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1127// %12 = extractelement <16 x i1> %mask, i32 2
1128// %13 = icmp eq i1 %12, true
1129// br i1 %13, label %cond.load4, label %else5
1130//
1131static void ScalarizeMaskedLoad(CallInst *CI) {
1132 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001133 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001134 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001135 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001136
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001137 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1138 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001139 assert(VecType && "Unexpected return type of masked load intrinsic");
1140
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001141 Type *EltTy = CI->getType()->getVectorElementType();
1142
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001143 IRBuilder<> Builder(CI->getContext());
1144 Instruction *InsertPt = CI;
1145 BasicBlock *IfBlock = CI->getParent();
1146 BasicBlock *CondBlock = nullptr;
1147 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001148
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001149 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001150 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1151
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001152 // Short-cut if the mask is all-true.
1153 bool IsAllOnesMask = isa<Constant>(Mask) &&
1154 cast<Constant>(Mask)->isAllOnesValue();
1155
1156 if (IsAllOnesMask) {
1157 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1158 CI->replaceAllUsesWith(NewI);
1159 CI->eraseFromParent();
1160 return;
1161 }
1162
1163 // Adjust alignment for the scalar instruction.
1164 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001165 // Bitcast %addr fron i8* to EltTy*
1166 Type *NewPtrType =
1167 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1168 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001169 unsigned VectorWidth = VecType->getNumElements();
1170
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001171 Value *UndefVal = UndefValue::get(VecType);
1172
1173 // The result vector
1174 Value *VResult = UndefVal;
1175
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001176 if (isa<ConstantVector>(Mask)) {
1177 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1178 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1179 continue;
1180 Value *Gep =
1181 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1182 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1183 VResult = Builder.CreateInsertElement(VResult, Load,
1184 Builder.getInt32(Idx));
1185 }
1186 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1187 CI->replaceAllUsesWith(NewI);
1188 CI->eraseFromParent();
1189 return;
1190 }
1191
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001192 PHINode *Phi = nullptr;
1193 Value *PrevPhi = UndefVal;
1194
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001195 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1196
1197 // Fill the "else" block, created in the previous iteration
1198 //
1199 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1200 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1201 // %to_load = icmp eq i1 %mask_1, true
1202 // br i1 %to_load, label %cond.load, label %else
1203 //
1204 if (Idx > 0) {
1205 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1206 Phi->addIncoming(VResult, CondBlock);
1207 Phi->addIncoming(PrevPhi, PrevIfBlock);
1208 PrevPhi = Phi;
1209 VResult = Phi;
1210 }
1211
1212 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1213 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1214 ConstantInt::get(Predicate->getType(), 1));
1215
1216 // Create "cond" block
1217 //
1218 // %EltAddr = getelementptr i32* %1, i32 0
1219 // %Elt = load i32* %EltAddr
1220 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1221 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001222 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001223 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001224
1225 Value *Gep =
1226 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001227 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001228 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1229
1230 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001231 BasicBlock *NewIfBlock =
1232 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001233 Builder.SetInsertPoint(InsertPt);
1234 Instruction *OldBr = IfBlock->getTerminator();
1235 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1236 OldBr->eraseFromParent();
1237 PrevIfBlock = IfBlock;
1238 IfBlock = NewIfBlock;
1239 }
1240
1241 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1242 Phi->addIncoming(VResult, CondBlock);
1243 Phi->addIncoming(PrevPhi, PrevIfBlock);
1244 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1245 CI->replaceAllUsesWith(NewI);
1246 CI->eraseFromParent();
1247}
1248
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001249// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001250// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1251// <16 x i1> %mask)
1252// to a chain of basic blocks, that stores element one-by-one if
1253// the appropriate mask bit is set
1254//
1255// %1 = bitcast i8* %addr to i32*
1256// %2 = extractelement <16 x i1> %mask, i32 0
1257// %3 = icmp eq i1 %2, true
1258// br i1 %3, label %cond.store, label %else
1259//
1260// cond.store: ; preds = %0
1261// %4 = extractelement <16 x i32> %val, i32 0
1262// %5 = getelementptr i32* %1, i32 0
1263// store i32 %4, i32* %5
1264// br label %else
1265//
1266// else: ; preds = %0, %cond.store
1267// %6 = extractelement <16 x i1> %mask, i32 1
1268// %7 = icmp eq i1 %6, true
1269// br i1 %7, label %cond.store1, label %else2
1270//
1271// cond.store1: ; preds = %else
1272// %8 = extractelement <16 x i32> %val, i32 1
1273// %9 = getelementptr i32* %1, i32 1
1274// store i32 %8, i32* %9
1275// br label %else2
1276// . . .
1277static void ScalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001278 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001279 Value *Ptr = CI->getArgOperand(1);
1280 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001281 Value *Mask = CI->getArgOperand(3);
1282
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001283 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001284 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001285 assert(VecType && "Unexpected data type in masked store intrinsic");
1286
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001287 Type *EltTy = VecType->getElementType();
1288
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001289 IRBuilder<> Builder(CI->getContext());
1290 Instruction *InsertPt = CI;
1291 BasicBlock *IfBlock = CI->getParent();
1292 Builder.SetInsertPoint(InsertPt);
1293 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1294
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001295 // Short-cut if the mask is all-true.
1296 bool IsAllOnesMask = isa<Constant>(Mask) &&
1297 cast<Constant>(Mask)->isAllOnesValue();
1298
1299 if (IsAllOnesMask) {
1300 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1301 CI->eraseFromParent();
1302 return;
1303 }
1304
1305 // Adjust alignment for the scalar instruction.
1306 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001307 // Bitcast %addr fron i8* to EltTy*
1308 Type *NewPtrType =
1309 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1310 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001311 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001312
1313 if (isa<ConstantVector>(Mask)) {
1314 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1315 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1316 continue;
1317 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1318 Value *Gep =
1319 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1320 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1321 }
1322 CI->eraseFromParent();
1323 return;
1324 }
1325
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001326 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1327
1328 // Fill the "else" block, created in the previous iteration
1329 //
1330 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1331 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001332 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001333 //
1334 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1335 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1336 ConstantInt::get(Predicate->getType(), 1));
1337
1338 // Create "cond" block
1339 //
1340 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1341 // %EltAddr = getelementptr i32* %1, i32 0
1342 // %store i32 %OneElt, i32* %EltAddr
1343 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001344 BasicBlock *CondBlock =
1345 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001346 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001347
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001348 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001349 Value *Gep =
1350 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001351 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001352
1353 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001354 BasicBlock *NewIfBlock =
1355 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001356 Builder.SetInsertPoint(InsertPt);
1357 Instruction *OldBr = IfBlock->getTerminator();
1358 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1359 OldBr->eraseFromParent();
1360 IfBlock = NewIfBlock;
1361 }
1362 CI->eraseFromParent();
1363}
1364
Elena Demikhovsky09285852015-10-25 15:37:55 +00001365// Translate a masked gather intrinsic like
1366// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1367// <16 x i1> %Mask, <16 x i32> %Src)
1368// to a chain of basic blocks, with loading element one-by-one if
1369// the appropriate mask bit is set
1370//
1371// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1372// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1373// % ToLoad0 = icmp eq i1 % Mask0, true
1374// br i1 % ToLoad0, label %cond.load, label %else
1375//
1376// cond.load:
1377// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1378// % Load0 = load i32, i32* % Ptr0, align 4
1379// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1380// br label %else
1381//
1382// else:
1383// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1384// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1385// % ToLoad1 = icmp eq i1 % Mask1, true
1386// br i1 % ToLoad1, label %cond.load1, label %else2
1387//
1388// cond.load1:
1389// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1390// % Load1 = load i32, i32* % Ptr1, align 4
1391// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1392// br label %else2
1393// . . .
1394// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1395// ret <16 x i32> %Result
1396static void ScalarizeMaskedGather(CallInst *CI) {
1397 Value *Ptrs = CI->getArgOperand(0);
1398 Value *Alignment = CI->getArgOperand(1);
1399 Value *Mask = CI->getArgOperand(2);
1400 Value *Src0 = CI->getArgOperand(3);
1401
1402 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1403
1404 assert(VecType && "Unexpected return type of masked load intrinsic");
1405
1406 IRBuilder<> Builder(CI->getContext());
1407 Instruction *InsertPt = CI;
1408 BasicBlock *IfBlock = CI->getParent();
1409 BasicBlock *CondBlock = nullptr;
1410 BasicBlock *PrevIfBlock = CI->getParent();
1411 Builder.SetInsertPoint(InsertPt);
1412 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1413
1414 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1415
1416 Value *UndefVal = UndefValue::get(VecType);
1417
1418 // The result vector
1419 Value *VResult = UndefVal;
1420 unsigned VectorWidth = VecType->getNumElements();
1421
1422 // Shorten the way if the mask is a vector of constants.
1423 bool IsConstMask = isa<ConstantVector>(Mask);
1424
1425 if (IsConstMask) {
1426 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1427 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1428 continue;
1429 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1430 "Ptr" + Twine(Idx));
1431 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1432 "Load" + Twine(Idx));
1433 VResult = Builder.CreateInsertElement(VResult, Load,
1434 Builder.getInt32(Idx),
1435 "Res" + Twine(Idx));
1436 }
1437 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1438 CI->replaceAllUsesWith(NewI);
1439 CI->eraseFromParent();
1440 return;
1441 }
1442
1443 PHINode *Phi = nullptr;
1444 Value *PrevPhi = UndefVal;
1445
1446 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1447
1448 // Fill the "else" block, created in the previous iteration
1449 //
1450 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1451 // %ToLoad1 = icmp eq i1 %Mask1, true
1452 // br i1 %ToLoad1, label %cond.load, label %else
1453 //
1454 if (Idx > 0) {
1455 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1456 Phi->addIncoming(VResult, CondBlock);
1457 Phi->addIncoming(PrevPhi, PrevIfBlock);
1458 PrevPhi = Phi;
1459 VResult = Phi;
1460 }
1461
1462 Value *Predicate = Builder.CreateExtractElement(Mask,
1463 Builder.getInt32(Idx),
1464 "Mask" + Twine(Idx));
1465 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1466 ConstantInt::get(Predicate->getType(), 1),
1467 "ToLoad" + Twine(Idx));
1468
1469 // Create "cond" block
1470 //
1471 // %EltAddr = getelementptr i32* %1, i32 0
1472 // %Elt = load i32* %EltAddr
1473 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1474 //
1475 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1476 Builder.SetInsertPoint(InsertPt);
1477
1478 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1479 "Ptr" + Twine(Idx));
1480 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1481 "Load" + Twine(Idx));
1482 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1483 "Res" + Twine(Idx));
1484
1485 // Create "else" block, fill it in the next iteration
1486 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1487 Builder.SetInsertPoint(InsertPt);
1488 Instruction *OldBr = IfBlock->getTerminator();
1489 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1490 OldBr->eraseFromParent();
1491 PrevIfBlock = IfBlock;
1492 IfBlock = NewIfBlock;
1493 }
1494
1495 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1496 Phi->addIncoming(VResult, CondBlock);
1497 Phi->addIncoming(PrevPhi, PrevIfBlock);
1498 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1499 CI->replaceAllUsesWith(NewI);
1500 CI->eraseFromParent();
1501}
1502
1503// Translate a masked scatter intrinsic, like
1504// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1505// <16 x i1> %Mask)
1506// to a chain of basic blocks, that stores element one-by-one if
1507// the appropriate mask bit is set.
1508//
1509// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1510// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1511// % ToStore0 = icmp eq i1 % Mask0, true
1512// br i1 %ToStore0, label %cond.store, label %else
1513//
1514// cond.store:
1515// % Elt0 = extractelement <16 x i32> %Src, i32 0
1516// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1517// store i32 %Elt0, i32* % Ptr0, align 4
1518// br label %else
1519//
1520// else:
1521// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1522// % ToStore1 = icmp eq i1 % Mask1, true
1523// br i1 % ToStore1, label %cond.store1, label %else2
1524//
1525// cond.store1:
1526// % Elt1 = extractelement <16 x i32> %Src, i32 1
1527// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1528// store i32 % Elt1, i32* % Ptr1, align 4
1529// br label %else2
1530// . . .
1531static void ScalarizeMaskedScatter(CallInst *CI) {
1532 Value *Src = CI->getArgOperand(0);
1533 Value *Ptrs = CI->getArgOperand(1);
1534 Value *Alignment = CI->getArgOperand(2);
1535 Value *Mask = CI->getArgOperand(3);
1536
1537 assert(isa<VectorType>(Src->getType()) &&
1538 "Unexpected data type in masked scatter intrinsic");
1539 assert(isa<VectorType>(Ptrs->getType()) &&
1540 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1541 "Vector of pointers is expected in masked scatter intrinsic");
1542
1543 IRBuilder<> Builder(CI->getContext());
1544 Instruction *InsertPt = CI;
1545 BasicBlock *IfBlock = CI->getParent();
1546 Builder.SetInsertPoint(InsertPt);
1547 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1548
1549 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1550 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1551
1552 // Shorten the way if the mask is a vector of constants.
1553 bool IsConstMask = isa<ConstantVector>(Mask);
1554
1555 if (IsConstMask) {
1556 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1557 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1558 continue;
1559 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1560 "Elt" + Twine(Idx));
1561 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1562 "Ptr" + Twine(Idx));
1563 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1564 }
1565 CI->eraseFromParent();
1566 return;
1567 }
1568 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1569 // Fill the "else" block, created in the previous iteration
1570 //
1571 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1572 // % ToStore = icmp eq i1 % Mask1, true
1573 // br i1 % ToStore, label %cond.store, label %else
1574 //
1575 Value *Predicate = Builder.CreateExtractElement(Mask,
1576 Builder.getInt32(Idx),
1577 "Mask" + Twine(Idx));
1578 Value *Cmp =
1579 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1580 ConstantInt::get(Predicate->getType(), 1),
1581 "ToStore" + Twine(Idx));
1582
1583 // Create "cond" block
1584 //
1585 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1586 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1587 // %store i32 % Elt1, i32* % Ptr1
1588 //
1589 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1590 Builder.SetInsertPoint(InsertPt);
1591
1592 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1593 "Elt" + Twine(Idx));
1594 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1595 "Ptr" + Twine(Idx));
1596 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1597
1598 // Create "else" block, fill it in the next iteration
1599 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1600 Builder.SetInsertPoint(InsertPt);
1601 Instruction *OldBr = IfBlock->getTerminator();
1602 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1603 OldBr->eraseFromParent();
1604 IfBlock = NewIfBlock;
1605 }
1606 CI->eraseFromParent();
1607}
1608
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001609/// If counting leading or trailing zeros is an expensive operation and a zero
1610/// input is defined, add a check for zero to avoid calling the intrinsic.
1611///
1612/// We want to transform:
1613/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1614///
1615/// into:
1616/// entry:
1617/// %cmpz = icmp eq i64 %A, 0
1618/// br i1 %cmpz, label %cond.end, label %cond.false
1619/// cond.false:
1620/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1621/// br label %cond.end
1622/// cond.end:
1623/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1624///
1625/// If the transform is performed, return true and set ModifiedDT to true.
1626static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1627 const TargetLowering *TLI,
1628 const DataLayout *DL,
1629 bool &ModifiedDT) {
1630 if (!TLI || !DL)
1631 return false;
1632
1633 // If a zero input is undefined, it doesn't make sense to despeculate that.
1634 if (match(CountZeros->getOperand(1), m_One()))
1635 return false;
1636
1637 // If it's cheap to speculate, there's nothing to do.
1638 auto IntrinsicID = CountZeros->getIntrinsicID();
1639 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1640 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1641 return false;
1642
1643 // Only handle legal scalar cases. Anything else requires too much work.
1644 Type *Ty = CountZeros->getType();
1645 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1646 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
1647 return false;
1648
1649 // The intrinsic will be sunk behind a compare against zero and branch.
1650 BasicBlock *StartBlock = CountZeros->getParent();
1651 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1652
1653 // Create another block after the count zero intrinsic. A PHI will be added
1654 // in this block to select the result of the intrinsic or the bit-width
1655 // constant if the input to the intrinsic is zero.
1656 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1657 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1658
1659 // Set up a builder to create a compare, conditional branch, and PHI.
1660 IRBuilder<> Builder(CountZeros->getContext());
1661 Builder.SetInsertPoint(StartBlock->getTerminator());
1662 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1663
1664 // Replace the unconditional branch that was created by the first split with
1665 // a compare against zero and a conditional branch.
1666 Value *Zero = Constant::getNullValue(Ty);
1667 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1668 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1669 StartBlock->getTerminator()->eraseFromParent();
1670
1671 // Create a PHI in the end block to select either the output of the intrinsic
1672 // or the bit width of the operand.
1673 Builder.SetInsertPoint(&EndBlock->front());
1674 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1675 CountZeros->replaceAllUsesWith(PN);
1676 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1677 PN->addIncoming(BitWidth, StartBlock);
1678 PN->addIncoming(CountZeros, CallBlock);
1679
1680 // We are explicitly handling the zero case, so we can set the intrinsic's
1681 // undefined zero argument to 'true'. This will also prevent reprocessing the
1682 // intrinsic; we only despeculate when a zero input is defined.
1683 CountZeros->setArgOperand(1, Builder.getTrue());
1684 ModifiedDT = true;
1685 return true;
1686}
1687
Sanjay Patelfc580a62015-09-21 23:03:16 +00001688bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001689 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001690
Chris Lattner7a277142011-01-15 07:14:54 +00001691 // Lower inline assembly if we can.
1692 // If we found an inline asm expession, and if the target knows how to
1693 // lower it to normal LLVM code, do so now.
1694 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1695 if (TLI->ExpandInlineAsm(CI)) {
1696 // Avoid invalidating the iterator.
1697 CurInstIterator = BB->begin();
1698 // Avoid processing instructions out of order, which could cause
1699 // reuse before a value is defined.
1700 SunkAddrs.clear();
1701 return true;
1702 }
1703 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001704 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001705 return true;
1706 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001707
John Brawn0dbcd652015-03-18 12:01:59 +00001708 // Align the pointer arguments to this call if the target thinks it's a good
1709 // idea
1710 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001711 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001712 for (auto &Arg : CI->arg_operands()) {
1713 // We want to align both objects whose address is used directly and
1714 // objects whose address is used in casts and GEPs, though it only makes
1715 // sense for GEPs if the offset is a multiple of the desired alignment and
1716 // if size - offset meets the size threshold.
1717 if (!Arg->getType()->isPointerTy())
1718 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001719 APInt Offset(DL->getPointerSizeInBits(
1720 cast<PointerType>(Arg->getType())->getAddressSpace()),
1721 0);
1722 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001723 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001724 if ((Offset2 & (PrefAlign-1)) != 0)
1725 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001726 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001727 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1728 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001729 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001730 // Global variables can only be aligned if they are defined in this
1731 // object (i.e. they are uniquely initialized in this object), and
1732 // over-aligning global variables that have an explicit section is
1733 // forbidden.
1734 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001735 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1736 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1737 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1738 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001739 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001740 }
1741 // If this is a memcpy (or similar) then we may be able to improve the
1742 // alignment
1743 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001744 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001745 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001746 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001747 if (Align > MI->getAlignment())
1748 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001749 }
1750 }
1751
Eric Christopher4b7948e2010-03-11 02:41:03 +00001752 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001753 if (II) {
1754 switch (II->getIntrinsicID()) {
1755 default: break;
1756 case Intrinsic::objectsize: {
1757 // Lower all uses of llvm.objectsize.*
1758 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1759 Type *ReturnTy = CI->getType();
1760 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001761
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001762 // Substituting this can cause recursive simplifications, which can
1763 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1764 // happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001765 WeakVH IterHandle(&*CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001766
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001767 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001768 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001769
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001770 // If the iterator instruction was recursively deleted, start over at the
1771 // start of the block.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001772 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001773 CurInstIterator = BB->begin();
1774 SunkAddrs.clear();
1775 }
1776 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001777 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001778 case Intrinsic::masked_load: {
1779 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001780 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001781 ScalarizeMaskedLoad(CI);
1782 ModifiedDT = true;
1783 return true;
1784 }
1785 return false;
1786 }
1787 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001788 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001789 ScalarizeMaskedStore(CI);
1790 ModifiedDT = true;
1791 return true;
1792 }
1793 return false;
1794 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001795 case Intrinsic::masked_gather: {
1796 if (!TTI->isLegalMaskedGather(CI->getType())) {
1797 ScalarizeMaskedGather(CI);
1798 ModifiedDT = true;
1799 return true;
1800 }
1801 return false;
1802 }
1803 case Intrinsic::masked_scatter: {
1804 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
1805 ScalarizeMaskedScatter(CI);
1806 ModifiedDT = true;
1807 return true;
1808 }
1809 return false;
1810 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001811 case Intrinsic::aarch64_stlxr:
1812 case Intrinsic::aarch64_stxr: {
1813 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1814 if (!ExtVal || !ExtVal->hasOneUse() ||
1815 ExtVal->getParent() == CI->getParent())
1816 return false;
1817 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1818 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001819 // Mark this instruction as "inserted by CGP", so that other
1820 // optimizations don't touch it.
1821 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001822 return true;
1823 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001824 case Intrinsic::invariant_group_barrier:
1825 II->replaceAllUsesWith(II->getArgOperand(0));
1826 II->eraseFromParent();
1827 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001828
1829 case Intrinsic::cttz:
1830 case Intrinsic::ctlz:
1831 // If counting zeros is expensive, try to avoid it.
1832 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001833 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001834
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001835 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001836 // Unknown address space.
1837 // TODO: Target hook to pick which address space the intrinsic cares
1838 // about?
1839 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001840 SmallVector<Value*, 2> PtrOps;
1841 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001842 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001843 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001844 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001845 return true;
1846 }
Pete Cooper615fd892012-03-13 20:59:56 +00001847 }
1848
Eric Christopher4b7948e2010-03-11 02:41:03 +00001849 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001850 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001851
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001852 // Lower all default uses of _chk calls. This is very similar
1853 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001854 // to fortified library functions (e.g. __memcpy_chk) that have the default
1855 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001856 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001857 if (Value *V = Simplifier.optimizeCall(CI)) {
1858 CI->replaceAllUsesWith(V);
1859 CI->eraseFromParent();
1860 return true;
1861 }
1862 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001863}
Chris Lattner1b93be52011-01-15 07:25:29 +00001864
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001865/// Look for opportunities to duplicate return instructions to the predecessor
1866/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001867/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001868/// bb0:
1869/// %tmp0 = tail call i32 @f0()
1870/// br label %return
1871/// bb1:
1872/// %tmp1 = tail call i32 @f1()
1873/// br label %return
1874/// bb2:
1875/// %tmp2 = tail call i32 @f2()
1876/// br label %return
1877/// return:
1878/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1879/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001880/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001881///
1882/// =>
1883///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001884/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001885/// bb0:
1886/// %tmp0 = tail call i32 @f0()
1887/// ret i32 %tmp0
1888/// bb1:
1889/// %tmp1 = tail call i32 @f1()
1890/// ret i32 %tmp1
1891/// bb2:
1892/// %tmp2 = tail call i32 @f2()
1893/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001894/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001895bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001896 if (!TLI)
1897 return false;
1898
Benjamin Kramer455fa352012-11-23 19:17:06 +00001899 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1900 if (!RI)
1901 return false;
1902
Craig Topperc0196b12014-04-14 00:51:57 +00001903 PHINode *PN = nullptr;
1904 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001905 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001906 if (V) {
1907 BCI = dyn_cast<BitCastInst>(V);
1908 if (BCI)
1909 V = BCI->getOperand(0);
1910
1911 PN = dyn_cast<PHINode>(V);
1912 if (!PN)
1913 return false;
1914 }
Evan Cheng0663f232011-03-21 01:19:09 +00001915
Cameron Zwarich4649f172011-03-24 04:52:10 +00001916 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001917 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001918
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001919 // It's not safe to eliminate the sign / zero extension of the return value.
1920 // See llvm::isInTailCallPosition().
1921 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001922 AttributeSet CallerAttrs = F->getAttributes();
1923 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1924 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001925 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001926
Cameron Zwarich4649f172011-03-24 04:52:10 +00001927 // Make sure there are no instructions between the PHI and return, or that the
1928 // return is the first instruction in the block.
1929 if (PN) {
1930 BasicBlock::iterator BI = BB->begin();
1931 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001932 if (&*BI == BCI)
1933 // Also skip over the bitcast.
1934 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001935 if (&*BI != RI)
1936 return false;
1937 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001938 BasicBlock::iterator BI = BB->begin();
1939 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1940 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001941 return false;
1942 }
Evan Cheng0663f232011-03-21 01:19:09 +00001943
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001944 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1945 /// call.
1946 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001947 if (PN) {
1948 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1949 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1950 // Make sure the phi value is indeed produced by the tail call.
1951 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1952 TLI->mayBeEmittedAsTailCall(CI))
1953 TailCalls.push_back(CI);
1954 }
1955 } else {
1956 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001957 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001958 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001959 continue;
1960
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001961 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001962 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1963 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001964 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1965 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001966 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001967
Cameron Zwarich4649f172011-03-24 04:52:10 +00001968 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001969 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001970 TailCalls.push_back(CI);
1971 }
Evan Cheng0663f232011-03-21 01:19:09 +00001972 }
1973
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001974 bool Changed = false;
1975 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1976 CallInst *CI = TailCalls[i];
1977 CallSite CS(CI);
1978
1979 // Conservatively require the attributes of the call to match those of the
1980 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001981 AttributeSet CalleeAttrs = CS.getAttributes();
1982 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001983 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001984 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001985 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001986 continue;
1987
1988 // Make sure the call instruction is followed by an unconditional branch to
1989 // the return block.
1990 BasicBlock *CallBB = CI->getParent();
1991 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1992 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1993 continue;
1994
1995 // Duplicate the return into CallBB.
1996 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001997 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001998 ++NumRetsDup;
1999 }
2000
2001 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002002 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002003 BB->eraseFromParent();
2004
2005 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002006}
2007
Chris Lattner728f9022008-11-25 07:09:13 +00002008//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002009// Memory Optimization
2010//===----------------------------------------------------------------------===//
2011
Chandler Carruthc8925912013-01-05 02:09:22 +00002012namespace {
2013
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002014/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002015/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002016struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002017 Value *BaseReg;
2018 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002019 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002020 void print(raw_ostream &OS) const;
2021 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002022
Chandler Carruthc8925912013-01-05 02:09:22 +00002023 bool operator==(const ExtAddrMode& O) const {
2024 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2025 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2026 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2027 }
2028};
2029
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002030#ifndef NDEBUG
2031static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2032 AM.print(OS);
2033 return OS;
2034}
2035#endif
2036
Chandler Carruthc8925912013-01-05 02:09:22 +00002037void ExtAddrMode::print(raw_ostream &OS) const {
2038 bool NeedPlus = false;
2039 OS << "[";
2040 if (BaseGV) {
2041 OS << (NeedPlus ? " + " : "")
2042 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002043 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002044 NeedPlus = true;
2045 }
2046
Richard Trieuc0f91212014-05-30 03:15:17 +00002047 if (BaseOffs) {
2048 OS << (NeedPlus ? " + " : "")
2049 << BaseOffs;
2050 NeedPlus = true;
2051 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002052
2053 if (BaseReg) {
2054 OS << (NeedPlus ? " + " : "")
2055 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002056 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002057 NeedPlus = true;
2058 }
2059 if (Scale) {
2060 OS << (NeedPlus ? " + " : "")
2061 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002062 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002063 }
2064
2065 OS << ']';
2066}
2067
2068#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2069void ExtAddrMode::dump() const {
2070 print(dbgs());
2071 dbgs() << '\n';
2072}
2073#endif
2074
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002075/// \brief This class provides transaction based operation on the IR.
2076/// Every change made through this class is recorded in the internal state and
2077/// can be undone (rollback) until commit is called.
2078class TypePromotionTransaction {
2079
2080 /// \brief This represents the common interface of the individual transaction.
2081 /// Each class implements the logic for doing one specific modification on
2082 /// the IR via the TypePromotionTransaction.
2083 class TypePromotionAction {
2084 protected:
2085 /// The Instruction modified.
2086 Instruction *Inst;
2087
2088 public:
2089 /// \brief Constructor of the action.
2090 /// The constructor performs the related action on the IR.
2091 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2092
2093 virtual ~TypePromotionAction() {}
2094
2095 /// \brief Undo the modification done by this action.
2096 /// When this method is called, the IR must be in the same state as it was
2097 /// before this action was applied.
2098 /// \pre Undoing the action works if and only if the IR is in the exact same
2099 /// state as it was directly after this action was applied.
2100 virtual void undo() = 0;
2101
2102 /// \brief Advocate every change made by this action.
2103 /// When the results on the IR of the action are to be kept, it is important
2104 /// to call this function, otherwise hidden information may be kept forever.
2105 virtual void commit() {
2106 // Nothing to be done, this action is not doing anything.
2107 }
2108 };
2109
2110 /// \brief Utility to remember the position of an instruction.
2111 class InsertionHandler {
2112 /// Position of an instruction.
2113 /// Either an instruction:
2114 /// - Is the first in a basic block: BB is used.
2115 /// - Has a previous instructon: PrevInst is used.
2116 union {
2117 Instruction *PrevInst;
2118 BasicBlock *BB;
2119 } Point;
2120 /// Remember whether or not the instruction had a previous instruction.
2121 bool HasPrevInstruction;
2122
2123 public:
2124 /// \brief Record the position of \p Inst.
2125 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002126 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002127 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2128 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002129 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002130 else
2131 Point.BB = Inst->getParent();
2132 }
2133
2134 /// \brief Insert \p Inst at the recorded position.
2135 void insert(Instruction *Inst) {
2136 if (HasPrevInstruction) {
2137 if (Inst->getParent())
2138 Inst->removeFromParent();
2139 Inst->insertAfter(Point.PrevInst);
2140 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002141 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002142 if (Inst->getParent())
2143 Inst->moveBefore(Position);
2144 else
2145 Inst->insertBefore(Position);
2146 }
2147 }
2148 };
2149
2150 /// \brief Move an instruction before another.
2151 class InstructionMoveBefore : public TypePromotionAction {
2152 /// Original position of the instruction.
2153 InsertionHandler Position;
2154
2155 public:
2156 /// \brief Move \p Inst before \p Before.
2157 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2158 : TypePromotionAction(Inst), Position(Inst) {
2159 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2160 Inst->moveBefore(Before);
2161 }
2162
2163 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002164 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002165 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2166 Position.insert(Inst);
2167 }
2168 };
2169
2170 /// \brief Set the operand of an instruction with a new value.
2171 class OperandSetter : public TypePromotionAction {
2172 /// Original operand of the instruction.
2173 Value *Origin;
2174 /// Index of the modified instruction.
2175 unsigned Idx;
2176
2177 public:
2178 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2179 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2180 : TypePromotionAction(Inst), Idx(Idx) {
2181 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2182 << "for:" << *Inst << "\n"
2183 << "with:" << *NewVal << "\n");
2184 Origin = Inst->getOperand(Idx);
2185 Inst->setOperand(Idx, NewVal);
2186 }
2187
2188 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002189 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002190 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2191 << "for: " << *Inst << "\n"
2192 << "with: " << *Origin << "\n");
2193 Inst->setOperand(Idx, Origin);
2194 }
2195 };
2196
2197 /// \brief Hide the operands of an instruction.
2198 /// Do as if this instruction was not using any of its operands.
2199 class OperandsHider : public TypePromotionAction {
2200 /// The list of original operands.
2201 SmallVector<Value *, 4> OriginalValues;
2202
2203 public:
2204 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2205 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2206 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2207 unsigned NumOpnds = Inst->getNumOperands();
2208 OriginalValues.reserve(NumOpnds);
2209 for (unsigned It = 0; It < NumOpnds; ++It) {
2210 // Save the current operand.
2211 Value *Val = Inst->getOperand(It);
2212 OriginalValues.push_back(Val);
2213 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002214 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002215 // that we are not willing to pay.
2216 Inst->setOperand(It, UndefValue::get(Val->getType()));
2217 }
2218 }
2219
2220 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002221 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002222 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2223 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2224 Inst->setOperand(It, OriginalValues[It]);
2225 }
2226 };
2227
2228 /// \brief Build a truncate instruction.
2229 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002230 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002231 public:
2232 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2233 /// result.
2234 /// trunc Opnd to Ty.
2235 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2236 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002237 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2238 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002239 }
2240
Quentin Colombetac55b152014-09-16 22:36:07 +00002241 /// \brief Get the built value.
2242 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002243
2244 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002245 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002246 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2247 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2248 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002249 }
2250 };
2251
2252 /// \brief Build a sign extension instruction.
2253 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002254 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 public:
2256 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2257 /// result.
2258 /// sext Opnd to Ty.
2259 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002260 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002261 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002262 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2263 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002264 }
2265
Quentin Colombetac55b152014-09-16 22:36:07 +00002266 /// \brief Get the built value.
2267 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002268
2269 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002270 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002271 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2272 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2273 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002274 }
2275 };
2276
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002277 /// \brief Build a zero extension instruction.
2278 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002279 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002280 public:
2281 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2282 /// result.
2283 /// zext Opnd to Ty.
2284 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002285 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002286 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002287 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2288 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002289 }
2290
Quentin Colombetac55b152014-09-16 22:36:07 +00002291 /// \brief Get the built value.
2292 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002293
2294 /// \brief Remove the built instruction.
2295 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002296 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2297 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2298 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002299 }
2300 };
2301
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002302 /// \brief Mutate an instruction to another type.
2303 class TypeMutator : public TypePromotionAction {
2304 /// Record the original type.
2305 Type *OrigTy;
2306
2307 public:
2308 /// \brief Mutate the type of \p Inst into \p NewTy.
2309 TypeMutator(Instruction *Inst, Type *NewTy)
2310 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2311 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2312 << "\n");
2313 Inst->mutateType(NewTy);
2314 }
2315
2316 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002317 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002318 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2319 << "\n");
2320 Inst->mutateType(OrigTy);
2321 }
2322 };
2323
2324 /// \brief Replace the uses of an instruction by another instruction.
2325 class UsesReplacer : public TypePromotionAction {
2326 /// Helper structure to keep track of the replaced uses.
2327 struct InstructionAndIdx {
2328 /// The instruction using the instruction.
2329 Instruction *Inst;
2330 /// The index where this instruction is used for Inst.
2331 unsigned Idx;
2332 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2333 : Inst(Inst), Idx(Idx) {}
2334 };
2335
2336 /// Keep track of the original uses (pair Instruction, Index).
2337 SmallVector<InstructionAndIdx, 4> OriginalUses;
2338 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2339
2340 public:
2341 /// \brief Replace all the use of \p Inst by \p New.
2342 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2343 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2344 << "\n");
2345 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002346 for (Use &U : Inst->uses()) {
2347 Instruction *UserI = cast<Instruction>(U.getUser());
2348 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002349 }
2350 // Now, we can replace the uses.
2351 Inst->replaceAllUsesWith(New);
2352 }
2353
2354 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002355 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002356 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2357 for (use_iterator UseIt = OriginalUses.begin(),
2358 EndIt = OriginalUses.end();
2359 UseIt != EndIt; ++UseIt) {
2360 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2361 }
2362 }
2363 };
2364
2365 /// \brief Remove an instruction from the IR.
2366 class InstructionRemover : public TypePromotionAction {
2367 /// Original position of the instruction.
2368 InsertionHandler Inserter;
2369 /// Helper structure to hide all the link to the instruction. In other
2370 /// words, this helps to do as if the instruction was removed.
2371 OperandsHider Hider;
2372 /// Keep track of the uses replaced, if any.
2373 UsesReplacer *Replacer;
2374
2375 public:
2376 /// \brief Remove all reference of \p Inst and optinally replace all its
2377 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002378 /// \pre If !Inst->use_empty(), then New != nullptr
2379 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002380 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002381 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002382 if (New)
2383 Replacer = new UsesReplacer(Inst, New);
2384 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2385 Inst->removeFromParent();
2386 }
2387
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002388 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002389
2390 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002391 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392
2393 /// \brief Resurrect the instruction and reassign it to the proper uses if
2394 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002395 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002396 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2397 Inserter.insert(Inst);
2398 if (Replacer)
2399 Replacer->undo();
2400 Hider.undo();
2401 }
2402 };
2403
2404public:
2405 /// Restoration point.
2406 /// The restoration point is a pointer to an action instead of an iterator
2407 /// because the iterator may be invalidated but not the pointer.
2408 typedef const TypePromotionAction *ConstRestorationPt;
2409 /// Advocate every changes made in that transaction.
2410 void commit();
2411 /// Undo all the changes made after the given point.
2412 void rollback(ConstRestorationPt Point);
2413 /// Get the current restoration point.
2414 ConstRestorationPt getRestorationPoint() const;
2415
2416 /// \name API for IR modification with state keeping to support rollback.
2417 /// @{
2418 /// Same as Instruction::setOperand.
2419 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2420 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002421 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002422 /// Same as Value::replaceAllUsesWith.
2423 void replaceAllUsesWith(Instruction *Inst, Value *New);
2424 /// Same as Value::mutateType.
2425 void mutateType(Instruction *Inst, Type *NewTy);
2426 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002427 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002429 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002430 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002431 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002432 /// Same as Instruction::moveBefore.
2433 void moveBefore(Instruction *Inst, Instruction *Before);
2434 /// @}
2435
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436private:
2437 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002438 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2439 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002440};
2441
2442void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2443 Value *NewVal) {
2444 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002445 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002446}
2447
2448void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2449 Value *NewVal) {
2450 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002451 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002452}
2453
2454void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2455 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002456 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002457}
2458
2459void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002460 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002461}
2462
Quentin Colombetac55b152014-09-16 22:36:07 +00002463Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2464 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002465 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002466 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002467 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002468 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002469}
2470
Quentin Colombetac55b152014-09-16 22:36:07 +00002471Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2472 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002473 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002474 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002475 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002476 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002477}
2478
Quentin Colombetac55b152014-09-16 22:36:07 +00002479Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2480 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002481 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002482 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002483 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002484 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002485}
2486
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002487void TypePromotionTransaction::moveBefore(Instruction *Inst,
2488 Instruction *Before) {
2489 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002490 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002491}
2492
2493TypePromotionTransaction::ConstRestorationPt
2494TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002495 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002496}
2497
2498void TypePromotionTransaction::commit() {
2499 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002500 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002501 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502 Actions.clear();
2503}
2504
2505void TypePromotionTransaction::rollback(
2506 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002507 while (!Actions.empty() && Point != Actions.back().get()) {
2508 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002509 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002510 }
2511}
2512
Chandler Carruthc8925912013-01-05 02:09:22 +00002513/// \brief A helper class for matching addressing modes.
2514///
2515/// This encapsulates the logic for matching the target-legal addressing modes.
2516class AddressingModeMatcher {
2517 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002518 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002519 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002520 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002521
2522 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2523 /// the memory instruction that we're computing this address for.
2524 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002525 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002526 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002527
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002528 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002529 /// part of the return value of this addressing mode matching stuff.
2530 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002531
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002532 /// The instructions inserted by other CodeGenPrepare optimizations.
2533 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002534 /// A map from the instructions to their type before promotion.
2535 InstrToOrigTy &PromotedInsts;
2536 /// The ongoing transaction where every action should be registered.
2537 TypePromotionTransaction &TPT;
2538
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002539 /// This is set to true when we should not do profitability checks.
2540 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002541 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002542
Eric Christopherd75c00c2015-02-26 22:38:34 +00002543 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002544 const TargetMachine &TM, Type *AT, unsigned AS,
2545 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002546 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002547 InstrToOrigTy &PromotedInsts,
2548 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002549 : AddrModeInsts(AMI), TM(TM),
2550 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2551 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002552 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2553 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2554 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002555 IgnoreProfitability = false;
2556 }
2557public:
Stephen Lin837bba12013-07-15 17:55:02 +00002558
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002559 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002560 /// give an access type of AccessTy. This returns a list of involved
2561 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002562 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002563 /// optimizations.
2564 /// \p PromotedInsts maps the instructions to their type before promotion.
2565 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002566 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002567 Instruction *MemoryInst,
2568 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002569 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002570 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002571 InstrToOrigTy &PromotedInsts,
2572 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002573 ExtAddrMode Result;
2574
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002575 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002576 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002577 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002578 (void)Success; assert(Success && "Couldn't select *anything*?");
2579 return Result;
2580 }
2581private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002582 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2583 bool matchAddr(Value *V, unsigned Depth);
2584 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002585 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002586 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002587 ExtAddrMode &AMBefore,
2588 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002589 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2590 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002591 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002592};
2593
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002594/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002595/// Return true and update AddrMode if this addr mode is legal for the target,
2596/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002597bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002598 unsigned Depth) {
2599 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2600 // mode. Just process that directly.
2601 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002602 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002603
Chandler Carruthc8925912013-01-05 02:09:22 +00002604 // If the scale is 0, it takes nothing to add this.
2605 if (Scale == 0)
2606 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002607
Chandler Carruthc8925912013-01-05 02:09:22 +00002608 // If we already have a scale of this value, we can add to it, otherwise, we
2609 // need an available scale field.
2610 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2611 return false;
2612
2613 ExtAddrMode TestAddrMode = AddrMode;
2614
2615 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2616 // [A+B + A*7] -> [B+A*8].
2617 TestAddrMode.Scale += Scale;
2618 TestAddrMode.ScaledReg = ScaleReg;
2619
2620 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002621 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002622 return false;
2623
2624 // It was legal, so commit it.
2625 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002626
Chandler Carruthc8925912013-01-05 02:09:22 +00002627 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2628 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2629 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002630 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002631 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2632 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2633 TestAddrMode.ScaledReg = AddLHS;
2634 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002635
Chandler Carruthc8925912013-01-05 02:09:22 +00002636 // If this addressing mode is legal, commit it and remember that we folded
2637 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002638 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002639 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2640 AddrMode = TestAddrMode;
2641 return true;
2642 }
2643 }
2644
2645 // Otherwise, not (x+c)*scale, just return what we have.
2646 return true;
2647}
2648
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002649/// This is a little filter, which returns true if an addressing computation
2650/// involving I might be folded into a load/store accessing it.
2651/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002652/// the set of instructions that MatchOperationAddr can.
2653static bool MightBeFoldableInst(Instruction *I) {
2654 switch (I->getOpcode()) {
2655 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002656 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002657 // Don't touch identity bitcasts.
2658 if (I->getType() == I->getOperand(0)->getType())
2659 return false;
2660 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2661 case Instruction::PtrToInt:
2662 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2663 return true;
2664 case Instruction::IntToPtr:
2665 // We know the input is intptr_t, so this is foldable.
2666 return true;
2667 case Instruction::Add:
2668 return true;
2669 case Instruction::Mul:
2670 case Instruction::Shl:
2671 // Can only handle X*C and X << C.
2672 return isa<ConstantInt>(I->getOperand(1));
2673 case Instruction::GetElementPtr:
2674 return true;
2675 default:
2676 return false;
2677 }
2678}
2679
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002680/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2681/// \note \p Val is assumed to be the product of some type promotion.
2682/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2683/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002684static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2685 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002686 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2687 if (!PromotedInst)
2688 return false;
2689 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2690 // If the ISDOpcode is undefined, it was undefined before the promotion.
2691 if (!ISDOpcode)
2692 return true;
2693 // Otherwise, check if the promoted instruction is legal or not.
2694 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002695 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002696}
2697
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002698/// \brief Hepler class to perform type promotion.
2699class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002700 /// \brief Utility function to check whether or not a sign or zero extension
2701 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2702 /// either using the operands of \p Inst or promoting \p Inst.
2703 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002704 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002705 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002706 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002707 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002708 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002709 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002710 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002711 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2712 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002713
2714 /// \brief Utility function to determine if \p OpIdx should be promoted when
2715 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002716 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002717 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002718 }
2719
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002720 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002721 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002722 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002723 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002724 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002725 /// Newly added extensions are inserted in \p Exts.
2726 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002727 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002728 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002729 static Value *promoteOperandForTruncAndAnyExt(
2730 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002731 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002732 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002733 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002734
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002735 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002736 /// operand is promotable and is not a supported trunc or sext.
2737 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002738 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002739 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002740 /// Newly added extensions are inserted in \p Exts.
2741 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002742 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002743 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002744 static Value *promoteOperandForOther(Instruction *Ext,
2745 TypePromotionTransaction &TPT,
2746 InstrToOrigTy &PromotedInsts,
2747 unsigned &CreatedInstsCost,
2748 SmallVectorImpl<Instruction *> *Exts,
2749 SmallVectorImpl<Instruction *> *Truncs,
2750 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002751
2752 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002753 static Value *signExtendOperandForOther(
2754 Instruction *Ext, TypePromotionTransaction &TPT,
2755 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2756 SmallVectorImpl<Instruction *> *Exts,
2757 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2758 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2759 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002760 }
2761
2762 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002763 static Value *zeroExtendOperandForOther(
2764 Instruction *Ext, TypePromotionTransaction &TPT,
2765 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2766 SmallVectorImpl<Instruction *> *Exts,
2767 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2768 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2769 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002770 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002771
2772public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002773 /// Type for the utility function that promotes the operand of Ext.
2774 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002775 InstrToOrigTy &PromotedInsts,
2776 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002777 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002778 SmallVectorImpl<Instruction *> *Truncs,
2779 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002780 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2781 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002782 /// \return NULL if no promotable action is possible with the current
2783 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002784 /// \p InsertedInsts keeps track of all the instructions inserted by the
2785 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002786 /// because we do not want to promote these instructions as CodeGenPrepare
2787 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2788 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002789 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002790 const TargetLowering &TLI,
2791 const InstrToOrigTy &PromotedInsts);
2792};
2793
2794bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002795 Type *ConsideredExtType,
2796 const InstrToOrigTy &PromotedInsts,
2797 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002798 // The promotion helper does not know how to deal with vector types yet.
2799 // To be able to fix that, we would need to fix the places where we
2800 // statically extend, e.g., constants and such.
2801 if (Inst->getType()->isVectorTy())
2802 return false;
2803
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002804 // We can always get through zext.
2805 if (isa<ZExtInst>(Inst))
2806 return true;
2807
2808 // sext(sext) is ok too.
2809 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002810 return true;
2811
2812 // We can get through binary operator, if it is legal. In other words, the
2813 // binary operator must have a nuw or nsw flag.
2814 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2815 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002816 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2817 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002818 return true;
2819
2820 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002821 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002822 if (!isa<TruncInst>(Inst))
2823 return false;
2824
2825 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002826 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002827 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002828 if (!OpndVal->getType()->isIntegerTy() ||
2829 OpndVal->getType()->getIntegerBitWidth() >
2830 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002831 return false;
2832
2833 // If the operand of the truncate is not an instruction, we will not have
2834 // any information on the dropped bits.
2835 // (Actually we could for constant but it is not worth the extra logic).
2836 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2837 if (!Opnd)
2838 return false;
2839
2840 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002841 // I.e., check that trunc just drops extended bits of the same kind of
2842 // the extension.
2843 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002844 const Type *OpndType;
2845 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002846 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2847 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002848 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2849 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002850 else
2851 return false;
2852
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002853 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002854 return Inst->getType()->getIntegerBitWidth() >=
2855 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002856}
2857
2858TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002859 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002860 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002861 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2862 "Unexpected instruction type");
2863 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2864 Type *ExtTy = Ext->getType();
2865 bool IsSExt = isa<SExtInst>(Ext);
2866 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002867 // get through.
2868 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002869 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002870 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002871
2872 // Do not promote if the operand has been added by codegenprepare.
2873 // Otherwise, it means we are undoing an optimization that is likely to be
2874 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002875 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002876 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002877
2878 // SExt or Trunc instructions.
2879 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002880 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2881 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002882 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002883
2884 // Regular instruction.
2885 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002886 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002887 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002888 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002889}
2890
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002891Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002892 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002893 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002894 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002895 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002896 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2897 // get through it and this method should not be called.
2898 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002899 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002900 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002901 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002902 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002903 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002904 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002905 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002906 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2907 TPT.replaceAllUsesWith(SExt, ZExt);
2908 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002909 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002910 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002911 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2912 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002913 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2914 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002915 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002916
2917 // Remove dead code.
2918 if (SExtOpnd->use_empty())
2919 TPT.eraseInstruction(SExtOpnd);
2920
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002921 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002922 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002923 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002924 if (ExtInst) {
2925 if (Exts)
2926 Exts->push_back(ExtInst);
2927 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2928 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002929 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002930 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002931
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002932 // At this point we have: ext ty opnd to ty.
2933 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2934 Value *NextVal = ExtInst->getOperand(0);
2935 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002936 return NextVal;
2937}
2938
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002939Value *TypePromotionHelper::promoteOperandForOther(
2940 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002941 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002942 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002943 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2944 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002945 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002946 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002947 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002948 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002949 if (!ExtOpnd->hasOneUse()) {
2950 // ExtOpnd will be promoted.
2951 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002952 // promoted version.
2953 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002954 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002955 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2956 ITrunc->removeFromParent();
2957 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002958 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002959 if (Truncs)
2960 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002961 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002962
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002963 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002964 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002965 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002966 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002967 }
2968
2969 // Get through the Instruction:
2970 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002971 // 2. Replace the uses of Ext by Inst.
2972 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002973
2974 // Remember the original type of the instruction before promotion.
2975 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002976 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2977 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002978 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002979 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002980 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002981 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002982 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002983 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002984
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002985 DEBUG(dbgs() << "Propagate Ext to operands\n");
2986 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002987 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002988 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2989 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2990 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002991 DEBUG(dbgs() << "No need to propagate\n");
2992 continue;
2993 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002994 // Check if we can statically extend the operand.
2995 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002996 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002997 DEBUG(dbgs() << "Statically extend\n");
2998 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2999 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3000 : Cst->getValue().zext(BitWidth);
3001 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003002 continue;
3003 }
3004 // UndefValue are typed, so we have to statically sign extend them.
3005 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003006 DEBUG(dbgs() << "Statically extend\n");
3007 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003008 continue;
3009 }
3010
3011 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003012 // Check if Ext was reused to extend an operand.
3013 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003014 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003015 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003016 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3017 : TPT.createZExt(Ext, Opnd, Ext->getType());
3018 if (!isa<Instruction>(ValForExtOpnd)) {
3019 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3020 continue;
3021 }
3022 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003023 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003024 if (Exts)
3025 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003026 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003027
3028 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003029 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3030 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003031 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003032 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003033 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003034 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003035 if (ExtForOpnd == Ext) {
3036 DEBUG(dbgs() << "Extension is useless now\n");
3037 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003038 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003039 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003040}
3041
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003042/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003043/// \p NewCost gives the cost of extension instructions created by the
3044/// promotion.
3045/// \p OldCost gives the cost of extension instructions before the promotion
3046/// plus the number of instructions that have been
3047/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003048/// \p PromotedOperand is the value that has been promoted.
3049/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003050bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003051 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3052 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3053 // The cost of the new extensions is greater than the cost of the
3054 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003055 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003056 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003057 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003058 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003059 return true;
3060 // The promotion is neutral but it may help folding the sign extension in
3061 // loads for instance.
3062 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003063 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003064}
3065
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003066/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003067/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003068/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003069/// If \p MovedAway is not NULL, it contains the information of whether or
3070/// not AddrInst has to be folded into the addressing mode on success.
3071/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3072/// because it has been moved away.
3073/// Thus AddrInst must not be added in the matched instructions.
3074/// This state can happen when AddrInst is a sext, since it may be moved away.
3075/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3076/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003077bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003078 unsigned Depth,
3079 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003080 // Avoid exponential behavior on extremely deep expression trees.
3081 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003082
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003083 // By default, all matched instructions stay in place.
3084 if (MovedAway)
3085 *MovedAway = false;
3086
Chandler Carruthc8925912013-01-05 02:09:22 +00003087 switch (Opcode) {
3088 case Instruction::PtrToInt:
3089 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003090 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003091 case Instruction::IntToPtr: {
3092 auto AS = AddrInst->getType()->getPointerAddressSpace();
3093 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003094 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003095 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003096 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003097 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003098 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003099 case Instruction::BitCast:
3100 // BitCast is always a noop, and we can handle it as long as it is
3101 // int->int or pointer->pointer (we don't want int<->fp or something).
3102 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3103 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3104 // Don't touch identity bitcasts. These were probably put here by LSR,
3105 // and we don't want to mess around with them. Assume it knows what it
3106 // is doing.
3107 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003108 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003109 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003110 case Instruction::AddrSpaceCast: {
3111 unsigned SrcAS
3112 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3113 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3114 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003115 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003116 return false;
3117 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003118 case Instruction::Add: {
3119 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3120 ExtAddrMode BackupAddrMode = AddrMode;
3121 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003122 // Start a transaction at this point.
3123 // The LHS may match but not the RHS.
3124 // Therefore, we need a higher level restoration point to undo partially
3125 // matched operation.
3126 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3127 TPT.getRestorationPoint();
3128
Sanjay Patelfc580a62015-09-21 23:03:16 +00003129 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3130 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003131 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003132
Chandler Carruthc8925912013-01-05 02:09:22 +00003133 // Restore the old addr mode info.
3134 AddrMode = BackupAddrMode;
3135 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003136 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003137
Chandler Carruthc8925912013-01-05 02:09:22 +00003138 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003139 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3140 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003141 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003142
Chandler Carruthc8925912013-01-05 02:09:22 +00003143 // Otherwise we definitely can't merge the ADD in.
3144 AddrMode = BackupAddrMode;
3145 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003146 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003147 break;
3148 }
3149 //case Instruction::Or:
3150 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3151 //break;
3152 case Instruction::Mul:
3153 case Instruction::Shl: {
3154 // Can only handle X*C and X << C.
3155 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003156 if (!RHS)
3157 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003158 int64_t Scale = RHS->getSExtValue();
3159 if (Opcode == Instruction::Shl)
3160 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003161
Sanjay Patelfc580a62015-09-21 23:03:16 +00003162 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003163 }
3164 case Instruction::GetElementPtr: {
3165 // Scan the GEP. We check it if it contains constant offsets and at most
3166 // one variable offset.
3167 int VariableOperand = -1;
3168 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003169
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003171 gep_type_iterator GTI = gep_type_begin(AddrInst);
3172 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3173 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003174 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003175 unsigned Idx =
3176 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3177 ConstantOffset += SL->getElementOffset(Idx);
3178 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003179 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003180 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3181 ConstantOffset += CI->getSExtValue()*TypeSize;
3182 } else if (TypeSize) { // Scales of zero don't do anything.
3183 // We only allow one variable index at the moment.
3184 if (VariableOperand != -1)
3185 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003186
Chandler Carruthc8925912013-01-05 02:09:22 +00003187 // Remember the variable index.
3188 VariableOperand = i;
3189 VariableScale = TypeSize;
3190 }
3191 }
3192 }
Stephen Lin837bba12013-07-15 17:55:02 +00003193
Chandler Carruthc8925912013-01-05 02:09:22 +00003194 // A common case is for the GEP to only do a constant offset. In this case,
3195 // just add it to the disp field and check validity.
3196 if (VariableOperand == -1) {
3197 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003198 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003199 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003200 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003201 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003202 return true;
3203 }
3204 AddrMode.BaseOffs -= ConstantOffset;
3205 return false;
3206 }
3207
3208 // Save the valid addressing mode in case we can't match.
3209 ExtAddrMode BackupAddrMode = AddrMode;
3210 unsigned OldSize = AddrModeInsts.size();
3211
3212 // See if the scale and offset amount is valid for this target.
3213 AddrMode.BaseOffs += ConstantOffset;
3214
3215 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003216 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003217 // If it couldn't be matched, just stuff the value in a register.
3218 if (AddrMode.HasBaseReg) {
3219 AddrMode = BackupAddrMode;
3220 AddrModeInsts.resize(OldSize);
3221 return false;
3222 }
3223 AddrMode.HasBaseReg = true;
3224 AddrMode.BaseReg = AddrInst->getOperand(0);
3225 }
3226
3227 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003228 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003229 Depth)) {
3230 // If it couldn't be matched, try stuffing the base into a register
3231 // instead of matching it, and retrying the match of the scale.
3232 AddrMode = BackupAddrMode;
3233 AddrModeInsts.resize(OldSize);
3234 if (AddrMode.HasBaseReg)
3235 return false;
3236 AddrMode.HasBaseReg = true;
3237 AddrMode.BaseReg = AddrInst->getOperand(0);
3238 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003239 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003240 VariableScale, Depth)) {
3241 // If even that didn't work, bail.
3242 AddrMode = BackupAddrMode;
3243 AddrModeInsts.resize(OldSize);
3244 return false;
3245 }
3246 }
3247
3248 return true;
3249 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003250 case Instruction::SExt:
3251 case Instruction::ZExt: {
3252 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3253 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003254 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003255
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003256 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003257 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003258 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003259 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003260 if (!TPH)
3261 return false;
3262
3263 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3264 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003265 unsigned CreatedInstsCost = 0;
3266 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003267 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003268 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003269 // SExt has been moved away.
3270 // Thus either it will be rematched later in the recursive calls or it is
3271 // gone. Anyway, we must not fold it into the addressing mode at this point.
3272 // E.g.,
3273 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003274 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003275 // addr = gep base, idx
3276 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003277 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003278 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3279 // addr = gep base, op <- match
3280 if (MovedAway)
3281 *MovedAway = true;
3282
3283 assert(PromotedOperand &&
3284 "TypePromotionHelper should have filtered out those cases");
3285
3286 ExtAddrMode BackupAddrMode = AddrMode;
3287 unsigned OldSize = AddrModeInsts.size();
3288
Sanjay Patelfc580a62015-09-21 23:03:16 +00003289 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003290 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003291 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003292 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003293 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003294 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003295 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003296 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003297 AddrMode = BackupAddrMode;
3298 AddrModeInsts.resize(OldSize);
3299 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3300 TPT.rollback(LastKnownGood);
3301 return false;
3302 }
3303 return true;
3304 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003305 }
3306 return false;
3307}
3308
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003309/// If we can, try to add the value of 'Addr' into the current addressing mode.
3310/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3311/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3312/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003313///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003314bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003315 // Start a transaction at this point that we will rollback if the matching
3316 // fails.
3317 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3318 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003319 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3320 // Fold in immediates if legal for the target.
3321 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003322 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003323 return true;
3324 AddrMode.BaseOffs -= CI->getSExtValue();
3325 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3326 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003327 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003328 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003329 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003330 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003331 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003332 }
3333 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3334 ExtAddrMode BackupAddrMode = AddrMode;
3335 unsigned OldSize = AddrModeInsts.size();
3336
3337 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003338 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003339 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003340 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003341 // to check here.
3342 if (MovedAway)
3343 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003344 // Okay, it's possible to fold this. Check to see if it is actually
3345 // *profitable* to do so. We use a simple cost model to avoid increasing
3346 // register pressure too much.
3347 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003348 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003349 AddrModeInsts.push_back(I);
3350 return true;
3351 }
Stephen Lin837bba12013-07-15 17:55:02 +00003352
Chandler Carruthc8925912013-01-05 02:09:22 +00003353 // It isn't profitable to do this, roll back.
3354 //cerr << "NOT FOLDING: " << *I;
3355 AddrMode = BackupAddrMode;
3356 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003357 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003358 }
3359 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003360 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003361 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003362 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003363 } else if (isa<ConstantPointerNull>(Addr)) {
3364 // Null pointer gets folded without affecting the addressing mode.
3365 return true;
3366 }
3367
3368 // Worse case, the target should support [reg] addressing modes. :)
3369 if (!AddrMode.HasBaseReg) {
3370 AddrMode.HasBaseReg = true;
3371 AddrMode.BaseReg = Addr;
3372 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003373 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003374 return true;
3375 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003376 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003377 }
3378
3379 // If the base register is already taken, see if we can do [r+r].
3380 if (AddrMode.Scale == 0) {
3381 AddrMode.Scale = 1;
3382 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003383 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003384 return true;
3385 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003386 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003387 }
3388 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003389 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003390 return false;
3391}
3392
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003393/// Check to see if all uses of OpVal by the specified inline asm call are due
3394/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003395static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003396 const TargetMachine &TM) {
3397 const Function *F = CI->getParent()->getParent();
3398 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3399 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003400 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003401 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3402 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003403 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3404 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003405
Chandler Carruthc8925912013-01-05 02:09:22 +00003406 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003407 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003408
3409 // If this asm operand is our Value*, and if it isn't an indirect memory
3410 // operand, we can't fold it!
3411 if (OpInfo.CallOperandVal == OpVal &&
3412 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3413 !OpInfo.isIndirect))
3414 return false;
3415 }
3416
3417 return true;
3418}
3419
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003420/// Recursively walk all the uses of I until we find a memory use.
3421/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003422/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003423static bool FindAllMemoryUses(
3424 Instruction *I,
3425 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3426 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003427 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003428 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003429 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003430
Chandler Carruthc8925912013-01-05 02:09:22 +00003431 // If this is an obviously unfoldable instruction, bail out.
3432 if (!MightBeFoldableInst(I))
3433 return true;
3434
3435 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003436 for (Use &U : I->uses()) {
3437 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003438
Chandler Carruthcdf47882014-03-09 03:16:01 +00003439 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3440 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003441 continue;
3442 }
Stephen Lin837bba12013-07-15 17:55:02 +00003443
Chandler Carruthcdf47882014-03-09 03:16:01 +00003444 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3445 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003446 if (opNo == 0) return true; // Storing addr, not into addr.
3447 MemoryUses.push_back(std::make_pair(SI, opNo));
3448 continue;
3449 }
Stephen Lin837bba12013-07-15 17:55:02 +00003450
Chandler Carruthcdf47882014-03-09 03:16:01 +00003451 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003452 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3453 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003454
Chandler Carruthc8925912013-01-05 02:09:22 +00003455 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003456 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003457 return true;
3458 continue;
3459 }
Stephen Lin837bba12013-07-15 17:55:02 +00003460
Eric Christopher11e4df72015-02-26 22:38:43 +00003461 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003462 return true;
3463 }
3464
3465 return false;
3466}
3467
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003468/// Return true if Val is already known to be live at the use site that we're
3469/// folding it into. If so, there is no cost to include it in the addressing
3470/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3471/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003472bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003473 Value *KnownLive2) {
3474 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003475 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003476 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003477
Chandler Carruthc8925912013-01-05 02:09:22 +00003478 // All values other than instructions and arguments (e.g. constants) are live.
3479 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003480
Chandler Carruthc8925912013-01-05 02:09:22 +00003481 // If Val is a constant sized alloca in the entry block, it is live, this is
3482 // true because it is just a reference to the stack/frame pointer, which is
3483 // live for the whole function.
3484 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3485 if (AI->isStaticAlloca())
3486 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003487
Chandler Carruthc8925912013-01-05 02:09:22 +00003488 // Check to see if this value is already used in the memory instruction's
3489 // block. If so, it's already live into the block at the very least, so we
3490 // can reasonably fold it.
3491 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3492}
3493
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003494/// It is possible for the addressing mode of the machine to fold the specified
3495/// instruction into a load or store that ultimately uses it.
3496/// However, the specified instruction has multiple uses.
3497/// Given this, it may actually increase register pressure to fold it
3498/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003499///
3500/// X = ...
3501/// Y = X+1
3502/// use(Y) -> nonload/store
3503/// Z = Y+1
3504/// load Z
3505///
3506/// In this case, Y has multiple uses, and can be folded into the load of Z
3507/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3508/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3509/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3510/// number of computations either.
3511///
3512/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3513/// X was live across 'load Z' for other reasons, we actually *would* want to
3514/// fold the addressing mode in the Z case. This would make Y die earlier.
3515bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003516isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003517 ExtAddrMode &AMAfter) {
3518 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003519
Chandler Carruthc8925912013-01-05 02:09:22 +00003520 // AMBefore is the addressing mode before this instruction was folded into it,
3521 // and AMAfter is the addressing mode after the instruction was folded. Get
3522 // the set of registers referenced by AMAfter and subtract out those
3523 // referenced by AMBefore: this is the set of values which folding in this
3524 // address extends the lifetime of.
3525 //
3526 // Note that there are only two potential values being referenced here,
3527 // BaseReg and ScaleReg (global addresses are always available, as are any
3528 // folded immediates).
3529 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003530
Chandler Carruthc8925912013-01-05 02:09:22 +00003531 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3532 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003533 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003534 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003535 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003536 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003537
3538 // If folding this instruction (and it's subexprs) didn't extend any live
3539 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003540 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003541 return true;
3542
3543 // If all uses of this instruction are ultimately load/store/inlineasm's,
3544 // check to see if their addressing modes will include this instruction. If
3545 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3546 // uses.
3547 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3548 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003549 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003550 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003551
Chandler Carruthc8925912013-01-05 02:09:22 +00003552 // Now that we know that all uses of this instruction are part of a chain of
3553 // computation involving only operations that could theoretically be folded
3554 // into a memory use, loop over each of these uses and see if they could
3555 // *actually* fold the instruction.
3556 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3557 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3558 Instruction *User = MemoryUses[i].first;
3559 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003560
Chandler Carruthc8925912013-01-05 02:09:22 +00003561 // Get the access type of this use. If the use isn't a pointer, we don't
3562 // know what it accesses.
3563 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003564 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3565 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003566 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003567 Type *AddressAccessTy = AddrTy->getElementType();
3568 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003569
Chandler Carruthc8925912013-01-05 02:09:22 +00003570 // Do a match against the root of this address, ignoring profitability. This
3571 // will tell us if the addressing mode for the memory operation will
3572 // *actually* cover the shared instruction.
3573 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003574 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3575 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003576 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003577 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003578 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003579 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003580 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003581 (void)Success; assert(Success && "Couldn't select *anything*?");
3582
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003583 // The match was to check the profitability, the changes made are not
3584 // part of the original matcher. Therefore, they should be dropped
3585 // otherwise the original matcher will not present the right state.
3586 TPT.rollback(LastKnownGood);
3587
Chandler Carruthc8925912013-01-05 02:09:22 +00003588 // If the match didn't cover I, then it won't be shared by it.
3589 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3590 I) == MatchedAddrModeInsts.end())
3591 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003592
Chandler Carruthc8925912013-01-05 02:09:22 +00003593 MatchedAddrModeInsts.clear();
3594 }
Stephen Lin837bba12013-07-15 17:55:02 +00003595
Chandler Carruthc8925912013-01-05 02:09:22 +00003596 return true;
3597}
3598
3599} // end anonymous namespace
3600
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003601/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003602/// different basic block than BB.
3603static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3604 if (Instruction *I = dyn_cast<Instruction>(V))
3605 return I->getParent() != BB;
3606 return false;
3607}
3608
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003609/// Load and Store Instructions often have addressing modes that can do
3610/// significant amounts of computation. As such, instruction selection will try
3611/// to get the load or store to do as much computation as possible for the
3612/// program. The problem is that isel can only see within a single block. As
3613/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003614///
3615/// This method is used to optimize both load/store and inline asms with memory
3616/// operands.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003617bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003618 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003619 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003620
3621 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003622 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003623 SmallVector<Value*, 8> worklist;
3624 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003625 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003626
Owen Anderson8ba5f392010-11-27 08:15:55 +00003627 // Use a worklist to iteratively look through PHI nodes, and ensure that
3628 // the addressing mode obtained from the non-PHI roots of the graph
3629 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003630 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003631 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003632 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003633 SmallVector<Instruction*, 16> AddrModeInsts;
3634 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003635 TypePromotionTransaction TPT;
3636 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3637 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003638 while (!worklist.empty()) {
3639 Value *V = worklist.back();
3640 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003641
Owen Anderson8ba5f392010-11-27 08:15:55 +00003642 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003643 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003644 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003645 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003646 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003647
Owen Anderson8ba5f392010-11-27 08:15:55 +00003648 // For a PHI node, push all of its incoming values.
3649 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003650 for (Value *IncValue : P->incoming_values())
3651 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003652 continue;
3653 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003654
Owen Anderson8ba5f392010-11-27 08:15:55 +00003655 // For non-PHIs, determine the addressing mode being computed.
3656 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003657 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003658 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003659 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003660
3661 // This check is broken into two cases with very similar code to avoid using
3662 // getNumUses() as much as possible. Some values have a lot of uses, so
3663 // calling getNumUses() unconditionally caused a significant compile-time
3664 // regression.
3665 if (!Consensus) {
3666 Consensus = V;
3667 AddrMode = NewAddrMode;
3668 AddrModeInsts = NewAddrModeInsts;
3669 continue;
3670 } else if (NewAddrMode == AddrMode) {
3671 if (!IsNumUsesConsensusValid) {
3672 NumUsesConsensus = Consensus->getNumUses();
3673 IsNumUsesConsensusValid = true;
3674 }
3675
3676 // Ensure that the obtained addressing mode is equivalent to that obtained
3677 // for all other roots of the PHI traversal. Also, when choosing one
3678 // such root as representative, select the one with the most uses in order
3679 // to keep the cost modeling heuristics in AddressingModeMatcher
3680 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003681 unsigned NumUses = V->getNumUses();
3682 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003683 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003684 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003685 AddrModeInsts = NewAddrModeInsts;
3686 }
3687 continue;
3688 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003689
Craig Topperc0196b12014-04-14 00:51:57 +00003690 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003691 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003692 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003693
Owen Anderson8ba5f392010-11-27 08:15:55 +00003694 // If the addressing mode couldn't be determined, or if multiple different
3695 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003696 if (!Consensus) {
3697 TPT.rollback(LastKnownGood);
3698 return false;
3699 }
3700 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003701
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003702 // Check to see if any of the instructions supersumed by this addr mode are
3703 // non-local to I's BB.
3704 bool AnyNonLocal = false;
3705 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003706 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003707 AnyNonLocal = true;
3708 break;
3709 }
3710 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003711
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003712 // If all the instructions matched are already in this BB, don't do anything.
3713 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003714 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003715 return false;
3716 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003717
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003718 // Insert this computation right after this user. Since our caller is
3719 // scanning from the top of the BB to the bottom, reuse of the expr are
3720 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003721 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003722
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003723 // Now that we determined the addressing expression we want to use and know
3724 // that we have to sink it into this block. Check to see if we have already
3725 // done this for some other load/store instr in this block. If so, reuse the
3726 // computation.
3727 Value *&SunkAddr = SunkAddrs[Addr];
3728 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003729 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003730 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003731 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003732 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003733 } else if (AddrSinkUsingGEPs ||
3734 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003735 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3736 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003737 // By default, we use the GEP-based method when AA is used later. This
3738 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3739 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003740 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003741 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003742 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003743
3744 // First, find the pointer.
3745 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3746 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003747 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003748 }
3749
3750 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3751 // We can't add more than one pointer together, nor can we scale a
3752 // pointer (both of which seem meaningless).
3753 if (ResultPtr || AddrMode.Scale != 1)
3754 return false;
3755
3756 ResultPtr = AddrMode.ScaledReg;
3757 AddrMode.Scale = 0;
3758 }
3759
3760 if (AddrMode.BaseGV) {
3761 if (ResultPtr)
3762 return false;
3763
3764 ResultPtr = AddrMode.BaseGV;
3765 }
3766
3767 // If the real base value actually came from an inttoptr, then the matcher
3768 // will look through it and provide only the integer value. In that case,
3769 // use it here.
3770 if (!ResultPtr && AddrMode.BaseReg) {
3771 ResultPtr =
3772 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003773 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003774 } else if (!ResultPtr && AddrMode.Scale == 1) {
3775 ResultPtr =
3776 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3777 AddrMode.Scale = 0;
3778 }
3779
3780 if (!ResultPtr &&
3781 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3782 SunkAddr = Constant::getNullValue(Addr->getType());
3783 } else if (!ResultPtr) {
3784 return false;
3785 } else {
3786 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003787 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3788 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003789
3790 // Start with the base register. Do this first so that subsequent address
3791 // matching finds it last, which will prevent it from trying to match it
3792 // as the scaled value in case it happens to be a mul. That would be
3793 // problematic if we've sunk a different mul for the scale, because then
3794 // we'd end up sinking both muls.
3795 if (AddrMode.BaseReg) {
3796 Value *V = AddrMode.BaseReg;
3797 if (V->getType() != IntPtrTy)
3798 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3799
3800 ResultIndex = V;
3801 }
3802
3803 // Add the scale value.
3804 if (AddrMode.Scale) {
3805 Value *V = AddrMode.ScaledReg;
3806 if (V->getType() == IntPtrTy) {
3807 // done.
3808 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3809 cast<IntegerType>(V->getType())->getBitWidth()) {
3810 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3811 } else {
3812 // It is only safe to sign extend the BaseReg if we know that the math
3813 // required to create it did not overflow before we extend it. Since
3814 // the original IR value was tossed in favor of a constant back when
3815 // the AddrMode was created we need to bail out gracefully if widths
3816 // do not match instead of extending it.
3817 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3818 if (I && (ResultIndex != AddrMode.BaseReg))
3819 I->eraseFromParent();
3820 return false;
3821 }
3822
3823 if (AddrMode.Scale != 1)
3824 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3825 "sunkaddr");
3826 if (ResultIndex)
3827 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3828 else
3829 ResultIndex = V;
3830 }
3831
3832 // Add in the Base Offset if present.
3833 if (AddrMode.BaseOffs) {
3834 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3835 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003836 // We need to add this separately from the scale above to help with
3837 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003838 if (ResultPtr->getType() != I8PtrTy)
3839 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003840 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003841 }
3842
3843 ResultIndex = V;
3844 }
3845
3846 if (!ResultIndex) {
3847 SunkAddr = ResultPtr;
3848 } else {
3849 if (ResultPtr->getType() != I8PtrTy)
3850 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003851 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003852 }
3853
3854 if (SunkAddr->getType() != Addr->getType())
3855 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3856 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003857 } else {
David Greene74e2d492010-01-05 01:27:11 +00003858 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003859 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003860 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003861 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003862
3863 // Start with the base register. Do this first so that subsequent address
3864 // matching finds it last, which will prevent it from trying to match it
3865 // as the scaled value in case it happens to be a mul. That would be
3866 // problematic if we've sunk a different mul for the scale, because then
3867 // we'd end up sinking both muls.
3868 if (AddrMode.BaseReg) {
3869 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003870 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003871 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003872 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003873 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003874 Result = V;
3875 }
3876
3877 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003878 if (AddrMode.Scale) {
3879 Value *V = AddrMode.ScaledReg;
3880 if (V->getType() == IntPtrTy) {
3881 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003882 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003883 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003884 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3885 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003886 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003887 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003888 // It is only safe to sign extend the BaseReg if we know that the math
3889 // required to create it did not overflow before we extend it. Since
3890 // the original IR value was tossed in favor of a constant back when
3891 // the AddrMode was created we need to bail out gracefully if widths
3892 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003893 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003894 if (I && (Result != AddrMode.BaseReg))
3895 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003896 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003897 }
3898 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003899 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3900 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003901 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003902 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003903 else
3904 Result = V;
3905 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003906
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003907 // Add in the BaseGV if present.
3908 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003909 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003910 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003911 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003912 else
3913 Result = V;
3914 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003915
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003916 // Add in the Base Offset if present.
3917 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003918 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003919 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003920 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003921 else
3922 Result = V;
3923 }
3924
Craig Topperc0196b12014-04-14 00:51:57 +00003925 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003926 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003927 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003928 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003929 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003930
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003931 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003932
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003933 // If we have no uses, recursively delete the value and all dead instructions
3934 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003935 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003936 // This can cause recursive deletion, which can invalidate our iterator.
3937 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003938 WeakVH IterHandle(&*CurInstIterator);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003939 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003940
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003941 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003942
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003943 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003944 // If the iterator instruction was recursively deleted, start over at the
3945 // start of the block.
3946 CurInstIterator = BB->begin();
3947 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003948 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003949 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003950 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003951 return true;
3952}
3953
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003954/// If there are any memory operands, use OptimizeMemoryInst to sink their
3955/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003956bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003957 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003958
Eric Christopher11e4df72015-02-26 22:38:43 +00003959 const TargetRegisterInfo *TRI =
3960 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003961 TargetLowering::AsmOperandInfoVector TargetConstraints =
3962 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003963 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003964 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3965 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003966
Evan Cheng1da25002008-02-26 02:42:37 +00003967 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003968 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003969
Eli Friedman666bbe32008-02-26 18:37:49 +00003970 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3971 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003972 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003973 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003974 } else if (OpInfo.Type == InlineAsm::isInput)
3975 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003976 }
3977
3978 return MadeChange;
3979}
3980
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003981/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3982/// sign extensions.
3983static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3984 assert(!Inst->use_empty() && "Input must have at least one use");
3985 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3986 bool IsSExt = isa<SExtInst>(FirstUser);
3987 Type *ExtTy = FirstUser->getType();
3988 for (const User *U : Inst->users()) {
3989 const Instruction *UI = cast<Instruction>(U);
3990 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3991 return false;
3992 Type *CurTy = UI->getType();
3993 // Same input and output types: Same instruction after CSE.
3994 if (CurTy == ExtTy)
3995 continue;
3996
3997 // If IsSExt is true, we are in this situation:
3998 // a = Inst
3999 // b = sext ty1 a to ty2
4000 // c = sext ty1 a to ty3
4001 // Assuming ty2 is shorter than ty3, this could be turned into:
4002 // a = Inst
4003 // b = sext ty1 a to ty2
4004 // c = sext ty2 b to ty3
4005 // However, the last sext is not free.
4006 if (IsSExt)
4007 return false;
4008
4009 // This is a ZExt, maybe this is free to extend from one type to another.
4010 // In that case, we would not account for a different use.
4011 Type *NarrowTy;
4012 Type *LargeTy;
4013 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4014 CurTy->getScalarType()->getIntegerBitWidth()) {
4015 NarrowTy = CurTy;
4016 LargeTy = ExtTy;
4017 } else {
4018 NarrowTy = ExtTy;
4019 LargeTy = CurTy;
4020 }
4021
4022 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4023 return false;
4024 }
4025 // All uses are the same or can be derived from one another for free.
4026 return true;
4027}
4028
4029/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4030/// load instruction.
4031/// If an ext(load) can be formed, it is returned via \p LI for the load
4032/// and \p Inst for the extension.
4033/// Otherwise LI == nullptr and Inst == nullptr.
4034/// When some promotion happened, \p TPT contains the proper state to
4035/// revert them.
4036///
4037/// \return true when promoting was necessary to expose the ext(load)
4038/// opportunity, false otherwise.
4039///
4040/// Example:
4041/// \code
4042/// %ld = load i32* %addr
4043/// %add = add nuw i32 %ld, 4
4044/// %zext = zext i32 %add to i64
4045/// \endcode
4046/// =>
4047/// \code
4048/// %ld = load i32* %addr
4049/// %zext = zext i32 %ld to i64
4050/// %add = add nuw i64 %zext, 4
4051/// \encode
4052/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004053bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004054 LoadInst *&LI, Instruction *&Inst,
4055 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004056 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004057 // Iterate over all the extensions to see if one form an ext(load).
4058 for (auto I : Exts) {
4059 // Check if we directly have ext(load).
4060 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4061 Inst = I;
4062 // No promotion happened here.
4063 return false;
4064 }
4065 // Check whether or not we want to do any promotion.
4066 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4067 continue;
4068 // Get the action to perform the promotion.
4069 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004070 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004071 // Check if we can promote.
4072 if (!TPH)
4073 continue;
4074 // Save the current state.
4075 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4076 TPT.getRestorationPoint();
4077 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004078 unsigned NewCreatedInstsCost = 0;
4079 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004080 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004081 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4082 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004083 assert(PromotedVal &&
4084 "TypePromotionHelper should have filtered out those cases");
4085
4086 // We would be able to merge only one extension in a load.
4087 // Therefore, if we have more than 1 new extension we heuristically
4088 // cut this search path, because it means we degrade the code quality.
4089 // With exactly 2, the transformation is neutral, because we will merge
4090 // one extension but leave one. However, we optimistically keep going,
4091 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004092 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4093 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004094 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004095 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004096 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004097 // The promotion is not profitable, rollback to the previous state.
4098 TPT.rollback(LastKnownGood);
4099 continue;
4100 }
4101 // The promotion is profitable.
4102 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004103 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004104 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004105 // If we have created a new extension, i.e., now we have two
4106 // extensions. We must make sure one of them is merged with
4107 // the load, otherwise we may degrade the code quality.
4108 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4109 // Promotion happened.
4110 return true;
4111 // If this does not help to expose an ext(load) then, rollback.
4112 TPT.rollback(LastKnownGood);
4113 }
4114 // None of the extension can form an ext(load).
4115 LI = nullptr;
4116 Inst = nullptr;
4117 return false;
4118}
4119
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004120/// Move a zext or sext fed by a load into the same basic block as the load,
4121/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4122/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004123/// \p I[in/out] the extension may be modified during the process if some
4124/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004125///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004126bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004127 // Try to promote a chain of computation if it allows to form
4128 // an extended load.
4129 TypePromotionTransaction TPT;
4130 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4131 TPT.getRestorationPoint();
4132 SmallVector<Instruction *, 1> Exts;
4133 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004134 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004135 LoadInst *LI = nullptr;
4136 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004137 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004138 if (!LI || !I) {
4139 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4140 "the code must remain the same");
4141 I = OldExt;
4142 return false;
4143 }
Dan Gohman99429a02009-10-16 20:59:35 +00004144
4145 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004146 // Make the cheap checks first if we did not promote.
4147 // If we promoted, we need to check if it is indeed profitable.
4148 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004149 return false;
4150
Mehdi Amini44ede332015-07-09 02:09:04 +00004151 EVT VT = TLI->getValueType(*DL, I->getType());
4152 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004153
Dan Gohman99429a02009-10-16 20:59:35 +00004154 // If the load has other users and the truncate is not free, this probably
4155 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004156 if (!LI->hasOneUse() && TLI &&
4157 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004158 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4159 I = OldExt;
4160 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004161 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004162 }
Dan Gohman99429a02009-10-16 20:59:35 +00004163
4164 // Check whether the target supports casts folded into loads.
4165 unsigned LType;
4166 if (isa<ZExtInst>(I))
4167 LType = ISD::ZEXTLOAD;
4168 else {
4169 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4170 LType = ISD::SEXTLOAD;
4171 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004172 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004173 I = OldExt;
4174 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004175 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004176 }
Dan Gohman99429a02009-10-16 20:59:35 +00004177
4178 // Move the extend into the same block as the load, so that SelectionDAG
4179 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004180 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004181 I->removeFromParent();
4182 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004183 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004184 return true;
4185}
4186
Sanjay Patelfc580a62015-09-21 23:03:16 +00004187bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004188 BasicBlock *DefBB = I->getParent();
4189
Bob Wilsonff714f92010-09-21 21:44:14 +00004190 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004191 // other uses of the source with result of extension.
4192 Value *Src = I->getOperand(0);
4193 if (Src->hasOneUse())
4194 return false;
4195
Evan Cheng2011df42007-12-13 07:50:36 +00004196 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004197 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004198 return false;
4199
Evan Cheng7bc89422007-12-12 00:51:06 +00004200 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004201 // this block.
4202 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004203 return false;
4204
Evan Chengd3d80172007-12-05 23:58:20 +00004205 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004206 for (User *U : I->users()) {
4207 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004208
4209 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004210 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004211 if (UserBB == DefBB) continue;
4212 DefIsLiveOut = true;
4213 break;
4214 }
4215 if (!DefIsLiveOut)
4216 return false;
4217
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004218 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004219 for (User *U : Src->users()) {
4220 Instruction *UI = cast<Instruction>(U);
4221 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004222 if (UserBB == DefBB) continue;
4223 // Be conservative. We don't want this xform to end up introducing
4224 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004225 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004226 return false;
4227 }
4228
Evan Chengd3d80172007-12-05 23:58:20 +00004229 // InsertedTruncs - Only insert one trunc in each block once.
4230 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4231
4232 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004233 for (Use &U : Src->uses()) {
4234 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004235
4236 // Figure out which BB this ext is used in.
4237 BasicBlock *UserBB = User->getParent();
4238 if (UserBB == DefBB) continue;
4239
4240 // Both src and def are live in this block. Rewrite the use.
4241 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4242
4243 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004244 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004245 assert(InsertPt != UserBB->end());
4246 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004247 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004248 }
4249
4250 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004251 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004252 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004253 MadeChange = true;
4254 }
4255
4256 return MadeChange;
4257}
4258
Sanjay Patel69a50a12015-10-19 21:59:12 +00004259/// Check if V (an operand of a select instruction) is an expensive instruction
4260/// that is only used once.
4261static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4262 auto *I = dyn_cast<Instruction>(V);
4263 // If it's safe to speculatively execute, then it should not have side
4264 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004265 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4266 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004267}
4268
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004269/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004270static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4271 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004272 // FIXME: This should use the same heuristics as IfConversion to determine
4273 // whether a select is better represented as a branch. This requires that
4274 // branch probability metadata is preserved for the select, which is not the
4275 // case currently.
4276
4277 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4278
Sanjay Patel4e652762015-09-28 22:14:51 +00004279 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4280 // comparison condition. If the compare has more than one use, there's
4281 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004282 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004283 return false;
4284
4285 Value *CmpOp0 = Cmp->getOperand(0);
4286 Value *CmpOp1 = Cmp->getOperand(1);
4287
Sanjay Patel4e652762015-09-28 22:14:51 +00004288 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
4289 // on a load from memory. But if the load is used more than once, do not
4290 // change the select to a branch because the load is probably needed
4291 // regardless of whether the branch is taken or not.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004292 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
4293 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
4294 return true;
4295
4296 // If either operand of the select is expensive and only needed on one side
4297 // of the select, we should form a branch.
4298 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4299 sinkSelectOperand(TTI, SI->getFalseValue()))
4300 return true;
4301
4302 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004303}
4304
4305
Nadav Rotem9d832022012-09-02 12:10:19 +00004306/// If we have a SelectInst that will likely profit from branch prediction,
4307/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004308bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00004309 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4310
4311 // Can we convert the 'select' to CF ?
4312 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004313 return false;
4314
Nadav Rotem9d832022012-09-02 12:10:19 +00004315 TargetLowering::SelectSupportKind SelectKind;
4316 if (VectorCond)
4317 SelectKind = TargetLowering::VectorMaskSelect;
4318 else if (SI->getType()->isVectorTy())
4319 SelectKind = TargetLowering::ScalarCondVectorVal;
4320 else
4321 SelectKind = TargetLowering::ScalarValSelect;
4322
4323 // Do we have efficient codegen support for this kind of 'selects' ?
4324 if (TLI->isSelectSupported(SelectKind)) {
4325 // We have efficient codegen support for the select instruction.
4326 // Check if it is profitable to keep this 'select'.
4327 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00004328 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00004329 return false;
4330 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004331
4332 ModifiedDT = true;
4333
Sanjay Patel69a50a12015-10-19 21:59:12 +00004334 // Transform a sequence like this:
4335 // start:
4336 // %cmp = cmp uge i32 %a, %b
4337 // %sel = select i1 %cmp, i32 %c, i32 %d
4338 //
4339 // Into:
4340 // start:
4341 // %cmp = cmp uge i32 %a, %b
4342 // br i1 %cmp, label %select.true, label %select.false
4343 // select.true:
4344 // br label %select.end
4345 // select.false:
4346 // br label %select.end
4347 // select.end:
4348 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4349 //
4350 // In addition, we may sink instructions that produce %c or %d from
4351 // the entry block into the destination(s) of the new branch.
4352 // If the true or false blocks do not contain a sunken instruction, that
4353 // block and its branch may be optimized away. In that case, one side of the
4354 // first branch will point directly to select.end, and the corresponding PHI
4355 // predecessor block will be the start block.
4356
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004357 // First, we split the block containing the select into 2 blocks.
4358 BasicBlock *StartBlock = SI->getParent();
4359 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004360 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004361
Sanjay Patel69a50a12015-10-19 21:59:12 +00004362 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004363 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004364
4365 // These are the new basic blocks for the conditional branch.
4366 // At least one will become an actual new basic block.
4367 BasicBlock *TrueBlock = nullptr;
4368 BasicBlock *FalseBlock = nullptr;
4369
4370 // Sink expensive instructions into the conditional blocks to avoid executing
4371 // them speculatively.
4372 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4373 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4374 EndBlock->getParent(), EndBlock);
4375 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4376 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4377 TrueInst->moveBefore(TrueBranch);
4378 }
4379 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4380 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4381 EndBlock->getParent(), EndBlock);
4382 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4383 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4384 FalseInst->moveBefore(FalseBranch);
4385 }
4386
4387 // If there was nothing to sink, then arbitrarily choose the 'false' side
4388 // for a new input value to the PHI.
4389 if (TrueBlock == FalseBlock) {
4390 assert(TrueBlock == nullptr &&
4391 "Unexpected basic block transform while optimizing select");
4392
4393 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4394 EndBlock->getParent(), EndBlock);
4395 BranchInst::Create(EndBlock, FalseBlock);
4396 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004397
4398 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004399 // If we did not create a new block for one of the 'true' or 'false' paths
4400 // of the condition, it means that side of the branch goes to the end block
4401 // directly and the path originates from the start block from the point of
4402 // view of the new PHI.
4403 if (TrueBlock == nullptr) {
4404 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4405 TrueBlock = StartBlock;
4406 } else if (FalseBlock == nullptr) {
4407 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4408 FalseBlock = StartBlock;
4409 } else {
4410 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4411 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004412
4413 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004414 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004415 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004416 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4417 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4418
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004419 SI->replaceAllUsesWith(PN);
4420 SI->eraseFromParent();
4421
4422 // Instruct OptimizeBlock to skip to the next block.
4423 CurInstIterator = StartBlock->end();
4424 ++NumSelectsExpanded;
4425 return true;
4426}
4427
Benjamin Kramer573ff362014-03-01 17:24:40 +00004428static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004429 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4430 int SplatElem = -1;
4431 for (unsigned i = 0; i < Mask.size(); ++i) {
4432 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4433 return false;
4434 SplatElem = Mask[i];
4435 }
4436
4437 return true;
4438}
4439
4440/// Some targets have expensive vector shifts if the lanes aren't all the same
4441/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4442/// it's often worth sinking a shufflevector splat down to its use so that
4443/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004444bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004445 BasicBlock *DefBB = SVI->getParent();
4446
4447 // Only do this xform if variable vector shifts are particularly expensive.
4448 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4449 return false;
4450
4451 // We only expect better codegen by sinking a shuffle if we can recognise a
4452 // constant splat.
4453 if (!isBroadcastShuffle(SVI))
4454 return false;
4455
4456 // InsertedShuffles - Only insert a shuffle in each block once.
4457 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4458
4459 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004460 for (User *U : SVI->users()) {
4461 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004462
4463 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004464 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004465 if (UserBB == DefBB) continue;
4466
4467 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004468 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004469
4470 // Everything checks out, sink the shuffle if the user's block doesn't
4471 // already have a copy.
4472 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4473
4474 if (!InsertedShuffle) {
4475 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004476 assert(InsertPt != UserBB->end());
4477 InsertedShuffle =
4478 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4479 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004480 }
4481
Chandler Carruthcdf47882014-03-09 03:16:01 +00004482 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004483 MadeChange = true;
4484 }
4485
4486 // If we removed all uses, nuke the shuffle.
4487 if (SVI->use_empty()) {
4488 SVI->eraseFromParent();
4489 MadeChange = true;
4490 }
4491
4492 return MadeChange;
4493}
4494
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004495bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4496 if (!TLI || !DL)
4497 return false;
4498
4499 Value *Cond = SI->getCondition();
4500 Type *OldType = Cond->getType();
4501 LLVMContext &Context = Cond->getContext();
4502 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4503 unsigned RegWidth = RegType.getSizeInBits();
4504
4505 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4506 return false;
4507
4508 // If the register width is greater than the type width, expand the condition
4509 // of the switch instruction and each case constant to the width of the
4510 // register. By widening the type of the switch condition, subsequent
4511 // comparisons (for case comparisons) will not need to be extended to the
4512 // preferred register width, so we will potentially eliminate N-1 extends,
4513 // where N is the number of cases in the switch.
4514 auto *NewType = Type::getIntNTy(Context, RegWidth);
4515
4516 // Zero-extend the switch condition and case constants unless the switch
4517 // condition is a function argument that is already being sign-extended.
4518 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4519 // everything instead.
4520 Instruction::CastOps ExtType = Instruction::ZExt;
4521 if (auto *Arg = dyn_cast<Argument>(Cond))
4522 if (Arg->hasSExtAttr())
4523 ExtType = Instruction::SExt;
4524
4525 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4526 ExtInst->insertBefore(SI);
4527 SI->setCondition(ExtInst);
4528 for (SwitchInst::CaseIt Case : SI->cases()) {
4529 APInt NarrowConst = Case.getCaseValue()->getValue();
4530 APInt WideConst = (ExtType == Instruction::ZExt) ?
4531 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4532 Case.setValue(ConstantInt::get(Context, WideConst));
4533 }
4534
4535 return true;
4536}
4537
Quentin Colombetc32615d2014-10-31 17:52:53 +00004538namespace {
4539/// \brief Helper class to promote a scalar operation to a vector one.
4540/// This class is used to move downward extractelement transition.
4541/// E.g.,
4542/// a = vector_op <2 x i32>
4543/// b = extractelement <2 x i32> a, i32 0
4544/// c = scalar_op b
4545/// store c
4546///
4547/// =>
4548/// a = vector_op <2 x i32>
4549/// c = vector_op a (equivalent to scalar_op on the related lane)
4550/// * d = extractelement <2 x i32> c, i32 0
4551/// * store d
4552/// Assuming both extractelement and store can be combine, we get rid of the
4553/// transition.
4554class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004555 /// DataLayout associated with the current module.
4556 const DataLayout &DL;
4557
Quentin Colombetc32615d2014-10-31 17:52:53 +00004558 /// Used to perform some checks on the legality of vector operations.
4559 const TargetLowering &TLI;
4560
4561 /// Used to estimated the cost of the promoted chain.
4562 const TargetTransformInfo &TTI;
4563
4564 /// The transition being moved downwards.
4565 Instruction *Transition;
4566 /// The sequence of instructions to be promoted.
4567 SmallVector<Instruction *, 4> InstsToBePromoted;
4568 /// Cost of combining a store and an extract.
4569 unsigned StoreExtractCombineCost;
4570 /// Instruction that will be combined with the transition.
4571 Instruction *CombineInst;
4572
4573 /// \brief The instruction that represents the current end of the transition.
4574 /// Since we are faking the promotion until we reach the end of the chain
4575 /// of computation, we need a way to get the current end of the transition.
4576 Instruction *getEndOfTransition() const {
4577 if (InstsToBePromoted.empty())
4578 return Transition;
4579 return InstsToBePromoted.back();
4580 }
4581
4582 /// \brief Return the index of the original value in the transition.
4583 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4584 /// c, is at index 0.
4585 unsigned getTransitionOriginalValueIdx() const {
4586 assert(isa<ExtractElementInst>(Transition) &&
4587 "Other kind of transitions are not supported yet");
4588 return 0;
4589 }
4590
4591 /// \brief Return the index of the index in the transition.
4592 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4593 /// is at index 1.
4594 unsigned getTransitionIdx() const {
4595 assert(isa<ExtractElementInst>(Transition) &&
4596 "Other kind of transitions are not supported yet");
4597 return 1;
4598 }
4599
4600 /// \brief Get the type of the transition.
4601 /// This is the type of the original value.
4602 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4603 /// transition is <2 x i32>.
4604 Type *getTransitionType() const {
4605 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4606 }
4607
4608 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4609 /// I.e., we have the following sequence:
4610 /// Def = Transition <ty1> a to <ty2>
4611 /// b = ToBePromoted <ty2> Def, ...
4612 /// =>
4613 /// b = ToBePromoted <ty1> a, ...
4614 /// Def = Transition <ty1> ToBePromoted to <ty2>
4615 void promoteImpl(Instruction *ToBePromoted);
4616
4617 /// \brief Check whether or not it is profitable to promote all the
4618 /// instructions enqueued to be promoted.
4619 bool isProfitableToPromote() {
4620 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4621 unsigned Index = isa<ConstantInt>(ValIdx)
4622 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4623 : -1;
4624 Type *PromotedType = getTransitionType();
4625
4626 StoreInst *ST = cast<StoreInst>(CombineInst);
4627 unsigned AS = ST->getPointerAddressSpace();
4628 unsigned Align = ST->getAlignment();
4629 // Check if this store is supported.
4630 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004631 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4632 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004633 // If this is not supported, there is no way we can combine
4634 // the extract with the store.
4635 return false;
4636 }
4637
4638 // The scalar chain of computation has to pay for the transition
4639 // scalar to vector.
4640 // The vector chain has to account for the combining cost.
4641 uint64_t ScalarCost =
4642 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4643 uint64_t VectorCost = StoreExtractCombineCost;
4644 for (const auto &Inst : InstsToBePromoted) {
4645 // Compute the cost.
4646 // By construction, all instructions being promoted are arithmetic ones.
4647 // Moreover, one argument is a constant that can be viewed as a splat
4648 // constant.
4649 Value *Arg0 = Inst->getOperand(0);
4650 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4651 isa<ConstantFP>(Arg0);
4652 TargetTransformInfo::OperandValueKind Arg0OVK =
4653 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4654 : TargetTransformInfo::OK_AnyValue;
4655 TargetTransformInfo::OperandValueKind Arg1OVK =
4656 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4657 : TargetTransformInfo::OK_AnyValue;
4658 ScalarCost += TTI.getArithmeticInstrCost(
4659 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4660 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4661 Arg0OVK, Arg1OVK);
4662 }
4663 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4664 << ScalarCost << "\nVector: " << VectorCost << '\n');
4665 return ScalarCost > VectorCost;
4666 }
4667
4668 /// \brief Generate a constant vector with \p Val with the same
4669 /// number of elements as the transition.
4670 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004671 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004672 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4673 /// otherwise we generate a vector with as many undef as possible:
4674 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4675 /// used at the index of the extract.
4676 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4677 unsigned ExtractIdx = UINT_MAX;
4678 if (!UseSplat) {
4679 // If we cannot determine where the constant must be, we have to
4680 // use a splat constant.
4681 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4682 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4683 ExtractIdx = CstVal->getSExtValue();
4684 else
4685 UseSplat = true;
4686 }
4687
4688 unsigned End = getTransitionType()->getVectorNumElements();
4689 if (UseSplat)
4690 return ConstantVector::getSplat(End, Val);
4691
4692 SmallVector<Constant *, 4> ConstVec;
4693 UndefValue *UndefVal = UndefValue::get(Val->getType());
4694 for (unsigned Idx = 0; Idx != End; ++Idx) {
4695 if (Idx == ExtractIdx)
4696 ConstVec.push_back(Val);
4697 else
4698 ConstVec.push_back(UndefVal);
4699 }
4700 return ConstantVector::get(ConstVec);
4701 }
4702
4703 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4704 /// in \p Use can trigger undefined behavior.
4705 static bool canCauseUndefinedBehavior(const Instruction *Use,
4706 unsigned OperandIdx) {
4707 // This is not safe to introduce undef when the operand is on
4708 // the right hand side of a division-like instruction.
4709 if (OperandIdx != 1)
4710 return false;
4711 switch (Use->getOpcode()) {
4712 default:
4713 return false;
4714 case Instruction::SDiv:
4715 case Instruction::UDiv:
4716 case Instruction::SRem:
4717 case Instruction::URem:
4718 return true;
4719 case Instruction::FDiv:
4720 case Instruction::FRem:
4721 return !Use->hasNoNaNs();
4722 }
4723 llvm_unreachable(nullptr);
4724 }
4725
4726public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004727 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4728 const TargetTransformInfo &TTI, Instruction *Transition,
4729 unsigned CombineCost)
4730 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004731 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4732 assert(Transition && "Do not know how to promote null");
4733 }
4734
4735 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4736 bool canPromote(const Instruction *ToBePromoted) const {
4737 // We could support CastInst too.
4738 return isa<BinaryOperator>(ToBePromoted);
4739 }
4740
4741 /// \brief Check if it is profitable to promote \p ToBePromoted
4742 /// by moving downward the transition through.
4743 bool shouldPromote(const Instruction *ToBePromoted) const {
4744 // Promote only if all the operands can be statically expanded.
4745 // Indeed, we do not want to introduce any new kind of transitions.
4746 for (const Use &U : ToBePromoted->operands()) {
4747 const Value *Val = U.get();
4748 if (Val == getEndOfTransition()) {
4749 // If the use is a division and the transition is on the rhs,
4750 // we cannot promote the operation, otherwise we may create a
4751 // division by zero.
4752 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4753 return false;
4754 continue;
4755 }
4756 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4757 !isa<ConstantFP>(Val))
4758 return false;
4759 }
4760 // Check that the resulting operation is legal.
4761 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4762 if (!ISDOpcode)
4763 return false;
4764 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004765 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004766 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004767 }
4768
4769 /// \brief Check whether or not \p Use can be combined
4770 /// with the transition.
4771 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4772 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4773
4774 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4775 void enqueueForPromotion(Instruction *ToBePromoted) {
4776 InstsToBePromoted.push_back(ToBePromoted);
4777 }
4778
4779 /// \brief Set the instruction that will be combined with the transition.
4780 void recordCombineInstruction(Instruction *ToBeCombined) {
4781 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4782 CombineInst = ToBeCombined;
4783 }
4784
4785 /// \brief Promote all the instructions enqueued for promotion if it is
4786 /// is profitable.
4787 /// \return True if the promotion happened, false otherwise.
4788 bool promote() {
4789 // Check if there is something to promote.
4790 // Right now, if we do not have anything to combine with,
4791 // we assume the promotion is not profitable.
4792 if (InstsToBePromoted.empty() || !CombineInst)
4793 return false;
4794
4795 // Check cost.
4796 if (!StressStoreExtract && !isProfitableToPromote())
4797 return false;
4798
4799 // Promote.
4800 for (auto &ToBePromoted : InstsToBePromoted)
4801 promoteImpl(ToBePromoted);
4802 InstsToBePromoted.clear();
4803 return true;
4804 }
4805};
4806} // End of anonymous namespace.
4807
4808void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4809 // At this point, we know that all the operands of ToBePromoted but Def
4810 // can be statically promoted.
4811 // For Def, we need to use its parameter in ToBePromoted:
4812 // b = ToBePromoted ty1 a
4813 // Def = Transition ty1 b to ty2
4814 // Move the transition down.
4815 // 1. Replace all uses of the promoted operation by the transition.
4816 // = ... b => = ... Def.
4817 assert(ToBePromoted->getType() == Transition->getType() &&
4818 "The type of the result of the transition does not match "
4819 "the final type");
4820 ToBePromoted->replaceAllUsesWith(Transition);
4821 // 2. Update the type of the uses.
4822 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4823 Type *TransitionTy = getTransitionType();
4824 ToBePromoted->mutateType(TransitionTy);
4825 // 3. Update all the operands of the promoted operation with promoted
4826 // operands.
4827 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4828 for (Use &U : ToBePromoted->operands()) {
4829 Value *Val = U.get();
4830 Value *NewVal = nullptr;
4831 if (Val == Transition)
4832 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4833 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4834 isa<ConstantFP>(Val)) {
4835 // Use a splat constant if it is not safe to use undef.
4836 NewVal = getConstantVector(
4837 cast<Constant>(Val),
4838 isa<UndefValue>(Val) ||
4839 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4840 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004841 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4842 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004843 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4844 }
4845 Transition->removeFromParent();
4846 Transition->insertAfter(ToBePromoted);
4847 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4848}
4849
4850/// Some targets can do store(extractelement) with one instruction.
4851/// Try to push the extractelement towards the stores when the target
4852/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004853bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004854 unsigned CombineCost = UINT_MAX;
4855 if (DisableStoreExtract || !TLI ||
4856 (!StressStoreExtract &&
4857 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4858 Inst->getOperand(1), CombineCost)))
4859 return false;
4860
4861 // At this point we know that Inst is a vector to scalar transition.
4862 // Try to move it down the def-use chain, until:
4863 // - We can combine the transition with its single use
4864 // => we got rid of the transition.
4865 // - We escape the current basic block
4866 // => we would need to check that we are moving it at a cheaper place and
4867 // we do not do that for now.
4868 BasicBlock *Parent = Inst->getParent();
4869 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00004870 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004871 // If the transition has more than one use, assume this is not going to be
4872 // beneficial.
4873 while (Inst->hasOneUse()) {
4874 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4875 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4876
4877 if (ToBePromoted->getParent() != Parent) {
4878 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4879 << ToBePromoted->getParent()->getName()
4880 << ") than the transition (" << Parent->getName() << ").\n");
4881 return false;
4882 }
4883
4884 if (VPH.canCombine(ToBePromoted)) {
4885 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4886 << "will be combined with: " << *ToBePromoted << '\n');
4887 VPH.recordCombineInstruction(ToBePromoted);
4888 bool Changed = VPH.promote();
4889 NumStoreExtractExposed += Changed;
4890 return Changed;
4891 }
4892
4893 DEBUG(dbgs() << "Try promoting.\n");
4894 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4895 return false;
4896
4897 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4898
4899 VPH.enqueueForPromotion(ToBePromoted);
4900 Inst = ToBePromoted;
4901 }
4902 return false;
4903}
4904
Sanjay Patelfc580a62015-09-21 23:03:16 +00004905bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004906 // Bail out if we inserted the instruction to prevent optimizations from
4907 // stepping on each other's toes.
4908 if (InsertedInsts.count(I))
4909 return false;
4910
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004911 if (PHINode *P = dyn_cast<PHINode>(I)) {
4912 // It is possible for very late stage optimizations (such as SimplifyCFG)
4913 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4914 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00004915 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004916 P->replaceAllUsesWith(V);
4917 P->eraseFromParent();
4918 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004919 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004920 }
Chris Lattneree588de2011-01-15 07:29:01 +00004921 return false;
4922 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004923
Chris Lattneree588de2011-01-15 07:29:01 +00004924 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004925 // If the source of the cast is a constant, then this should have
4926 // already been constant folded. The only reason NOT to constant fold
4927 // it is if something (e.g. LSR) was careful to place the constant
4928 // evaluation in a block other than then one that uses it (e.g. to hoist
4929 // the address of globals out of a loop). If this is the case, we don't
4930 // want to forward-subst the cast.
4931 if (isa<Constant>(CI->getOperand(0)))
4932 return false;
4933
Mehdi Amini44ede332015-07-09 02:09:04 +00004934 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00004935 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004936
Chris Lattneree588de2011-01-15 07:29:01 +00004937 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004938 /// Sink a zext or sext into its user blocks if the target type doesn't
4939 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00004940 if (TLI &&
4941 TLI->getTypeAction(CI->getContext(),
4942 TLI->getValueType(*DL, CI->getType())) ==
4943 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004944 return SinkCast(CI);
4945 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004946 bool MadeChange = moveExtToFormExtLoad(I);
4947 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004948 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004949 }
Chris Lattneree588de2011-01-15 07:29:01 +00004950 return false;
4951 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004952
Chris Lattneree588de2011-01-15 07:29:01 +00004953 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004954 if (!TLI || !TLI->hasMultipleConditionRegisters())
4955 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004956
Chris Lattneree588de2011-01-15 07:29:01 +00004957 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004958 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004959 if (TLI) {
4960 unsigned AS = LI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00004961 return optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004962 }
Hans Wennborgf3254832012-10-30 11:23:25 +00004963 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004964 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004965
Chris Lattneree588de2011-01-15 07:29:01 +00004966 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004967 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004968 if (TLI) {
4969 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00004970 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004971 SI->getOperand(0)->getType(), AS);
4972 }
Chris Lattneree588de2011-01-15 07:29:01 +00004973 return false;
4974 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004975
Yi Jiangd069f632014-04-21 19:34:27 +00004976 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4977
4978 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4979 BinOp->getOpcode() == Instruction::LShr)) {
4980 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4981 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00004982 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00004983
4984 return false;
4985 }
4986
Chris Lattneree588de2011-01-15 07:29:01 +00004987 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004988 if (GEPI->hasAllZeroIndices()) {
4989 /// The GEP operand must be a pointer, so must its result -> BitCast
4990 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4991 GEPI->getName(), GEPI);
4992 GEPI->replaceAllUsesWith(NC);
4993 GEPI->eraseFromParent();
4994 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004995 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004996 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004997 }
Chris Lattneree588de2011-01-15 07:29:01 +00004998 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004999 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005000
Chris Lattneree588de2011-01-15 07:29:01 +00005001 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005002 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005003
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005004 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005005 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005006
Tim Northoveraeb8e062014-02-19 10:02:43 +00005007 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005008 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005009
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005010 if (auto *Switch = dyn_cast<SwitchInst>(I))
5011 return optimizeSwitchInst(Switch);
5012
Quentin Colombetc32615d2014-10-31 17:52:53 +00005013 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005014 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005015
Chris Lattneree588de2011-01-15 07:29:01 +00005016 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005017}
5018
Chris Lattnerf2836d12007-03-31 04:06:36 +00005019// In this pass we look for GEP and cast instructions that are used
5020// across basic blocks and rewrite them to improve basic-block-at-a-time
5021// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005022bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005023 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005024 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005025
Chris Lattner7a277142011-01-15 07:14:54 +00005026 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005027 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005028 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005029 if (ModifiedDT)
5030 return true;
5031 }
Sanjay Patelfc580a62015-09-21 23:03:16 +00005032 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Benjamin Kramer455fa352012-11-23 19:17:06 +00005033
Chris Lattnerf2836d12007-03-31 04:06:36 +00005034 return MadeChange;
5035}
Devang Patel53771ba2011-08-18 00:50:51 +00005036
5037// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005038// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005039// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005040bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005041 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005042 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005043 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005044 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005045 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005046 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005047 // Leave dbg.values that refer to an alloca alone. These
5048 // instrinsics describe the address of a variable (= the alloca)
5049 // being taken. They should not be moved next to the alloca
5050 // (and to the beginning of the scope), but rather stay close to
5051 // where said address is used.
5052 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005053 PrevNonDbgInst = Insn;
5054 continue;
5055 }
5056
5057 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5058 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
5059 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5060 DVI->removeFromParent();
5061 if (isa<PHINode>(VI))
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005062 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
Devang Patel53771ba2011-08-18 00:50:51 +00005063 else
5064 DVI->insertAfter(VI);
5065 MadeChange = true;
5066 ++NumDbgValueMoved;
5067 }
5068 }
5069 }
5070 return MadeChange;
5071}
Tim Northovercea0abb2014-03-29 08:22:29 +00005072
5073// If there is a sequence that branches based on comparing a single bit
5074// against zero that can be combined into a single instruction, and the
5075// target supports folding these into a single instruction, sink the
5076// mask and compare into the branch uses. Do this before OptimizeBlock ->
5077// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5078// searched for.
5079bool CodeGenPrepare::sinkAndCmp(Function &F) {
5080 if (!EnableAndCmpSinking)
5081 return false;
5082 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5083 return false;
5084 bool MadeChange = false;
5085 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005086 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00005087
5088 // Does this BB end with the following?
5089 // %andVal = and %val, #single-bit-set
5090 // %icmpVal = icmp %andResult, 0
5091 // br i1 %cmpVal label %dest1, label %dest2"
5092 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
5093 if (!Brcc || !Brcc->isConditional())
5094 continue;
5095 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5096 if (!Cmp || Cmp->getParent() != BB)
5097 continue;
5098 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5099 if (!Zero || !Zero->isZero())
5100 continue;
5101 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5102 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
5103 continue;
5104 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5105 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5106 continue;
5107 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
5108
5109 // Push the "and; icmp" for any users that are conditional branches.
5110 // Since there can only be one branch use per BB, we don't need to keep
5111 // track of which BBs we insert into.
5112 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
5113 UI != E; ) {
5114 Use &TheUse = *UI;
5115 // Find brcc use.
5116 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
5117 ++UI;
5118 if (!BrccUser || !BrccUser->isConditional())
5119 continue;
5120 BasicBlock *UserBB = BrccUser->getParent();
5121 if (UserBB == BB) continue;
5122 DEBUG(dbgs() << "found Brcc use\n");
5123
5124 // Sink the "and; icmp" to use.
5125 MadeChange = true;
5126 BinaryOperator *NewAnd =
5127 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5128 BrccUser);
5129 CmpInst *NewCmp =
5130 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5131 "", BrccUser);
5132 TheUse = NewCmp;
5133 ++NumAndCmpsMoved;
5134 DEBUG(BrccUser->getParent()->dump());
5135 }
5136 }
5137 return MadeChange;
5138}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005139
Juergen Ributzka194350a2014-12-09 17:32:12 +00005140/// \brief Retrieve the probabilities of a conditional branch. Returns true on
5141/// success, or returns false if no or invalid metadata was found.
5142static bool extractBranchMetadata(BranchInst *BI,
5143 uint64_t &ProbTrue, uint64_t &ProbFalse) {
5144 assert(BI->isConditional() &&
5145 "Looking for probabilities on unconditional branch?");
5146 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
5147 if (!ProfileData || ProfileData->getNumOperands() != 3)
5148 return false;
5149
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005150 const auto *CITrue =
5151 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
5152 const auto *CIFalse =
5153 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00005154 if (!CITrue || !CIFalse)
5155 return false;
5156
5157 ProbTrue = CITrue->getValue().getZExtValue();
5158 ProbFalse = CIFalse->getValue().getZExtValue();
5159
5160 return true;
5161}
5162
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005163/// \brief Scale down both weights to fit into uint32_t.
5164static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5165 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5166 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5167 NewTrue = NewTrue / Scale;
5168 NewFalse = NewFalse / Scale;
5169}
5170
5171/// \brief Some targets prefer to split a conditional branch like:
5172/// \code
5173/// %0 = icmp ne i32 %a, 0
5174/// %1 = icmp ne i32 %b, 0
5175/// %or.cond = or i1 %0, %1
5176/// br i1 %or.cond, label %TrueBB, label %FalseBB
5177/// \endcode
5178/// into multiple branch instructions like:
5179/// \code
5180/// bb1:
5181/// %0 = icmp ne i32 %a, 0
5182/// br i1 %0, label %TrueBB, label %bb2
5183/// bb2:
5184/// %1 = icmp ne i32 %b, 0
5185/// br i1 %1, label %TrueBB, label %FalseBB
5186/// \endcode
5187/// This usually allows instruction selection to do even further optimizations
5188/// and combine the compare with the branch instruction. Currently this is
5189/// applied for targets which have "cheap" jump instructions.
5190///
5191/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5192///
5193bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005194 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005195 return false;
5196
5197 bool MadeChange = false;
5198 for (auto &BB : F) {
5199 // Does this BB end with the following?
5200 // %cond1 = icmp|fcmp|binary instruction ...
5201 // %cond2 = icmp|fcmp|binary instruction ...
5202 // %cond.or = or|and i1 %cond1, cond2
5203 // br i1 %cond.or label %dest1, label %dest2"
5204 BinaryOperator *LogicOp;
5205 BasicBlock *TBB, *FBB;
5206 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5207 continue;
5208
Sanjay Patel42574202015-09-02 19:23:23 +00005209 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5210 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5211 continue;
5212
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005213 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005214 Value *Cond1, *Cond2;
5215 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5216 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005217 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005218 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5219 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005220 Opc = Instruction::Or;
5221 else
5222 continue;
5223
5224 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5225 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5226 continue;
5227
5228 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5229
5230 // Create a new BB.
5231 auto *InsertBefore = std::next(Function::iterator(BB))
5232 .getNodePtrUnchecked();
5233 auto TmpBB = BasicBlock::Create(BB.getContext(),
5234 BB.getName() + ".cond.split",
5235 BB.getParent(), InsertBefore);
5236
5237 // Update original basic block by using the first condition directly by the
5238 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005239 Br1->setCondition(Cond1);
5240 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005241
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005242 // Depending on the conditon we have to either replace the true or the false
5243 // successor of the original branch instruction.
5244 if (Opc == Instruction::And)
5245 Br1->setSuccessor(0, TmpBB);
5246 else
5247 Br1->setSuccessor(1, TmpBB);
5248
5249 // Fill in the new basic block.
5250 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005251 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5252 I->removeFromParent();
5253 I->insertBefore(Br2);
5254 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005255
5256 // Update PHI nodes in both successors. The original BB needs to be
5257 // replaced in one succesor's PHI nodes, because the branch comes now from
5258 // the newly generated BB (NewBB). In the other successor we need to add one
5259 // incoming edge to the PHI nodes, because both branch instructions target
5260 // now the same successor. Depending on the original branch condition
5261 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5262 // we perfrom the correct update for the PHI nodes.
5263 // This doesn't change the successor order of the just created branch
5264 // instruction (or any other instruction).
5265 if (Opc == Instruction::Or)
5266 std::swap(TBB, FBB);
5267
5268 // Replace the old BB with the new BB.
5269 for (auto &I : *TBB) {
5270 PHINode *PN = dyn_cast<PHINode>(&I);
5271 if (!PN)
5272 break;
5273 int i;
5274 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5275 PN->setIncomingBlock(i, TmpBB);
5276 }
5277
5278 // Add another incoming edge form the new BB.
5279 for (auto &I : *FBB) {
5280 PHINode *PN = dyn_cast<PHINode>(&I);
5281 if (!PN)
5282 break;
5283 auto *Val = PN->getIncomingValueForBlock(&BB);
5284 PN->addIncoming(Val, TmpBB);
5285 }
5286
5287 // Update the branch weights (from SelectionDAGBuilder::
5288 // FindMergedConditions).
5289 if (Opc == Instruction::Or) {
5290 // Codegen X | Y as:
5291 // BB1:
5292 // jmp_if_X TBB
5293 // jmp TmpBB
5294 // TmpBB:
5295 // jmp_if_Y TBB
5296 // jmp FBB
5297 //
5298
5299 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5300 // The requirement is that
5301 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5302 // = TrueProb for orignal BB.
5303 // Assuming the orignal weights are A and B, one choice is to set BB1's
5304 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5305 // assumes that
5306 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5307 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5308 // TmpBB, but the math is more complicated.
5309 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005310 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005311 uint64_t NewTrueWeight = TrueWeight;
5312 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5313 scaleWeights(NewTrueWeight, NewFalseWeight);
5314 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5315 .createBranchWeights(TrueWeight, FalseWeight));
5316
5317 NewTrueWeight = TrueWeight;
5318 NewFalseWeight = 2 * FalseWeight;
5319 scaleWeights(NewTrueWeight, NewFalseWeight);
5320 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5321 .createBranchWeights(TrueWeight, FalseWeight));
5322 }
5323 } else {
5324 // Codegen X & Y as:
5325 // BB1:
5326 // jmp_if_X TmpBB
5327 // jmp FBB
5328 // TmpBB:
5329 // jmp_if_Y TBB
5330 // jmp FBB
5331 //
5332 // This requires creation of TmpBB after CurBB.
5333
5334 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5335 // The requirement is that
5336 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5337 // = FalseProb for orignal BB.
5338 // Assuming the orignal weights are A and B, one choice is to set BB1's
5339 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5340 // assumes that
5341 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5342 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005343 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005344 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5345 uint64_t NewFalseWeight = FalseWeight;
5346 scaleWeights(NewTrueWeight, NewFalseWeight);
5347 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5348 .createBranchWeights(TrueWeight, FalseWeight));
5349
5350 NewTrueWeight = 2 * TrueWeight;
5351 NewFalseWeight = FalseWeight;
5352 scaleWeights(NewTrueWeight, NewFalseWeight);
5353 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5354 .createBranchWeights(TrueWeight, FalseWeight));
5355 }
5356 }
5357
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005358 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005359 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005360 ModifiedDT = true;
5361
5362 MadeChange = true;
5363
5364 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5365 TmpBB->dump());
5366 }
5367 return MadeChange;
5368}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005369
5370void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005371 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005372 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5373}