blob: c78ad6532d9355a5f3071613cb2ee3d30afd972c [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000021#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000025#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000031#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000036#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000037#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000038#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000039#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000040#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000041#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000042#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000043#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000044#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000046#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000049#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000051#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000052using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000053using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000054
Chandler Carruth1b9dde02014-04-22 02:02:50 +000055#define DEBUG_TYPE "codegenprepare"
56
Cameron Zwarichced753f2011-01-05 17:27:27 +000057STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000058STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
59STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000060STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
61 "sunken Cmps");
62STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
63 "of sunken Casts");
64STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
65 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000066STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
67STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000068STATISTIC(NumAndsAdded,
69 "Number of and mask instructions added to form ext loads");
70STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000071STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000072STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000073STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000074STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000075STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000076
Cameron Zwarich338d3622011-03-11 21:52:04 +000077static cl::opt<bool> DisableBranchOpts(
78 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
79 cl::desc("Disable branch optimizations in CodeGenPrepare"));
80
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000081static cl::opt<bool>
82 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
83 cl::desc("Disable GC optimizations in CodeGenPrepare"));
84
Benjamin Kramer3d38c172012-05-06 14:25:16 +000085static cl::opt<bool> DisableSelectToBranch(
86 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
87 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000088
Hal Finkelc3998302014-04-12 00:59:48 +000089static cl::opt<bool> AddrSinkUsingGEPs(
90 "addr-sink-using-gep", cl::Hidden, cl::init(false),
91 cl::desc("Address sinking in CGP using GEPs."));
92
Tim Northovercea0abb2014-03-29 08:22:29 +000093static cl::opt<bool> EnableAndCmpSinking(
94 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
95 cl::desc("Enable sinkinig and/cmp into branches."));
96
Quentin Colombetc32615d2014-10-31 17:52:53 +000097static cl::opt<bool> DisableStoreExtract(
98 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
99 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
100
101static cl::opt<bool> StressStoreExtract(
102 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
103 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
104
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000105static cl::opt<bool> DisableExtLdPromotion(
106 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
108 "CodeGenPrepare"));
109
110static cl::opt<bool> StressExtLdPromotion(
111 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
112 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
113 "optimization in CodeGenPrepare"));
114
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000115static cl::opt<bool> DisablePreheaderProtect(
116 "disable-preheader-prot", cl::Hidden, cl::init(false),
117 cl::desc("Disable protection against removing loop preheaders"));
118
Eric Christopherc1ea1492008-09-24 05:32:41 +0000119namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000120typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000121typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000122typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000123class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000124
Chris Lattner2dd09db2009-09-02 06:11:42 +0000125 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000126 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000127 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000128 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000129 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000130 const LoopInfo *LI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000131
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000132 /// As we scan instructions optimizing them, this is the next instruction
133 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000134 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000135
Evan Cheng0663f232011-03-21 01:19:09 +0000136 /// Keeps track of non-local addresses that have been sunk into a block.
137 /// This allows us to avoid inserting duplicate code for blocks with
138 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000139 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000140
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000141 /// Keeps track of all instructions inserted for the current function.
142 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000143 /// Keeps track of the type of the related instruction before their
144 /// promotion for the current function.
145 InstrToOrigTy PromotedInsts;
146
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000147 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000148 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000149
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000150 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000151 bool OptSize;
152
Mehdi Amini4fe37982015-07-07 18:45:17 +0000153 /// DataLayout for the Function being processed.
154 const DataLayout *DL;
155
Chris Lattnerf2836d12007-03-31 04:06:36 +0000156 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000157 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000158 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000159 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000160 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
161 }
Craig Topper4584cd52014-03-07 09:26:03 +0000162 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000163
Craig Topper4584cd52014-03-07 09:26:03 +0000164 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000165
Craig Topper4584cd52014-03-07 09:26:03 +0000166 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000167 // FIXME: When we can selectively preserve passes, preserve the domtree.
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000168 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000169 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000170 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000171 }
172
Chris Lattnerf2836d12007-03-31 04:06:36 +0000173 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000174 bool eliminateFallThrough(Function &F);
175 bool eliminateMostlyEmptyBlocks(Function &F);
176 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
177 void eliminateMostlyEmptyBlock(BasicBlock *BB);
178 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
179 bool optimizeInst(Instruction *I, bool& ModifiedDT);
180 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000181 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000182 bool optimizeInlineAsmInst(CallInst *CS);
183 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
184 bool moveExtToFormExtLoad(Instruction *&I);
185 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000186 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000187 bool optimizeSelectInst(SelectInst *SI);
188 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000189 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000190 bool optimizeExtractElementInst(Instruction *Inst);
191 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
192 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000193 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000194 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000195 Instruction *&Inst,
196 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000197 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000198 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000199 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000200 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000201 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000202}
Devang Patel09f162c2007-05-01 21:15:47 +0000203
Devang Patel8c78a0b2007-05-03 01:11:54 +0000204char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000205INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
206 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000207
Bill Wendling7a639ea2013-06-19 21:07:11 +0000208FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
209 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000210}
211
Chris Lattnerf2836d12007-03-31 04:06:36 +0000212bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000213 if (skipOptnoneFunction(F))
214 return false;
215
Mehdi Amini4fe37982015-07-07 18:45:17 +0000216 DL = &F.getParent()->getDataLayout();
217
Chris Lattnerf2836d12007-03-31 04:06:36 +0000218 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000219 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000220 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000221 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000222
Devang Patel8f606d72011-03-24 15:35:25 +0000223 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000224 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000225 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000226 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000227 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000228 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000229 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000230
Preston Gurdcdf540d2012-09-04 18:22:17 +0000231 /// This optimization identifies DIV instructions that can be
232 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000233 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000234 const DenseMap<unsigned int, unsigned int> &BypassWidths =
235 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000236 BasicBlock* BB = &*F.begin();
237 while (BB != nullptr) {
238 // bypassSlowDivision may create new BBs, but we don't want to reapply the
239 // optimization to those blocks.
240 BasicBlock* Next = BB->getNextNode();
241 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
242 BB = Next;
243 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000244 }
245
246 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000247 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000248 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000249
Devang Patel53771ba2011-08-18 00:50:51 +0000250 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000251 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000252 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000253 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000254
Tim Northovercea0abb2014-03-29 08:22:29 +0000255 // If there is a mask, compare against zero, and branch that can be combined
256 // into a single target instruction, push the mask and compare into branch
257 // users. Do this before OptimizeBlock -> OptimizeInst ->
258 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000259 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000260 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000261 EverMadeChange |= splitBranchCondition(F);
262 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000263
Chris Lattnerc3748562007-04-02 01:35:34 +0000264 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000265 while (MadeChange) {
266 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000267 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000268 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000269 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000270 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000271
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000272 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000273 if (ModifiedDTOnIteration)
274 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000275 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000276 EverMadeChange |= MadeChange;
277 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000278
279 SunkAddrs.clear();
280
Cameron Zwarich338d3622011-03-11 21:52:04 +0000281 if (!DisableBranchOpts) {
282 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000283 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000284 for (BasicBlock &BB : F) {
285 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
286 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000287 if (!MadeChange) continue;
288
289 for (SmallVectorImpl<BasicBlock*>::iterator
290 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
291 if (pred_begin(*II) == pred_end(*II))
292 WorkList.insert(*II);
293 }
294
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000295 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000296 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000297 while (!WorkList.empty()) {
298 BasicBlock *BB = *WorkList.begin();
299 WorkList.erase(BB);
300 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
301
302 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000303
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000304 for (SmallVectorImpl<BasicBlock*>::iterator
305 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
306 if (pred_begin(*II) == pred_end(*II))
307 WorkList.insert(*II);
308 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000309
Nadav Rotem70409992012-08-14 05:19:07 +0000310 // Merge pairs of basic blocks with unconditional branches, connected by
311 // a single edge.
312 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000313 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000314
Cameron Zwarich338d3622011-03-11 21:52:04 +0000315 EverMadeChange |= MadeChange;
316 }
317
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000318 if (!DisableGCOpts) {
319 SmallVector<Instruction *, 2> Statepoints;
320 for (BasicBlock &BB : F)
321 for (Instruction &I : BB)
322 if (isStatepoint(I))
323 Statepoints.push_back(&I);
324 for (auto &I : Statepoints)
325 EverMadeChange |= simplifyOffsetableRelocate(*I);
326 }
327
Chris Lattnerf2836d12007-03-31 04:06:36 +0000328 return EverMadeChange;
329}
330
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000331/// Merge basic blocks which are connected by a single edge, where one of the
332/// basic blocks has a single successor pointing to the other basic block,
333/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000334bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000335 bool Changed = false;
336 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000337 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000338 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000339 // If the destination block has a single pred, then this is a trivial
340 // edge, just collapse it.
341 BasicBlock *SinglePred = BB->getSinglePredecessor();
342
Evan Cheng64a223a2012-09-28 23:58:57 +0000343 // Don't merge if BB's address is taken.
344 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000345
346 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
347 if (Term && !Term->isConditional()) {
348 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000349 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000350 // Remember if SinglePred was the entry block of the function.
351 // If so, we will need to move BB back to the entry position.
352 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000353 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000354
355 if (isEntry && BB != &BB->getParent()->getEntryBlock())
356 BB->moveBefore(&BB->getParent()->getEntryBlock());
357
358 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000359 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000360 }
361 }
362 return Changed;
363}
364
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000365/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
366/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
367/// edges in ways that are non-optimal for isel. Start by eliminating these
368/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000369bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000370 SmallPtrSet<BasicBlock *, 16> Preheaders;
371 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
372 while (!LoopList.empty()) {
373 Loop *L = LoopList.pop_back_val();
374 LoopList.insert(LoopList.end(), L->begin(), L->end());
375 if (BasicBlock *Preheader = L->getLoopPreheader())
376 Preheaders.insert(Preheader);
377 }
378
Chris Lattnerc3748562007-04-02 01:35:34 +0000379 bool MadeChange = false;
380 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000381 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000382 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000383
384 // If this block doesn't end with an uncond branch, ignore it.
385 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
386 if (!BI || !BI->isUnconditional())
387 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000388
Dale Johannesen4026b042009-03-27 01:13:37 +0000389 // If the instruction before the branch (skipping debug info) isn't a phi
390 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000391 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000392 if (BBI != BB->begin()) {
393 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000394 while (isa<DbgInfoIntrinsic>(BBI)) {
395 if (BBI == BB->begin())
396 break;
397 --BBI;
398 }
399 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
400 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000401 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000402
Chris Lattnerc3748562007-04-02 01:35:34 +0000403 // Do not break infinite loops.
404 BasicBlock *DestBB = BI->getSuccessor(0);
405 if (DestBB == BB)
406 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000407
Sanjay Patelfc580a62015-09-21 23:03:16 +0000408 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000409 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000410
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000411 // Do not delete loop preheaders if doing so would create a critical edge.
412 // Loop preheaders can be good locations to spill registers. If the
413 // preheader is deleted and we create a critical edge, registers may be
414 // spilled in the loop body instead.
415 if (!DisablePreheaderProtect && Preheaders.count(BB) &&
416 !(BB->getSinglePredecessor() && BB->getSinglePredecessor()->getSingleSuccessor()))
417 continue;
418
Sanjay Patelfc580a62015-09-21 23:03:16 +0000419 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000420 MadeChange = true;
421 }
422 return MadeChange;
423}
424
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000425/// Return true if we can merge BB into DestBB if there is a single
426/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000427/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000428bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 const BasicBlock *DestBB) const {
430 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
431 // the successor. If there are more complex condition (e.g. preheaders),
432 // don't mess around with them.
433 BasicBlock::const_iterator BBI = BB->begin();
434 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000435 for (const User *U : PN->users()) {
436 const Instruction *UI = cast<Instruction>(U);
437 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000438 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000439 // If User is inside DestBB block and it is a PHINode then check
440 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000441 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000442 if (UI->getParent() == DestBB) {
443 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000444 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
445 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
446 if (Insn && Insn->getParent() == BB &&
447 Insn->getParent() != UPN->getIncomingBlock(I))
448 return false;
449 }
450 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000451 }
452 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000453
Chris Lattnerc3748562007-04-02 01:35:34 +0000454 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
455 // and DestBB may have conflicting incoming values for the block. If so, we
456 // can't merge the block.
457 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
458 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000459
Chris Lattnerc3748562007-04-02 01:35:34 +0000460 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000461 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000462 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
463 // It is faster to get preds from a PHI than with pred_iterator.
464 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
465 BBPreds.insert(BBPN->getIncomingBlock(i));
466 } else {
467 BBPreds.insert(pred_begin(BB), pred_end(BB));
468 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000469
Chris Lattnerc3748562007-04-02 01:35:34 +0000470 // Walk the preds of DestBB.
471 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
472 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
473 if (BBPreds.count(Pred)) { // Common predecessor?
474 BBI = DestBB->begin();
475 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
476 const Value *V1 = PN->getIncomingValueForBlock(Pred);
477 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000478
Chris Lattnerc3748562007-04-02 01:35:34 +0000479 // If V2 is a phi node in BB, look up what the mapped value will be.
480 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
481 if (V2PN->getParent() == BB)
482 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000483
Chris Lattnerc3748562007-04-02 01:35:34 +0000484 // If there is a conflict, bail out.
485 if (V1 != V2) return false;
486 }
487 }
488 }
489
490 return true;
491}
492
493
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000494/// Eliminate a basic block that has only phi's and an unconditional branch in
495/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000496void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000497 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
498 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000499
David Greene74e2d492010-01-05 01:27:11 +0000500 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000501
Chris Lattnerc3748562007-04-02 01:35:34 +0000502 // If the destination block has a single pred, then this is a trivial edge,
503 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000504 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000505 if (SinglePred != DestBB) {
506 // Remember if SinglePred was the entry block of the function. If so, we
507 // will need to move BB back to the entry position.
508 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000509 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000510
Chris Lattner8a172da2008-11-28 19:54:49 +0000511 if (isEntry && BB != &BB->getParent()->getEntryBlock())
512 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000513
David Greene74e2d492010-01-05 01:27:11 +0000514 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000515 return;
516 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000517 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000518
Chris Lattnerc3748562007-04-02 01:35:34 +0000519 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
520 // to handle the new incoming edges it is about to have.
521 PHINode *PN;
522 for (BasicBlock::iterator BBI = DestBB->begin();
523 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
524 // Remove the incoming value for BB, and remember it.
525 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000526
Chris Lattnerc3748562007-04-02 01:35:34 +0000527 // Two options: either the InVal is a phi node defined in BB or it is some
528 // value that dominates BB.
529 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
530 if (InValPhi && InValPhi->getParent() == BB) {
531 // Add all of the input values of the input PHI as inputs of this phi.
532 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
533 PN->addIncoming(InValPhi->getIncomingValue(i),
534 InValPhi->getIncomingBlock(i));
535 } else {
536 // Otherwise, add one instance of the dominating value for each edge that
537 // we will be adding.
538 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
539 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
540 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
541 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000542 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
543 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000544 }
545 }
546 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000547
Chris Lattnerc3748562007-04-02 01:35:34 +0000548 // The PHIs are now updated, change everything that refers to BB to use
549 // DestBB and remove BB.
550 BB->replaceAllUsesWith(DestBB);
551 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000552 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000553
David Greene74e2d492010-01-05 01:27:11 +0000554 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000555}
556
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000557// Computes a map of base pointer relocation instructions to corresponding
558// derived pointer relocation instructions given a vector of all relocate calls
559static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000560 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
561 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
562 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000563 // Collect information in two maps: one primarily for locating the base object
564 // while filling the second map; the second map is the final structure holding
565 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000566 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
567 for (auto *ThisRelocate : AllRelocateCalls) {
568 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
569 ThisRelocate->getDerivedPtrIndex());
570 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000571 }
572 for (auto &Item : RelocateIdxMap) {
573 std::pair<unsigned, unsigned> Key = Item.first;
574 if (Key.first == Key.second)
575 // Base relocation: nothing to insert
576 continue;
577
Manuel Jacob83eefa62016-01-05 04:03:00 +0000578 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000579 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000580
581 // We're iterating over RelocateIdxMap so we cannot modify it.
582 auto MaybeBase = RelocateIdxMap.find(BaseKey);
583 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000584 // TODO: We might want to insert a new base object relocate and gep off
585 // that, if there are enough derived object relocates.
586 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000587
588 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000589 }
590}
591
592// Accepts a GEP and extracts the operands into a vector provided they're all
593// small integer constants
594static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
595 SmallVectorImpl<Value *> &OffsetV) {
596 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
597 // Only accept small constant integer operands
598 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
599 if (!Op || Op->getZExtValue() > 20)
600 return false;
601 }
602
603 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
604 OffsetV.push_back(GEP->getOperand(i));
605 return true;
606}
607
608// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
609// replace, computes a replacement, and affects it.
610static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000611simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
612 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000613 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000614 for (GCRelocateInst *ToReplace : Targets) {
615 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000616 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000617 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000618 // A duplicate relocate call. TODO: coalesce duplicates.
619 continue;
620 }
621
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000622 if (RelocatedBase->getParent() != ToReplace->getParent()) {
623 // Base and derived relocates are in different basic blocks.
624 // In this case transform is only valid when base dominates derived
625 // relocate. However it would be too expensive to check dominance
626 // for each such relocate, so we skip the whole transformation.
627 continue;
628 }
629
Manuel Jacob83eefa62016-01-05 04:03:00 +0000630 Value *Base = ToReplace->getBasePtr();
631 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000632 if (!Derived || Derived->getPointerOperand() != Base)
633 continue;
634
635 SmallVector<Value *, 2> OffsetV;
636 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
637 continue;
638
639 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000640 assert(RelocatedBase->getNextNode() &&
641 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000642
643 // Insert after RelocatedBase
644 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000645 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000646
647 // If gc_relocate does not match the actual type, cast it to the right type.
648 // In theory, there must be a bitcast after gc_relocate if the type does not
649 // match, and we should reuse it to get the derived pointer. But it could be
650 // cases like this:
651 // bb1:
652 // ...
653 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
654 // br label %merge
655 //
656 // bb2:
657 // ...
658 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
659 // br label %merge
660 //
661 // merge:
662 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
663 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
664 //
665 // In this case, we can not find the bitcast any more. So we insert a new bitcast
666 // no matter there is already one or not. In this way, we can handle all cases, and
667 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000668 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000669 if (RelocatedBase->getType() != Base->getType()) {
670 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000671 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000672 }
David Blaikie68d535c2015-03-24 22:38:16 +0000673 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000674 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000675 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000676 // If the newly generated derived pointer's type does not match the original derived
677 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000678 Value *ActualReplacement = Replacement;
679 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000680 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000681 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000682 }
683 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000684 ToReplace->eraseFromParent();
685
686 MadeChange = true;
687 }
688 return MadeChange;
689}
690
691// Turns this:
692//
693// %base = ...
694// %ptr = gep %base + 15
695// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
696// %base' = relocate(%tok, i32 4, i32 4)
697// %ptr' = relocate(%tok, i32 4, i32 5)
698// %val = load %ptr'
699//
700// into this:
701//
702// %base = ...
703// %ptr = gep %base + 15
704// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
705// %base' = gc.relocate(%tok, i32 4, i32 4)
706// %ptr' = gep %base' + 15
707// %val = load %ptr'
708bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
709 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000710 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000711
712 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000713 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000714 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000715 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000716
717 // We need atleast one base pointer relocation + one derived pointer
718 // relocation to mangle
719 if (AllRelocateCalls.size() < 2)
720 return false;
721
722 // RelocateInstMap is a mapping from the base relocate instruction to the
723 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000724 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000725 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
726 if (RelocateInstMap.empty())
727 return false;
728
729 for (auto &Item : RelocateInstMap)
730 // Item.first is the RelocatedBase to offset against
731 // Item.second is the vector of Targets to replace
732 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
733 return MadeChange;
734}
735
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000736/// SinkCast - Sink the specified cast instruction into its user blocks
737static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000738 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000739
Chris Lattnerf2836d12007-03-31 04:06:36 +0000740 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000741 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000742
Chris Lattnerf2836d12007-03-31 04:06:36 +0000743 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000744 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000745 UI != E; ) {
746 Use &TheUse = UI.getUse();
747 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000748
Chris Lattnerf2836d12007-03-31 04:06:36 +0000749 // Figure out which BB this cast is used in. For PHI's this is the
750 // appropriate predecessor block.
751 BasicBlock *UserBB = User->getParent();
752 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000753 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000754 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000755
Chris Lattnerf2836d12007-03-31 04:06:36 +0000756 // Preincrement use iterator so we don't invalidate it.
757 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000758
Andrew Kaylord0430e82015-11-23 19:16:15 +0000759 // If the block selected to receive the cast is an EH pad that does not
760 // allow non-PHI instructions before the terminator, we can't sink the
761 // cast.
762 if (UserBB->getTerminator()->isEHPad())
763 continue;
764
Chris Lattnerf2836d12007-03-31 04:06:36 +0000765 // If this user is in the same block as the cast, don't change the cast.
766 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000767
Chris Lattnerf2836d12007-03-31 04:06:36 +0000768 // If we have already inserted a cast into this block, use it.
769 CastInst *&InsertedCast = InsertedCasts[UserBB];
770
771 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000772 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000773 assert(InsertPt != UserBB->end());
774 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
775 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000776 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000777
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000778 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000779 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000780 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000781 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000782 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000783
Chris Lattnerf2836d12007-03-31 04:06:36 +0000784 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000785 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000786 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000787 MadeChange = true;
788 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000789
Chris Lattnerf2836d12007-03-31 04:06:36 +0000790 return MadeChange;
791}
792
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000793/// If the specified cast instruction is a noop copy (e.g. it's casting from
794/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
795/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000796///
797/// Return true if any changes are made.
798///
Mehdi Amini44ede332015-07-09 02:09:04 +0000799static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
800 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000801 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000802 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
803 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000804
805 // This is an fp<->int conversion?
806 if (SrcVT.isInteger() != DstVT.isInteger())
807 return false;
808
809 // If this is an extension, it will be a zero or sign extension, which
810 // isn't a noop.
811 if (SrcVT.bitsLT(DstVT)) return false;
812
813 // If these values will be promoted, find out what they will be promoted
814 // to. This helps us consider truncates on PPC as noop copies when they
815 // are.
816 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
817 TargetLowering::TypePromoteInteger)
818 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
819 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
820 TargetLowering::TypePromoteInteger)
821 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
822
823 // If, after promotion, these are the same types, this is a noop copy.
824 if (SrcVT != DstVT)
825 return false;
826
827 return SinkCast(CI);
828}
829
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000830/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
831/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000832///
833/// Return true if any changes were made.
834static bool CombineUAddWithOverflow(CmpInst *CI) {
835 Value *A, *B;
836 Instruction *AddI;
837 if (!match(CI,
838 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
839 return false;
840
841 Type *Ty = AddI->getType();
842 if (!isa<IntegerType>(Ty))
843 return false;
844
845 // We don't want to move around uses of condition values this late, so we we
846 // check if it is legal to create the call to the intrinsic in the basic
847 // block containing the icmp:
848
849 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
850 return false;
851
852#ifndef NDEBUG
853 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
854 // for now:
855 if (AddI->hasOneUse())
856 assert(*AddI->user_begin() == CI && "expected!");
857#endif
858
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000859 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000860 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
861
862 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
863
864 auto *UAddWithOverflow =
865 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
866 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
867 auto *Overflow =
868 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
869
870 CI->replaceAllUsesWith(Overflow);
871 AddI->replaceAllUsesWith(UAdd);
872 CI->eraseFromParent();
873 AddI->eraseFromParent();
874 return true;
875}
876
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000877/// Sink the given CmpInst into user blocks to reduce the number of virtual
878/// registers that must be created and coalesced. This is a clear win except on
879/// targets with multiple condition code registers (PowerPC), where it might
880/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000881///
882/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000883static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000884 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000885
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000886 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000887 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000888 return false;
889
890 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000891 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000892
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000893 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000894 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000895 UI != E; ) {
896 Use &TheUse = UI.getUse();
897 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000898
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000899 // Preincrement use iterator so we don't invalidate it.
900 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000901
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000902 // Don't bother for PHI nodes.
903 if (isa<PHINode>(User))
904 continue;
905
906 // Figure out which BB this cmp is used in.
907 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000908
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000909 // If this user is in the same block as the cmp, don't change the cmp.
910 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000911
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000912 // If we have already inserted a cmp into this block, use it.
913 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
914
915 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000916 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000917 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000918 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000919 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
920 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000921 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000922
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000923 // Replace a use of the cmp with a use of the new cmp.
924 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000925 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000926 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000927 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000928
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000929 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000930 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000931 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000932 MadeChange = true;
933 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000934
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000935 return MadeChange;
936}
937
Peter Zotovf87e5502016-04-03 17:11:53 +0000938static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +0000939 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000940 return true;
941
942 if (CombineUAddWithOverflow(CI))
943 return true;
944
945 return false;
946}
947
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000948/// Check if the candidates could be combined with a shift instruction, which
949/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000950/// 1. Truncate instruction
951/// 2. And instruction and the imm is a mask of the low bits:
952/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000953static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000954 if (!isa<TruncInst>(User)) {
955 if (User->getOpcode() != Instruction::And ||
956 !isa<ConstantInt>(User->getOperand(1)))
957 return false;
958
Quentin Colombetd4f44692014-04-22 01:20:34 +0000959 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000960
Quentin Colombetd4f44692014-04-22 01:20:34 +0000961 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000962 return false;
963 }
964 return true;
965}
966
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000967/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000968static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000969SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
970 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000971 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000972 BasicBlock *UserBB = User->getParent();
973 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
974 TruncInst *TruncI = dyn_cast<TruncInst>(User);
975 bool MadeChange = false;
976
977 for (Value::user_iterator TruncUI = TruncI->user_begin(),
978 TruncE = TruncI->user_end();
979 TruncUI != TruncE;) {
980
981 Use &TruncTheUse = TruncUI.getUse();
982 Instruction *TruncUser = cast<Instruction>(*TruncUI);
983 // Preincrement use iterator so we don't invalidate it.
984
985 ++TruncUI;
986
987 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
988 if (!ISDOpcode)
989 continue;
990
Tim Northovere2239ff2014-07-29 10:20:22 +0000991 // If the use is actually a legal node, there will not be an
992 // implicit truncate.
993 // FIXME: always querying the result type is just an
994 // approximation; some nodes' legality is determined by the
995 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000996 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000997 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000998 continue;
999
1000 // Don't bother for PHI nodes.
1001 if (isa<PHINode>(TruncUser))
1002 continue;
1003
1004 BasicBlock *TruncUserBB = TruncUser->getParent();
1005
1006 if (UserBB == TruncUserBB)
1007 continue;
1008
1009 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1010 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1011
1012 if (!InsertedShift && !InsertedTrunc) {
1013 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001014 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001015 // Sink the shift
1016 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001017 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1018 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001019 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001020 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1021 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001022
1023 // Sink the trunc
1024 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1025 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001026 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001027
1028 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001029 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001030
1031 MadeChange = true;
1032
1033 TruncTheUse = InsertedTrunc;
1034 }
1035 }
1036 return MadeChange;
1037}
1038
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001039/// Sink the shift *right* instruction into user blocks if the uses could
1040/// potentially be combined with this shift instruction and generate BitExtract
1041/// instruction. It will only be applied if the architecture supports BitExtract
1042/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001043/// BB1:
1044/// %x.extract.shift = lshr i64 %arg1, 32
1045/// BB2:
1046/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1047/// ==>
1048///
1049/// BB2:
1050/// %x.extract.shift.1 = lshr i64 %arg1, 32
1051/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1052///
1053/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1054/// instruction.
1055/// Return true if any changes are made.
1056static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001057 const TargetLowering &TLI,
1058 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001059 BasicBlock *DefBB = ShiftI->getParent();
1060
1061 /// Only insert instructions in each block once.
1062 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1063
Mehdi Amini44ede332015-07-09 02:09:04 +00001064 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001065
1066 bool MadeChange = false;
1067 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1068 UI != E;) {
1069 Use &TheUse = UI.getUse();
1070 Instruction *User = cast<Instruction>(*UI);
1071 // Preincrement use iterator so we don't invalidate it.
1072 ++UI;
1073
1074 // Don't bother for PHI nodes.
1075 if (isa<PHINode>(User))
1076 continue;
1077
1078 if (!isExtractBitsCandidateUse(User))
1079 continue;
1080
1081 BasicBlock *UserBB = User->getParent();
1082
1083 if (UserBB == DefBB) {
1084 // If the shift and truncate instruction are in the same BB. The use of
1085 // the truncate(TruncUse) may still introduce another truncate if not
1086 // legal. In this case, we would like to sink both shift and truncate
1087 // instruction to the BB of TruncUse.
1088 // for example:
1089 // BB1:
1090 // i64 shift.result = lshr i64 opnd, imm
1091 // trunc.result = trunc shift.result to i16
1092 //
1093 // BB2:
1094 // ----> We will have an implicit truncate here if the architecture does
1095 // not have i16 compare.
1096 // cmp i16 trunc.result, opnd2
1097 //
1098 if (isa<TruncInst>(User) && shiftIsLegal
1099 // If the type of the truncate is legal, no trucate will be
1100 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001101 &&
1102 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001103 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001104 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001105
1106 continue;
1107 }
1108 // If we have already inserted a shift into this block, use it.
1109 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1110
1111 if (!InsertedShift) {
1112 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001113 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001114
1115 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001116 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1117 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001118 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001119 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1120 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001121
1122 MadeChange = true;
1123 }
1124
1125 // Replace a use of the shift with a use of the new shift.
1126 TheUse = InsertedShift;
1127 }
1128
1129 // If we removed all uses, nuke the shift.
1130 if (ShiftI->use_empty())
1131 ShiftI->eraseFromParent();
1132
1133 return MadeChange;
1134}
1135
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001136// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001137// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1138// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001139// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001140// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001141//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001142// %1 = bitcast i8* %addr to i32*
1143// %2 = extractelement <16 x i1> %mask, i32 0
1144// %3 = icmp eq i1 %2, true
1145// br i1 %3, label %cond.load, label %else
1146//
1147//cond.load: ; preds = %0
1148// %4 = getelementptr i32* %1, i32 0
1149// %5 = load i32* %4
1150// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1151// br label %else
1152//
1153//else: ; preds = %0, %cond.load
1154// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1155// %7 = extractelement <16 x i1> %mask, i32 1
1156// %8 = icmp eq i1 %7, true
1157// br i1 %8, label %cond.load1, label %else2
1158//
1159//cond.load1: ; preds = %else
1160// %9 = getelementptr i32* %1, i32 1
1161// %10 = load i32* %9
1162// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1163// br label %else2
1164//
1165//else2: ; preds = %else, %cond.load1
1166// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1167// %12 = extractelement <16 x i1> %mask, i32 2
1168// %13 = icmp eq i1 %12, true
1169// br i1 %13, label %cond.load4, label %else5
1170//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001171static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001172 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001173 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001174 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001175 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001176
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001177 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1178 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001179 assert(VecType && "Unexpected return type of masked load intrinsic");
1180
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001181 Type *EltTy = CI->getType()->getVectorElementType();
1182
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001183 IRBuilder<> Builder(CI->getContext());
1184 Instruction *InsertPt = CI;
1185 BasicBlock *IfBlock = CI->getParent();
1186 BasicBlock *CondBlock = nullptr;
1187 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001188
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001189 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001190 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1191
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001192 // Short-cut if the mask is all-true.
1193 bool IsAllOnesMask = isa<Constant>(Mask) &&
1194 cast<Constant>(Mask)->isAllOnesValue();
1195
1196 if (IsAllOnesMask) {
1197 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1198 CI->replaceAllUsesWith(NewI);
1199 CI->eraseFromParent();
1200 return;
1201 }
1202
1203 // Adjust alignment for the scalar instruction.
1204 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001205 // Bitcast %addr fron i8* to EltTy*
1206 Type *NewPtrType =
1207 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1208 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001209 unsigned VectorWidth = VecType->getNumElements();
1210
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001211 Value *UndefVal = UndefValue::get(VecType);
1212
1213 // The result vector
1214 Value *VResult = UndefVal;
1215
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001216 if (isa<ConstantVector>(Mask)) {
1217 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1218 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1219 continue;
1220 Value *Gep =
1221 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1222 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1223 VResult = Builder.CreateInsertElement(VResult, Load,
1224 Builder.getInt32(Idx));
1225 }
1226 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1227 CI->replaceAllUsesWith(NewI);
1228 CI->eraseFromParent();
1229 return;
1230 }
1231
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001232 PHINode *Phi = nullptr;
1233 Value *PrevPhi = UndefVal;
1234
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001235 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1236
1237 // Fill the "else" block, created in the previous iteration
1238 //
1239 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1240 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1241 // %to_load = icmp eq i1 %mask_1, true
1242 // br i1 %to_load, label %cond.load, label %else
1243 //
1244 if (Idx > 0) {
1245 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1246 Phi->addIncoming(VResult, CondBlock);
1247 Phi->addIncoming(PrevPhi, PrevIfBlock);
1248 PrevPhi = Phi;
1249 VResult = Phi;
1250 }
1251
1252 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1253 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1254 ConstantInt::get(Predicate->getType(), 1));
1255
1256 // Create "cond" block
1257 //
1258 // %EltAddr = getelementptr i32* %1, i32 0
1259 // %Elt = load i32* %EltAddr
1260 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1261 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001262 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001263 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001264
1265 Value *Gep =
1266 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001267 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001268 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1269
1270 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001271 BasicBlock *NewIfBlock =
1272 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001273 Builder.SetInsertPoint(InsertPt);
1274 Instruction *OldBr = IfBlock->getTerminator();
1275 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1276 OldBr->eraseFromParent();
1277 PrevIfBlock = IfBlock;
1278 IfBlock = NewIfBlock;
1279 }
1280
1281 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1282 Phi->addIncoming(VResult, CondBlock);
1283 Phi->addIncoming(PrevPhi, PrevIfBlock);
1284 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1285 CI->replaceAllUsesWith(NewI);
1286 CI->eraseFromParent();
1287}
1288
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001289// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001290// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1291// <16 x i1> %mask)
1292// to a chain of basic blocks, that stores element one-by-one if
1293// the appropriate mask bit is set
1294//
1295// %1 = bitcast i8* %addr to i32*
1296// %2 = extractelement <16 x i1> %mask, i32 0
1297// %3 = icmp eq i1 %2, true
1298// br i1 %3, label %cond.store, label %else
1299//
1300// cond.store: ; preds = %0
1301// %4 = extractelement <16 x i32> %val, i32 0
1302// %5 = getelementptr i32* %1, i32 0
1303// store i32 %4, i32* %5
1304// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001305//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001306// else: ; preds = %0, %cond.store
1307// %6 = extractelement <16 x i1> %mask, i32 1
1308// %7 = icmp eq i1 %6, true
1309// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001310//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001311// cond.store1: ; preds = %else
1312// %8 = extractelement <16 x i32> %val, i32 1
1313// %9 = getelementptr i32* %1, i32 1
1314// store i32 %8, i32* %9
1315// br label %else2
1316// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001317static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001318 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001319 Value *Ptr = CI->getArgOperand(1);
1320 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001321 Value *Mask = CI->getArgOperand(3);
1322
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001323 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001324 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001325 assert(VecType && "Unexpected data type in masked store intrinsic");
1326
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001327 Type *EltTy = VecType->getElementType();
1328
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001329 IRBuilder<> Builder(CI->getContext());
1330 Instruction *InsertPt = CI;
1331 BasicBlock *IfBlock = CI->getParent();
1332 Builder.SetInsertPoint(InsertPt);
1333 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1334
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001335 // Short-cut if the mask is all-true.
1336 bool IsAllOnesMask = isa<Constant>(Mask) &&
1337 cast<Constant>(Mask)->isAllOnesValue();
1338
1339 if (IsAllOnesMask) {
1340 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1341 CI->eraseFromParent();
1342 return;
1343 }
1344
1345 // Adjust alignment for the scalar instruction.
1346 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001347 // Bitcast %addr fron i8* to EltTy*
1348 Type *NewPtrType =
1349 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1350 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001351 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001352
1353 if (isa<ConstantVector>(Mask)) {
1354 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1355 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1356 continue;
1357 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1358 Value *Gep =
1359 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1360 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1361 }
1362 CI->eraseFromParent();
1363 return;
1364 }
1365
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001366 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1367
1368 // Fill the "else" block, created in the previous iteration
1369 //
1370 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1371 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001372 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001373 //
1374 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1375 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1376 ConstantInt::get(Predicate->getType(), 1));
1377
1378 // Create "cond" block
1379 //
1380 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1381 // %EltAddr = getelementptr i32* %1, i32 0
1382 // %store i32 %OneElt, i32* %EltAddr
1383 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001384 BasicBlock *CondBlock =
1385 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001386 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001387
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001388 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001389 Value *Gep =
1390 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001391 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001392
1393 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001394 BasicBlock *NewIfBlock =
1395 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001396 Builder.SetInsertPoint(InsertPt);
1397 Instruction *OldBr = IfBlock->getTerminator();
1398 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1399 OldBr->eraseFromParent();
1400 IfBlock = NewIfBlock;
1401 }
1402 CI->eraseFromParent();
1403}
1404
Elena Demikhovsky09285852015-10-25 15:37:55 +00001405// Translate a masked gather intrinsic like
1406// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1407// <16 x i1> %Mask, <16 x i32> %Src)
1408// to a chain of basic blocks, with loading element one-by-one if
1409// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001410//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001411// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1412// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1413// % ToLoad0 = icmp eq i1 % Mask0, true
1414// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001415//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001416// cond.load:
1417// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1418// % Load0 = load i32, i32* % Ptr0, align 4
1419// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1420// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001421//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001422// else:
1423// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1424// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1425// % ToLoad1 = icmp eq i1 % Mask1, true
1426// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001427//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001428// cond.load1:
1429// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1430// % Load1 = load i32, i32* % Ptr1, align 4
1431// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1432// br label %else2
1433// . . .
1434// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1435// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001436static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001437 Value *Ptrs = CI->getArgOperand(0);
1438 Value *Alignment = CI->getArgOperand(1);
1439 Value *Mask = CI->getArgOperand(2);
1440 Value *Src0 = CI->getArgOperand(3);
1441
1442 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1443
1444 assert(VecType && "Unexpected return type of masked load intrinsic");
1445
1446 IRBuilder<> Builder(CI->getContext());
1447 Instruction *InsertPt = CI;
1448 BasicBlock *IfBlock = CI->getParent();
1449 BasicBlock *CondBlock = nullptr;
1450 BasicBlock *PrevIfBlock = CI->getParent();
1451 Builder.SetInsertPoint(InsertPt);
1452 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1453
1454 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1455
1456 Value *UndefVal = UndefValue::get(VecType);
1457
1458 // The result vector
1459 Value *VResult = UndefVal;
1460 unsigned VectorWidth = VecType->getNumElements();
1461
1462 // Shorten the way if the mask is a vector of constants.
1463 bool IsConstMask = isa<ConstantVector>(Mask);
1464
1465 if (IsConstMask) {
1466 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1467 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1468 continue;
1469 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1470 "Ptr" + Twine(Idx));
1471 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1472 "Load" + Twine(Idx));
1473 VResult = Builder.CreateInsertElement(VResult, Load,
1474 Builder.getInt32(Idx),
1475 "Res" + Twine(Idx));
1476 }
1477 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1478 CI->replaceAllUsesWith(NewI);
1479 CI->eraseFromParent();
1480 return;
1481 }
1482
1483 PHINode *Phi = nullptr;
1484 Value *PrevPhi = UndefVal;
1485
1486 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1487
1488 // Fill the "else" block, created in the previous iteration
1489 //
1490 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1491 // %ToLoad1 = icmp eq i1 %Mask1, true
1492 // br i1 %ToLoad1, label %cond.load, label %else
1493 //
1494 if (Idx > 0) {
1495 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1496 Phi->addIncoming(VResult, CondBlock);
1497 Phi->addIncoming(PrevPhi, PrevIfBlock);
1498 PrevPhi = Phi;
1499 VResult = Phi;
1500 }
1501
1502 Value *Predicate = Builder.CreateExtractElement(Mask,
1503 Builder.getInt32(Idx),
1504 "Mask" + Twine(Idx));
1505 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1506 ConstantInt::get(Predicate->getType(), 1),
1507 "ToLoad" + Twine(Idx));
1508
1509 // Create "cond" block
1510 //
1511 // %EltAddr = getelementptr i32* %1, i32 0
1512 // %Elt = load i32* %EltAddr
1513 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1514 //
1515 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1516 Builder.SetInsertPoint(InsertPt);
1517
1518 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1519 "Ptr" + Twine(Idx));
1520 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1521 "Load" + Twine(Idx));
1522 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1523 "Res" + Twine(Idx));
1524
1525 // Create "else" block, fill it in the next iteration
1526 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1527 Builder.SetInsertPoint(InsertPt);
1528 Instruction *OldBr = IfBlock->getTerminator();
1529 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1530 OldBr->eraseFromParent();
1531 PrevIfBlock = IfBlock;
1532 IfBlock = NewIfBlock;
1533 }
1534
1535 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1536 Phi->addIncoming(VResult, CondBlock);
1537 Phi->addIncoming(PrevPhi, PrevIfBlock);
1538 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1539 CI->replaceAllUsesWith(NewI);
1540 CI->eraseFromParent();
1541}
1542
1543// Translate a masked scatter intrinsic, like
1544// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1545// <16 x i1> %Mask)
1546// to a chain of basic blocks, that stores element one-by-one if
1547// the appropriate mask bit is set.
1548//
1549// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1550// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1551// % ToStore0 = icmp eq i1 % Mask0, true
1552// br i1 %ToStore0, label %cond.store, label %else
1553//
1554// cond.store:
1555// % Elt0 = extractelement <16 x i32> %Src, i32 0
1556// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1557// store i32 %Elt0, i32* % Ptr0, align 4
1558// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001559//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001560// else:
1561// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1562// % ToStore1 = icmp eq i1 % Mask1, true
1563// br i1 % ToStore1, label %cond.store1, label %else2
1564//
1565// cond.store1:
1566// % Elt1 = extractelement <16 x i32> %Src, i32 1
1567// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1568// store i32 % Elt1, i32* % Ptr1, align 4
1569// br label %else2
1570// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001571static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001572 Value *Src = CI->getArgOperand(0);
1573 Value *Ptrs = CI->getArgOperand(1);
1574 Value *Alignment = CI->getArgOperand(2);
1575 Value *Mask = CI->getArgOperand(3);
1576
1577 assert(isa<VectorType>(Src->getType()) &&
1578 "Unexpected data type in masked scatter intrinsic");
1579 assert(isa<VectorType>(Ptrs->getType()) &&
1580 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1581 "Vector of pointers is expected in masked scatter intrinsic");
1582
1583 IRBuilder<> Builder(CI->getContext());
1584 Instruction *InsertPt = CI;
1585 BasicBlock *IfBlock = CI->getParent();
1586 Builder.SetInsertPoint(InsertPt);
1587 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1588
1589 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1590 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1591
1592 // Shorten the way if the mask is a vector of constants.
1593 bool IsConstMask = isa<ConstantVector>(Mask);
1594
1595 if (IsConstMask) {
1596 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1597 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1598 continue;
1599 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1600 "Elt" + Twine(Idx));
1601 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1602 "Ptr" + Twine(Idx));
1603 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1604 }
1605 CI->eraseFromParent();
1606 return;
1607 }
1608 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1609 // Fill the "else" block, created in the previous iteration
1610 //
1611 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1612 // % ToStore = icmp eq i1 % Mask1, true
1613 // br i1 % ToStore, label %cond.store, label %else
1614 //
1615 Value *Predicate = Builder.CreateExtractElement(Mask,
1616 Builder.getInt32(Idx),
1617 "Mask" + Twine(Idx));
1618 Value *Cmp =
1619 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1620 ConstantInt::get(Predicate->getType(), 1),
1621 "ToStore" + Twine(Idx));
1622
1623 // Create "cond" block
1624 //
1625 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1626 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1627 // %store i32 % Elt1, i32* % Ptr1
1628 //
1629 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1630 Builder.SetInsertPoint(InsertPt);
1631
1632 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1633 "Elt" + Twine(Idx));
1634 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1635 "Ptr" + Twine(Idx));
1636 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1637
1638 // Create "else" block, fill it in the next iteration
1639 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1640 Builder.SetInsertPoint(InsertPt);
1641 Instruction *OldBr = IfBlock->getTerminator();
1642 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1643 OldBr->eraseFromParent();
1644 IfBlock = NewIfBlock;
1645 }
1646 CI->eraseFromParent();
1647}
1648
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001649/// If counting leading or trailing zeros is an expensive operation and a zero
1650/// input is defined, add a check for zero to avoid calling the intrinsic.
1651///
1652/// We want to transform:
1653/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1654///
1655/// into:
1656/// entry:
1657/// %cmpz = icmp eq i64 %A, 0
1658/// br i1 %cmpz, label %cond.end, label %cond.false
1659/// cond.false:
1660/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1661/// br label %cond.end
1662/// cond.end:
1663/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1664///
1665/// If the transform is performed, return true and set ModifiedDT to true.
1666static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1667 const TargetLowering *TLI,
1668 const DataLayout *DL,
1669 bool &ModifiedDT) {
1670 if (!TLI || !DL)
1671 return false;
1672
1673 // If a zero input is undefined, it doesn't make sense to despeculate that.
1674 if (match(CountZeros->getOperand(1), m_One()))
1675 return false;
1676
1677 // If it's cheap to speculate, there's nothing to do.
1678 auto IntrinsicID = CountZeros->getIntrinsicID();
1679 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1680 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1681 return false;
1682
1683 // Only handle legal scalar cases. Anything else requires too much work.
1684 Type *Ty = CountZeros->getType();
1685 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1686 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
1687 return false;
1688
1689 // The intrinsic will be sunk behind a compare against zero and branch.
1690 BasicBlock *StartBlock = CountZeros->getParent();
1691 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1692
1693 // Create another block after the count zero intrinsic. A PHI will be added
1694 // in this block to select the result of the intrinsic or the bit-width
1695 // constant if the input to the intrinsic is zero.
1696 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1697 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1698
1699 // Set up a builder to create a compare, conditional branch, and PHI.
1700 IRBuilder<> Builder(CountZeros->getContext());
1701 Builder.SetInsertPoint(StartBlock->getTerminator());
1702 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1703
1704 // Replace the unconditional branch that was created by the first split with
1705 // a compare against zero and a conditional branch.
1706 Value *Zero = Constant::getNullValue(Ty);
1707 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1708 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1709 StartBlock->getTerminator()->eraseFromParent();
1710
1711 // Create a PHI in the end block to select either the output of the intrinsic
1712 // or the bit width of the operand.
1713 Builder.SetInsertPoint(&EndBlock->front());
1714 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1715 CountZeros->replaceAllUsesWith(PN);
1716 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1717 PN->addIncoming(BitWidth, StartBlock);
1718 PN->addIncoming(CountZeros, CallBlock);
1719
1720 // We are explicitly handling the zero case, so we can set the intrinsic's
1721 // undefined zero argument to 'true'. This will also prevent reprocessing the
1722 // intrinsic; we only despeculate when a zero input is defined.
1723 CountZeros->setArgOperand(1, Builder.getTrue());
1724 ModifiedDT = true;
1725 return true;
1726}
1727
Sanjay Patelfc580a62015-09-21 23:03:16 +00001728bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001729 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001730
Chris Lattner7a277142011-01-15 07:14:54 +00001731 // Lower inline assembly if we can.
1732 // If we found an inline asm expession, and if the target knows how to
1733 // lower it to normal LLVM code, do so now.
1734 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1735 if (TLI->ExpandInlineAsm(CI)) {
1736 // Avoid invalidating the iterator.
1737 CurInstIterator = BB->begin();
1738 // Avoid processing instructions out of order, which could cause
1739 // reuse before a value is defined.
1740 SunkAddrs.clear();
1741 return true;
1742 }
1743 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001744 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001745 return true;
1746 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001747
John Brawn0dbcd652015-03-18 12:01:59 +00001748 // Align the pointer arguments to this call if the target thinks it's a good
1749 // idea
1750 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001751 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001752 for (auto &Arg : CI->arg_operands()) {
1753 // We want to align both objects whose address is used directly and
1754 // objects whose address is used in casts and GEPs, though it only makes
1755 // sense for GEPs if the offset is a multiple of the desired alignment and
1756 // if size - offset meets the size threshold.
1757 if (!Arg->getType()->isPointerTy())
1758 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001759 APInt Offset(DL->getPointerSizeInBits(
1760 cast<PointerType>(Arg->getType())->getAddressSpace()),
1761 0);
1762 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001763 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001764 if ((Offset2 & (PrefAlign-1)) != 0)
1765 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001766 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001767 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1768 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001769 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001770 // Global variables can only be aligned if they are defined in this
1771 // object (i.e. they are uniquely initialized in this object), and
1772 // over-aligning global variables that have an explicit section is
1773 // forbidden.
1774 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001775 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
1776 GV->getAlignment() < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001777 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001778 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001779 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001780 }
1781 // If this is a memcpy (or similar) then we may be able to improve the
1782 // alignment
1783 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001784 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001785 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001786 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001787 if (Align > MI->getAlignment())
1788 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001789 }
1790 }
1791
Philip Reamesac115ed2016-03-09 23:13:12 +00001792 // If we have a cold call site, try to sink addressing computation into the
1793 // cold block. This interacts with our handling for loads and stores to
1794 // ensure that we can fold all uses of a potential addressing computation
1795 // into their uses. TODO: generalize this to work over profiling data
1796 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1797 for (auto &Arg : CI->arg_operands()) {
1798 if (!Arg->getType()->isPointerTy())
1799 continue;
1800 unsigned AS = Arg->getType()->getPointerAddressSpace();
1801 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1802 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001803
Eric Christopher4b7948e2010-03-11 02:41:03 +00001804 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001805 if (II) {
1806 switch (II->getIntrinsicID()) {
1807 default: break;
1808 case Intrinsic::objectsize: {
1809 // Lower all uses of llvm.objectsize.*
1810 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1811 Type *ReturnTy = CI->getType();
1812 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001813
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001814 // Substituting this can cause recursive simplifications, which can
1815 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1816 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001817 Value *CurValue = &*CurInstIterator;
1818 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001819
Sanjay Patel545a4562016-01-20 18:59:16 +00001820 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001821
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001822 // If the iterator instruction was recursively deleted, start over at the
1823 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001824 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001825 CurInstIterator = BB->begin();
1826 SunkAddrs.clear();
1827 }
1828 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001829 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001830 case Intrinsic::masked_load: {
1831 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001832 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001833 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001834 ModifiedDT = true;
1835 return true;
1836 }
1837 return false;
1838 }
1839 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001840 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001841 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001842 ModifiedDT = true;
1843 return true;
1844 }
1845 return false;
1846 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001847 case Intrinsic::masked_gather: {
1848 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001849 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001850 ModifiedDT = true;
1851 return true;
1852 }
1853 return false;
1854 }
1855 case Intrinsic::masked_scatter: {
1856 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001857 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001858 ModifiedDT = true;
1859 return true;
1860 }
1861 return false;
1862 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001863 case Intrinsic::aarch64_stlxr:
1864 case Intrinsic::aarch64_stxr: {
1865 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1866 if (!ExtVal || !ExtVal->hasOneUse() ||
1867 ExtVal->getParent() == CI->getParent())
1868 return false;
1869 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1870 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001871 // Mark this instruction as "inserted by CGP", so that other
1872 // optimizations don't touch it.
1873 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001874 return true;
1875 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001876 case Intrinsic::invariant_group_barrier:
1877 II->replaceAllUsesWith(II->getArgOperand(0));
1878 II->eraseFromParent();
1879 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001880
1881 case Intrinsic::cttz:
1882 case Intrinsic::ctlz:
1883 // If counting zeros is expensive, try to avoid it.
1884 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001885 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001886
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001887 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001888 // Unknown address space.
1889 // TODO: Target hook to pick which address space the intrinsic cares
1890 // about?
1891 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001892 SmallVector<Value*, 2> PtrOps;
1893 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001894 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001895 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001896 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001897 return true;
1898 }
Pete Cooper615fd892012-03-13 20:59:56 +00001899 }
1900
Eric Christopher4b7948e2010-03-11 02:41:03 +00001901 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001902 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001903
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001904 // Lower all default uses of _chk calls. This is very similar
1905 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001906 // to fortified library functions (e.g. __memcpy_chk) that have the default
1907 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001908 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001909 if (Value *V = Simplifier.optimizeCall(CI)) {
1910 CI->replaceAllUsesWith(V);
1911 CI->eraseFromParent();
1912 return true;
1913 }
1914 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001915}
Chris Lattner1b93be52011-01-15 07:25:29 +00001916
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001917/// Look for opportunities to duplicate return instructions to the predecessor
1918/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001919/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001920/// bb0:
1921/// %tmp0 = tail call i32 @f0()
1922/// br label %return
1923/// bb1:
1924/// %tmp1 = tail call i32 @f1()
1925/// br label %return
1926/// bb2:
1927/// %tmp2 = tail call i32 @f2()
1928/// br label %return
1929/// return:
1930/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1931/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001932/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001933///
1934/// =>
1935///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001936/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001937/// bb0:
1938/// %tmp0 = tail call i32 @f0()
1939/// ret i32 %tmp0
1940/// bb1:
1941/// %tmp1 = tail call i32 @f1()
1942/// ret i32 %tmp1
1943/// bb2:
1944/// %tmp2 = tail call i32 @f2()
1945/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001946/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001947bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001948 if (!TLI)
1949 return false;
1950
Benjamin Kramer455fa352012-11-23 19:17:06 +00001951 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1952 if (!RI)
1953 return false;
1954
Craig Topperc0196b12014-04-14 00:51:57 +00001955 PHINode *PN = nullptr;
1956 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001957 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001958 if (V) {
1959 BCI = dyn_cast<BitCastInst>(V);
1960 if (BCI)
1961 V = BCI->getOperand(0);
1962
1963 PN = dyn_cast<PHINode>(V);
1964 if (!PN)
1965 return false;
1966 }
Evan Cheng0663f232011-03-21 01:19:09 +00001967
Cameron Zwarich4649f172011-03-24 04:52:10 +00001968 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001969 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001970
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001971 // It's not safe to eliminate the sign / zero extension of the return value.
1972 // See llvm::isInTailCallPosition().
1973 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001974 AttributeSet CallerAttrs = F->getAttributes();
1975 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1976 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001977 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001978
Cameron Zwarich4649f172011-03-24 04:52:10 +00001979 // Make sure there are no instructions between the PHI and return, or that the
1980 // return is the first instruction in the block.
1981 if (PN) {
1982 BasicBlock::iterator BI = BB->begin();
1983 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001984 if (&*BI == BCI)
1985 // Also skip over the bitcast.
1986 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001987 if (&*BI != RI)
1988 return false;
1989 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001990 BasicBlock::iterator BI = BB->begin();
1991 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1992 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001993 return false;
1994 }
Evan Cheng0663f232011-03-21 01:19:09 +00001995
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001996 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1997 /// call.
1998 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001999 if (PN) {
2000 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2001 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2002 // Make sure the phi value is indeed produced by the tail call.
2003 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2004 TLI->mayBeEmittedAsTailCall(CI))
2005 TailCalls.push_back(CI);
2006 }
2007 } else {
2008 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002009 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002010 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002011 continue;
2012
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002013 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002014 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2015 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002016 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2017 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002018 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002019
Cameron Zwarich4649f172011-03-24 04:52:10 +00002020 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00002021 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002022 TailCalls.push_back(CI);
2023 }
Evan Cheng0663f232011-03-21 01:19:09 +00002024 }
2025
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002026 bool Changed = false;
2027 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2028 CallInst *CI = TailCalls[i];
2029 CallSite CS(CI);
2030
2031 // Conservatively require the attributes of the call to match those of the
2032 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002033 AttributeSet CalleeAttrs = CS.getAttributes();
2034 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002035 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002036 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002037 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002038 continue;
2039
2040 // Make sure the call instruction is followed by an unconditional branch to
2041 // the return block.
2042 BasicBlock *CallBB = CI->getParent();
2043 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2044 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2045 continue;
2046
2047 // Duplicate the return into CallBB.
2048 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002049 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002050 ++NumRetsDup;
2051 }
2052
2053 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002054 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002055 BB->eraseFromParent();
2056
2057 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002058}
2059
Chris Lattner728f9022008-11-25 07:09:13 +00002060//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002061// Memory Optimization
2062//===----------------------------------------------------------------------===//
2063
Chandler Carruthc8925912013-01-05 02:09:22 +00002064namespace {
2065
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002066/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002067/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002068struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002069 Value *BaseReg;
2070 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002071 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002072 void print(raw_ostream &OS) const;
2073 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002074
Chandler Carruthc8925912013-01-05 02:09:22 +00002075 bool operator==(const ExtAddrMode& O) const {
2076 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2077 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2078 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2079 }
2080};
2081
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002082#ifndef NDEBUG
2083static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2084 AM.print(OS);
2085 return OS;
2086}
2087#endif
2088
Chandler Carruthc8925912013-01-05 02:09:22 +00002089void ExtAddrMode::print(raw_ostream &OS) const {
2090 bool NeedPlus = false;
2091 OS << "[";
2092 if (BaseGV) {
2093 OS << (NeedPlus ? " + " : "")
2094 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002095 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002096 NeedPlus = true;
2097 }
2098
Richard Trieuc0f91212014-05-30 03:15:17 +00002099 if (BaseOffs) {
2100 OS << (NeedPlus ? " + " : "")
2101 << BaseOffs;
2102 NeedPlus = true;
2103 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002104
2105 if (BaseReg) {
2106 OS << (NeedPlus ? " + " : "")
2107 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002108 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002109 NeedPlus = true;
2110 }
2111 if (Scale) {
2112 OS << (NeedPlus ? " + " : "")
2113 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002114 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002115 }
2116
2117 OS << ']';
2118}
2119
2120#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002121LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002122 print(dbgs());
2123 dbgs() << '\n';
2124}
2125#endif
2126
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002127/// \brief This class provides transaction based operation on the IR.
2128/// Every change made through this class is recorded in the internal state and
2129/// can be undone (rollback) until commit is called.
2130class TypePromotionTransaction {
2131
2132 /// \brief This represents the common interface of the individual transaction.
2133 /// Each class implements the logic for doing one specific modification on
2134 /// the IR via the TypePromotionTransaction.
2135 class TypePromotionAction {
2136 protected:
2137 /// The Instruction modified.
2138 Instruction *Inst;
2139
2140 public:
2141 /// \brief Constructor of the action.
2142 /// The constructor performs the related action on the IR.
2143 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2144
2145 virtual ~TypePromotionAction() {}
2146
2147 /// \brief Undo the modification done by this action.
2148 /// When this method is called, the IR must be in the same state as it was
2149 /// before this action was applied.
2150 /// \pre Undoing the action works if and only if the IR is in the exact same
2151 /// state as it was directly after this action was applied.
2152 virtual void undo() = 0;
2153
2154 /// \brief Advocate every change made by this action.
2155 /// When the results on the IR of the action are to be kept, it is important
2156 /// to call this function, otherwise hidden information may be kept forever.
2157 virtual void commit() {
2158 // Nothing to be done, this action is not doing anything.
2159 }
2160 };
2161
2162 /// \brief Utility to remember the position of an instruction.
2163 class InsertionHandler {
2164 /// Position of an instruction.
2165 /// Either an instruction:
2166 /// - Is the first in a basic block: BB is used.
2167 /// - Has a previous instructon: PrevInst is used.
2168 union {
2169 Instruction *PrevInst;
2170 BasicBlock *BB;
2171 } Point;
2172 /// Remember whether or not the instruction had a previous instruction.
2173 bool HasPrevInstruction;
2174
2175 public:
2176 /// \brief Record the position of \p Inst.
2177 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002178 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002179 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2180 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002181 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002182 else
2183 Point.BB = Inst->getParent();
2184 }
2185
2186 /// \brief Insert \p Inst at the recorded position.
2187 void insert(Instruction *Inst) {
2188 if (HasPrevInstruction) {
2189 if (Inst->getParent())
2190 Inst->removeFromParent();
2191 Inst->insertAfter(Point.PrevInst);
2192 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002193 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002194 if (Inst->getParent())
2195 Inst->moveBefore(Position);
2196 else
2197 Inst->insertBefore(Position);
2198 }
2199 }
2200 };
2201
2202 /// \brief Move an instruction before another.
2203 class InstructionMoveBefore : public TypePromotionAction {
2204 /// Original position of the instruction.
2205 InsertionHandler Position;
2206
2207 public:
2208 /// \brief Move \p Inst before \p Before.
2209 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2210 : TypePromotionAction(Inst), Position(Inst) {
2211 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2212 Inst->moveBefore(Before);
2213 }
2214
2215 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002216 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002217 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2218 Position.insert(Inst);
2219 }
2220 };
2221
2222 /// \brief Set the operand of an instruction with a new value.
2223 class OperandSetter : public TypePromotionAction {
2224 /// Original operand of the instruction.
2225 Value *Origin;
2226 /// Index of the modified instruction.
2227 unsigned Idx;
2228
2229 public:
2230 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2231 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2232 : TypePromotionAction(Inst), Idx(Idx) {
2233 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2234 << "for:" << *Inst << "\n"
2235 << "with:" << *NewVal << "\n");
2236 Origin = Inst->getOperand(Idx);
2237 Inst->setOperand(Idx, NewVal);
2238 }
2239
2240 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002241 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002242 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2243 << "for: " << *Inst << "\n"
2244 << "with: " << *Origin << "\n");
2245 Inst->setOperand(Idx, Origin);
2246 }
2247 };
2248
2249 /// \brief Hide the operands of an instruction.
2250 /// Do as if this instruction was not using any of its operands.
2251 class OperandsHider : public TypePromotionAction {
2252 /// The list of original operands.
2253 SmallVector<Value *, 4> OriginalValues;
2254
2255 public:
2256 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2257 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2258 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2259 unsigned NumOpnds = Inst->getNumOperands();
2260 OriginalValues.reserve(NumOpnds);
2261 for (unsigned It = 0; It < NumOpnds; ++It) {
2262 // Save the current operand.
2263 Value *Val = Inst->getOperand(It);
2264 OriginalValues.push_back(Val);
2265 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002266 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002267 // that we are not willing to pay.
2268 Inst->setOperand(It, UndefValue::get(Val->getType()));
2269 }
2270 }
2271
2272 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002273 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002274 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2275 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2276 Inst->setOperand(It, OriginalValues[It]);
2277 }
2278 };
2279
2280 /// \brief Build a truncate instruction.
2281 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002282 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002283 public:
2284 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2285 /// result.
2286 /// trunc Opnd to Ty.
2287 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2288 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002289 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2290 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002291 }
2292
Quentin Colombetac55b152014-09-16 22:36:07 +00002293 /// \brief Get the built value.
2294 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002295
2296 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002297 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002298 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2299 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2300 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002301 }
2302 };
2303
2304 /// \brief Build a sign extension instruction.
2305 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002306 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002307 public:
2308 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2309 /// result.
2310 /// sext Opnd to Ty.
2311 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002312 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002313 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002314 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2315 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002316 }
2317
Quentin Colombetac55b152014-09-16 22:36:07 +00002318 /// \brief Get the built value.
2319 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320
2321 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002322 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002323 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2324 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2325 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 }
2327 };
2328
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002329 /// \brief Build a zero extension instruction.
2330 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002331 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002332 public:
2333 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2334 /// result.
2335 /// zext Opnd to Ty.
2336 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002337 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002338 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002339 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2340 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002341 }
2342
Quentin Colombetac55b152014-09-16 22:36:07 +00002343 /// \brief Get the built value.
2344 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002345
2346 /// \brief Remove the built instruction.
2347 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002348 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2349 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2350 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002351 }
2352 };
2353
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002354 /// \brief Mutate an instruction to another type.
2355 class TypeMutator : public TypePromotionAction {
2356 /// Record the original type.
2357 Type *OrigTy;
2358
2359 public:
2360 /// \brief Mutate the type of \p Inst into \p NewTy.
2361 TypeMutator(Instruction *Inst, Type *NewTy)
2362 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2363 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2364 << "\n");
2365 Inst->mutateType(NewTy);
2366 }
2367
2368 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002369 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002370 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2371 << "\n");
2372 Inst->mutateType(OrigTy);
2373 }
2374 };
2375
2376 /// \brief Replace the uses of an instruction by another instruction.
2377 class UsesReplacer : public TypePromotionAction {
2378 /// Helper structure to keep track of the replaced uses.
2379 struct InstructionAndIdx {
2380 /// The instruction using the instruction.
2381 Instruction *Inst;
2382 /// The index where this instruction is used for Inst.
2383 unsigned Idx;
2384 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2385 : Inst(Inst), Idx(Idx) {}
2386 };
2387
2388 /// Keep track of the original uses (pair Instruction, Index).
2389 SmallVector<InstructionAndIdx, 4> OriginalUses;
2390 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2391
2392 public:
2393 /// \brief Replace all the use of \p Inst by \p New.
2394 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2395 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2396 << "\n");
2397 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002398 for (Use &U : Inst->uses()) {
2399 Instruction *UserI = cast<Instruction>(U.getUser());
2400 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 }
2402 // Now, we can replace the uses.
2403 Inst->replaceAllUsesWith(New);
2404 }
2405
2406 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002407 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002408 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2409 for (use_iterator UseIt = OriginalUses.begin(),
2410 EndIt = OriginalUses.end();
2411 UseIt != EndIt; ++UseIt) {
2412 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2413 }
2414 }
2415 };
2416
2417 /// \brief Remove an instruction from the IR.
2418 class InstructionRemover : public TypePromotionAction {
2419 /// Original position of the instruction.
2420 InsertionHandler Inserter;
2421 /// Helper structure to hide all the link to the instruction. In other
2422 /// words, this helps to do as if the instruction was removed.
2423 OperandsHider Hider;
2424 /// Keep track of the uses replaced, if any.
2425 UsesReplacer *Replacer;
2426
2427 public:
2428 /// \brief Remove all reference of \p Inst and optinally replace all its
2429 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002430 /// \pre If !Inst->use_empty(), then New != nullptr
2431 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002432 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002433 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002434 if (New)
2435 Replacer = new UsesReplacer(Inst, New);
2436 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2437 Inst->removeFromParent();
2438 }
2439
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002440 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002441
2442 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002443 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002444
2445 /// \brief Resurrect the instruction and reassign it to the proper uses if
2446 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002447 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002448 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2449 Inserter.insert(Inst);
2450 if (Replacer)
2451 Replacer->undo();
2452 Hider.undo();
2453 }
2454 };
2455
2456public:
2457 /// Restoration point.
2458 /// The restoration point is a pointer to an action instead of an iterator
2459 /// because the iterator may be invalidated but not the pointer.
2460 typedef const TypePromotionAction *ConstRestorationPt;
2461 /// Advocate every changes made in that transaction.
2462 void commit();
2463 /// Undo all the changes made after the given point.
2464 void rollback(ConstRestorationPt Point);
2465 /// Get the current restoration point.
2466 ConstRestorationPt getRestorationPoint() const;
2467
2468 /// \name API for IR modification with state keeping to support rollback.
2469 /// @{
2470 /// Same as Instruction::setOperand.
2471 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2472 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002473 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002474 /// Same as Value::replaceAllUsesWith.
2475 void replaceAllUsesWith(Instruction *Inst, Value *New);
2476 /// Same as Value::mutateType.
2477 void mutateType(Instruction *Inst, Type *NewTy);
2478 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002479 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002480 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002481 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002482 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002483 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002484 /// Same as Instruction::moveBefore.
2485 void moveBefore(Instruction *Inst, Instruction *Before);
2486 /// @}
2487
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002488private:
2489 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002490 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2491 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002492};
2493
2494void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2495 Value *NewVal) {
2496 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002497 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002498}
2499
2500void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2501 Value *NewVal) {
2502 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002503 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002504}
2505
2506void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2507 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002508 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002509}
2510
2511void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002512 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002513}
2514
Quentin Colombetac55b152014-09-16 22:36:07 +00002515Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2516 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002517 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002518 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002519 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002520 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002521}
2522
Quentin Colombetac55b152014-09-16 22:36:07 +00002523Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2524 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002525 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002526 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002527 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002528 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002529}
2530
Quentin Colombetac55b152014-09-16 22:36:07 +00002531Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2532 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002533 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002534 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002535 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002536 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002537}
2538
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002539void TypePromotionTransaction::moveBefore(Instruction *Inst,
2540 Instruction *Before) {
2541 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002542 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543}
2544
2545TypePromotionTransaction::ConstRestorationPt
2546TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002547 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002548}
2549
2550void TypePromotionTransaction::commit() {
2551 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002552 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002553 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002554 Actions.clear();
2555}
2556
2557void TypePromotionTransaction::rollback(
2558 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002559 while (!Actions.empty() && Point != Actions.back().get()) {
2560 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002561 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002562 }
2563}
2564
Chandler Carruthc8925912013-01-05 02:09:22 +00002565/// \brief A helper class for matching addressing modes.
2566///
2567/// This encapsulates the logic for matching the target-legal addressing modes.
2568class AddressingModeMatcher {
2569 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002570 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002571 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002572 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002573
2574 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2575 /// the memory instruction that we're computing this address for.
2576 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002577 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002578 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002579
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002580 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002581 /// part of the return value of this addressing mode matching stuff.
2582 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002583
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002584 /// The instructions inserted by other CodeGenPrepare optimizations.
2585 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586 /// A map from the instructions to their type before promotion.
2587 InstrToOrigTy &PromotedInsts;
2588 /// The ongoing transaction where every action should be registered.
2589 TypePromotionTransaction &TPT;
2590
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002591 /// This is set to true when we should not do profitability checks.
2592 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002593 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002594
Eric Christopherd75c00c2015-02-26 22:38:34 +00002595 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002596 const TargetMachine &TM, Type *AT, unsigned AS,
2597 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002598 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 InstrToOrigTy &PromotedInsts,
2600 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002601 : AddrModeInsts(AMI), TM(TM),
2602 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2603 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002604 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2605 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2606 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002607 IgnoreProfitability = false;
2608 }
2609public:
Stephen Lin837bba12013-07-15 17:55:02 +00002610
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002611 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002612 /// give an access type of AccessTy. This returns a list of involved
2613 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002614 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002615 /// optimizations.
2616 /// \p PromotedInsts maps the instructions to their type before promotion.
2617 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002618 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002619 Instruction *MemoryInst,
2620 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002621 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002622 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002623 InstrToOrigTy &PromotedInsts,
2624 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002625 ExtAddrMode Result;
2626
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002627 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002628 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002629 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002630 (void)Success; assert(Success && "Couldn't select *anything*?");
2631 return Result;
2632 }
2633private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002634 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2635 bool matchAddr(Value *V, unsigned Depth);
2636 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002637 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002638 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002639 ExtAddrMode &AMBefore,
2640 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002641 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2642 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002643 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002644};
2645
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002646/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002647/// Return true and update AddrMode if this addr mode is legal for the target,
2648/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002649bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002650 unsigned Depth) {
2651 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2652 // mode. Just process that directly.
2653 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002654 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002655
Chandler Carruthc8925912013-01-05 02:09:22 +00002656 // If the scale is 0, it takes nothing to add this.
2657 if (Scale == 0)
2658 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002659
Chandler Carruthc8925912013-01-05 02:09:22 +00002660 // If we already have a scale of this value, we can add to it, otherwise, we
2661 // need an available scale field.
2662 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2663 return false;
2664
2665 ExtAddrMode TestAddrMode = AddrMode;
2666
2667 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2668 // [A+B + A*7] -> [B+A*8].
2669 TestAddrMode.Scale += Scale;
2670 TestAddrMode.ScaledReg = ScaleReg;
2671
2672 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002673 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002674 return false;
2675
2676 // It was legal, so commit it.
2677 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002678
Chandler Carruthc8925912013-01-05 02:09:22 +00002679 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2680 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2681 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002682 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002683 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2684 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2685 TestAddrMode.ScaledReg = AddLHS;
2686 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002687
Chandler Carruthc8925912013-01-05 02:09:22 +00002688 // If this addressing mode is legal, commit it and remember that we folded
2689 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002690 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002691 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2692 AddrMode = TestAddrMode;
2693 return true;
2694 }
2695 }
2696
2697 // Otherwise, not (x+c)*scale, just return what we have.
2698 return true;
2699}
2700
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002701/// This is a little filter, which returns true if an addressing computation
2702/// involving I might be folded into a load/store accessing it.
2703/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002704/// the set of instructions that MatchOperationAddr can.
2705static bool MightBeFoldableInst(Instruction *I) {
2706 switch (I->getOpcode()) {
2707 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002708 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002709 // Don't touch identity bitcasts.
2710 if (I->getType() == I->getOperand(0)->getType())
2711 return false;
2712 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2713 case Instruction::PtrToInt:
2714 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2715 return true;
2716 case Instruction::IntToPtr:
2717 // We know the input is intptr_t, so this is foldable.
2718 return true;
2719 case Instruction::Add:
2720 return true;
2721 case Instruction::Mul:
2722 case Instruction::Shl:
2723 // Can only handle X*C and X << C.
2724 return isa<ConstantInt>(I->getOperand(1));
2725 case Instruction::GetElementPtr:
2726 return true;
2727 default:
2728 return false;
2729 }
2730}
2731
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002732/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2733/// \note \p Val is assumed to be the product of some type promotion.
2734/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2735/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002736static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2737 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002738 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2739 if (!PromotedInst)
2740 return false;
2741 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2742 // If the ISDOpcode is undefined, it was undefined before the promotion.
2743 if (!ISDOpcode)
2744 return true;
2745 // Otherwise, check if the promoted instruction is legal or not.
2746 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002747 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002748}
2749
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002750/// \brief Hepler class to perform type promotion.
2751class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002752 /// \brief Utility function to check whether or not a sign or zero extension
2753 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2754 /// either using the operands of \p Inst or promoting \p Inst.
2755 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002756 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002757 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002758 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002759 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002760 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002761 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002762 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002763 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2764 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002765
2766 /// \brief Utility function to determine if \p OpIdx should be promoted when
2767 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002768 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002769 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002770 }
2771
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002772 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002773 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002774 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002775 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002776 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002777 /// Newly added extensions are inserted in \p Exts.
2778 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002779 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002780 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002781 static Value *promoteOperandForTruncAndAnyExt(
2782 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002783 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002784 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002785 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002786
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002787 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002788 /// operand is promotable and is not a supported trunc or sext.
2789 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002790 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002791 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002792 /// Newly added extensions are inserted in \p Exts.
2793 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002794 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002795 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002796 static Value *promoteOperandForOther(Instruction *Ext,
2797 TypePromotionTransaction &TPT,
2798 InstrToOrigTy &PromotedInsts,
2799 unsigned &CreatedInstsCost,
2800 SmallVectorImpl<Instruction *> *Exts,
2801 SmallVectorImpl<Instruction *> *Truncs,
2802 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002803
2804 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002805 static Value *signExtendOperandForOther(
2806 Instruction *Ext, TypePromotionTransaction &TPT,
2807 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2808 SmallVectorImpl<Instruction *> *Exts,
2809 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2810 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2811 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002812 }
2813
2814 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002815 static Value *zeroExtendOperandForOther(
2816 Instruction *Ext, TypePromotionTransaction &TPT,
2817 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2818 SmallVectorImpl<Instruction *> *Exts,
2819 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2820 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2821 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002822 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002823
2824public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002825 /// Type for the utility function that promotes the operand of Ext.
2826 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002827 InstrToOrigTy &PromotedInsts,
2828 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002829 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002830 SmallVectorImpl<Instruction *> *Truncs,
2831 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002832 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2833 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002834 /// \return NULL if no promotable action is possible with the current
2835 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002836 /// \p InsertedInsts keeps track of all the instructions inserted by the
2837 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002838 /// because we do not want to promote these instructions as CodeGenPrepare
2839 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2840 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002841 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002842 const TargetLowering &TLI,
2843 const InstrToOrigTy &PromotedInsts);
2844};
2845
2846bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002847 Type *ConsideredExtType,
2848 const InstrToOrigTy &PromotedInsts,
2849 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002850 // The promotion helper does not know how to deal with vector types yet.
2851 // To be able to fix that, we would need to fix the places where we
2852 // statically extend, e.g., constants and such.
2853 if (Inst->getType()->isVectorTy())
2854 return false;
2855
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002856 // We can always get through zext.
2857 if (isa<ZExtInst>(Inst))
2858 return true;
2859
2860 // sext(sext) is ok too.
2861 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002862 return true;
2863
2864 // We can get through binary operator, if it is legal. In other words, the
2865 // binary operator must have a nuw or nsw flag.
2866 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2867 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002868 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2869 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002870 return true;
2871
2872 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002873 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002874 if (!isa<TruncInst>(Inst))
2875 return false;
2876
2877 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002878 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002879 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002880 if (!OpndVal->getType()->isIntegerTy() ||
2881 OpndVal->getType()->getIntegerBitWidth() >
2882 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002883 return false;
2884
2885 // If the operand of the truncate is not an instruction, we will not have
2886 // any information on the dropped bits.
2887 // (Actually we could for constant but it is not worth the extra logic).
2888 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2889 if (!Opnd)
2890 return false;
2891
2892 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002893 // I.e., check that trunc just drops extended bits of the same kind of
2894 // the extension.
2895 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002896 const Type *OpndType;
2897 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002898 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2899 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002900 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2901 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002902 else
2903 return false;
2904
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002905 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002906 return Inst->getType()->getIntegerBitWidth() >=
2907 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002908}
2909
2910TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002911 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002912 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002913 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2914 "Unexpected instruction type");
2915 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2916 Type *ExtTy = Ext->getType();
2917 bool IsSExt = isa<SExtInst>(Ext);
2918 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002919 // get through.
2920 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002921 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002922 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002923
2924 // Do not promote if the operand has been added by codegenprepare.
2925 // Otherwise, it means we are undoing an optimization that is likely to be
2926 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002927 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002928 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002929
2930 // SExt or Trunc instructions.
2931 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002932 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2933 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002934 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002935
2936 // Regular instruction.
2937 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002938 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002939 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002940 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002941}
2942
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002943Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002944 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002945 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002946 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002947 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002948 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2949 // get through it and this method should not be called.
2950 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002951 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002952 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002953 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002954 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002955 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002956 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002957 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002958 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2959 TPT.replaceAllUsesWith(SExt, ZExt);
2960 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002961 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002962 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002963 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2964 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002965 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2966 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002967 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002968
2969 // Remove dead code.
2970 if (SExtOpnd->use_empty())
2971 TPT.eraseInstruction(SExtOpnd);
2972
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002973 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002974 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002975 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002976 if (ExtInst) {
2977 if (Exts)
2978 Exts->push_back(ExtInst);
2979 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2980 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002981 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002982 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002983
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002984 // At this point we have: ext ty opnd to ty.
2985 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2986 Value *NextVal = ExtInst->getOperand(0);
2987 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002988 return NextVal;
2989}
2990
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002991Value *TypePromotionHelper::promoteOperandForOther(
2992 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002993 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002994 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002995 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2996 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002997 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002998 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002999 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003000 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003001 if (!ExtOpnd->hasOneUse()) {
3002 // ExtOpnd will be promoted.
3003 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003004 // promoted version.
3005 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003006 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003007 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3008 ITrunc->removeFromParent();
3009 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003010 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003011 if (Truncs)
3012 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003013 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003014
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003015 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003016 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003017 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003018 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003019 }
3020
3021 // Get through the Instruction:
3022 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003023 // 2. Replace the uses of Ext by Inst.
3024 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003025
3026 // Remember the original type of the instruction before promotion.
3027 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003028 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3029 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003030 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003031 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003032 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003033 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003034 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003035 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003037 DEBUG(dbgs() << "Propagate Ext to operands\n");
3038 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003039 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003040 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3041 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3042 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003043 DEBUG(dbgs() << "No need to propagate\n");
3044 continue;
3045 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003046 // Check if we can statically extend the operand.
3047 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003048 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003049 DEBUG(dbgs() << "Statically extend\n");
3050 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3051 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3052 : Cst->getValue().zext(BitWidth);
3053 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003054 continue;
3055 }
3056 // UndefValue are typed, so we have to statically sign extend them.
3057 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003058 DEBUG(dbgs() << "Statically extend\n");
3059 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003060 continue;
3061 }
3062
3063 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003064 // Check if Ext was reused to extend an operand.
3065 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003066 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003067 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003068 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3069 : TPT.createZExt(Ext, Opnd, Ext->getType());
3070 if (!isa<Instruction>(ValForExtOpnd)) {
3071 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3072 continue;
3073 }
3074 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003075 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003076 if (Exts)
3077 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003078 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003079
3080 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003081 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3082 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003083 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003084 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003085 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003086 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003087 if (ExtForOpnd == Ext) {
3088 DEBUG(dbgs() << "Extension is useless now\n");
3089 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003090 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003091 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003092}
3093
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003094/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003095/// \p NewCost gives the cost of extension instructions created by the
3096/// promotion.
3097/// \p OldCost gives the cost of extension instructions before the promotion
3098/// plus the number of instructions that have been
3099/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003100/// \p PromotedOperand is the value that has been promoted.
3101/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003102bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003103 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3104 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3105 // The cost of the new extensions is greater than the cost of the
3106 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003107 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003108 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003109 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003110 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003111 return true;
3112 // The promotion is neutral but it may help folding the sign extension in
3113 // loads for instance.
3114 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003115 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003116}
3117
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003118/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003119/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003120/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003121/// If \p MovedAway is not NULL, it contains the information of whether or
3122/// not AddrInst has to be folded into the addressing mode on success.
3123/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3124/// because it has been moved away.
3125/// Thus AddrInst must not be added in the matched instructions.
3126/// This state can happen when AddrInst is a sext, since it may be moved away.
3127/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3128/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003129bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003130 unsigned Depth,
3131 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003132 // Avoid exponential behavior on extremely deep expression trees.
3133 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003134
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003135 // By default, all matched instructions stay in place.
3136 if (MovedAway)
3137 *MovedAway = false;
3138
Chandler Carruthc8925912013-01-05 02:09:22 +00003139 switch (Opcode) {
3140 case Instruction::PtrToInt:
3141 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003142 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003143 case Instruction::IntToPtr: {
3144 auto AS = AddrInst->getType()->getPointerAddressSpace();
3145 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003146 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003147 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003148 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003149 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003150 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003151 case Instruction::BitCast:
3152 // BitCast is always a noop, and we can handle it as long as it is
3153 // int->int or pointer->pointer (we don't want int<->fp or something).
3154 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3155 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3156 // Don't touch identity bitcasts. These were probably put here by LSR,
3157 // and we don't want to mess around with them. Assume it knows what it
3158 // is doing.
3159 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003160 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003161 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003162 case Instruction::AddrSpaceCast: {
3163 unsigned SrcAS
3164 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3165 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3166 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003167 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003168 return false;
3169 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 case Instruction::Add: {
3171 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3172 ExtAddrMode BackupAddrMode = AddrMode;
3173 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003174 // Start a transaction at this point.
3175 // The LHS may match but not the RHS.
3176 // Therefore, we need a higher level restoration point to undo partially
3177 // matched operation.
3178 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3179 TPT.getRestorationPoint();
3180
Sanjay Patelfc580a62015-09-21 23:03:16 +00003181 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3182 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003183 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003184
Chandler Carruthc8925912013-01-05 02:09:22 +00003185 // Restore the old addr mode info.
3186 AddrMode = BackupAddrMode;
3187 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003188 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003189
Chandler Carruthc8925912013-01-05 02:09:22 +00003190 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003191 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3192 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003193 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003194
Chandler Carruthc8925912013-01-05 02:09:22 +00003195 // Otherwise we definitely can't merge the ADD in.
3196 AddrMode = BackupAddrMode;
3197 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003198 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003199 break;
3200 }
3201 //case Instruction::Or:
3202 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3203 //break;
3204 case Instruction::Mul:
3205 case Instruction::Shl: {
3206 // Can only handle X*C and X << C.
3207 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003208 if (!RHS)
3209 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003210 int64_t Scale = RHS->getSExtValue();
3211 if (Opcode == Instruction::Shl)
3212 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003213
Sanjay Patelfc580a62015-09-21 23:03:16 +00003214 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003215 }
3216 case Instruction::GetElementPtr: {
3217 // Scan the GEP. We check it if it contains constant offsets and at most
3218 // one variable offset.
3219 int VariableOperand = -1;
3220 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003221
Chandler Carruthc8925912013-01-05 02:09:22 +00003222 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003223 gep_type_iterator GTI = gep_type_begin(AddrInst);
3224 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3225 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003226 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003227 unsigned Idx =
3228 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3229 ConstantOffset += SL->getElementOffset(Idx);
3230 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003231 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003232 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3233 ConstantOffset += CI->getSExtValue()*TypeSize;
3234 } else if (TypeSize) { // Scales of zero don't do anything.
3235 // We only allow one variable index at the moment.
3236 if (VariableOperand != -1)
3237 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003238
Chandler Carruthc8925912013-01-05 02:09:22 +00003239 // Remember the variable index.
3240 VariableOperand = i;
3241 VariableScale = TypeSize;
3242 }
3243 }
3244 }
Stephen Lin837bba12013-07-15 17:55:02 +00003245
Chandler Carruthc8925912013-01-05 02:09:22 +00003246 // A common case is for the GEP to only do a constant offset. In this case,
3247 // just add it to the disp field and check validity.
3248 if (VariableOperand == -1) {
3249 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003250 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003251 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003252 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003253 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003254 return true;
3255 }
3256 AddrMode.BaseOffs -= ConstantOffset;
3257 return false;
3258 }
3259
3260 // Save the valid addressing mode in case we can't match.
3261 ExtAddrMode BackupAddrMode = AddrMode;
3262 unsigned OldSize = AddrModeInsts.size();
3263
3264 // See if the scale and offset amount is valid for this target.
3265 AddrMode.BaseOffs += ConstantOffset;
3266
3267 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003268 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003269 // If it couldn't be matched, just stuff the value in a register.
3270 if (AddrMode.HasBaseReg) {
3271 AddrMode = BackupAddrMode;
3272 AddrModeInsts.resize(OldSize);
3273 return false;
3274 }
3275 AddrMode.HasBaseReg = true;
3276 AddrMode.BaseReg = AddrInst->getOperand(0);
3277 }
3278
3279 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003280 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003281 Depth)) {
3282 // If it couldn't be matched, try stuffing the base into a register
3283 // instead of matching it, and retrying the match of the scale.
3284 AddrMode = BackupAddrMode;
3285 AddrModeInsts.resize(OldSize);
3286 if (AddrMode.HasBaseReg)
3287 return false;
3288 AddrMode.HasBaseReg = true;
3289 AddrMode.BaseReg = AddrInst->getOperand(0);
3290 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003291 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003292 VariableScale, Depth)) {
3293 // If even that didn't work, bail.
3294 AddrMode = BackupAddrMode;
3295 AddrModeInsts.resize(OldSize);
3296 return false;
3297 }
3298 }
3299
3300 return true;
3301 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003302 case Instruction::SExt:
3303 case Instruction::ZExt: {
3304 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3305 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003306 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003307
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003308 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003309 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003310 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003311 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003312 if (!TPH)
3313 return false;
3314
3315 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3316 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003317 unsigned CreatedInstsCost = 0;
3318 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003319 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003320 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003321 // SExt has been moved away.
3322 // Thus either it will be rematched later in the recursive calls or it is
3323 // gone. Anyway, we must not fold it into the addressing mode at this point.
3324 // E.g.,
3325 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003326 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003327 // addr = gep base, idx
3328 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003329 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003330 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3331 // addr = gep base, op <- match
3332 if (MovedAway)
3333 *MovedAway = true;
3334
3335 assert(PromotedOperand &&
3336 "TypePromotionHelper should have filtered out those cases");
3337
3338 ExtAddrMode BackupAddrMode = AddrMode;
3339 unsigned OldSize = AddrModeInsts.size();
3340
Sanjay Patelfc580a62015-09-21 23:03:16 +00003341 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003342 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003343 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003344 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003345 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003346 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003347 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003348 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003349 AddrMode = BackupAddrMode;
3350 AddrModeInsts.resize(OldSize);
3351 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3352 TPT.rollback(LastKnownGood);
3353 return false;
3354 }
3355 return true;
3356 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003357 }
3358 return false;
3359}
3360
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003361/// If we can, try to add the value of 'Addr' into the current addressing mode.
3362/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3363/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3364/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003365///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003366bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003367 // Start a transaction at this point that we will rollback if the matching
3368 // fails.
3369 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3370 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003371 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3372 // Fold in immediates if legal for the target.
3373 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003374 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003375 return true;
3376 AddrMode.BaseOffs -= CI->getSExtValue();
3377 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3378 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003379 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003380 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003381 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003382 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003383 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003384 }
3385 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3386 ExtAddrMode BackupAddrMode = AddrMode;
3387 unsigned OldSize = AddrModeInsts.size();
3388
3389 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003390 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003391 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003392 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003393 // to check here.
3394 if (MovedAway)
3395 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003396 // Okay, it's possible to fold this. Check to see if it is actually
3397 // *profitable* to do so. We use a simple cost model to avoid increasing
3398 // register pressure too much.
3399 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003400 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003401 AddrModeInsts.push_back(I);
3402 return true;
3403 }
Stephen Lin837bba12013-07-15 17:55:02 +00003404
Chandler Carruthc8925912013-01-05 02:09:22 +00003405 // It isn't profitable to do this, roll back.
3406 //cerr << "NOT FOLDING: " << *I;
3407 AddrMode = BackupAddrMode;
3408 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003409 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003410 }
3411 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003412 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003413 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003414 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003415 } else if (isa<ConstantPointerNull>(Addr)) {
3416 // Null pointer gets folded without affecting the addressing mode.
3417 return true;
3418 }
3419
3420 // Worse case, the target should support [reg] addressing modes. :)
3421 if (!AddrMode.HasBaseReg) {
3422 AddrMode.HasBaseReg = true;
3423 AddrMode.BaseReg = Addr;
3424 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003425 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003426 return true;
3427 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003428 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003429 }
3430
3431 // If the base register is already taken, see if we can do [r+r].
3432 if (AddrMode.Scale == 0) {
3433 AddrMode.Scale = 1;
3434 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003435 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003436 return true;
3437 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003438 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003439 }
3440 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003441 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003442 return false;
3443}
3444
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003445/// Check to see if all uses of OpVal by the specified inline asm call are due
3446/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003447static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003448 const TargetMachine &TM) {
3449 const Function *F = CI->getParent()->getParent();
3450 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3451 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003452 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003453 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3454 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003455 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3456 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003457
Chandler Carruthc8925912013-01-05 02:09:22 +00003458 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003459 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003460
3461 // If this asm operand is our Value*, and if it isn't an indirect memory
3462 // operand, we can't fold it!
3463 if (OpInfo.CallOperandVal == OpVal &&
3464 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3465 !OpInfo.isIndirect))
3466 return false;
3467 }
3468
3469 return true;
3470}
3471
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003472/// Recursively walk all the uses of I until we find a memory use.
3473/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003474/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003475static bool FindAllMemoryUses(
3476 Instruction *I,
3477 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3478 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003479 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003480 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003481 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003482
Chandler Carruthc8925912013-01-05 02:09:22 +00003483 // If this is an obviously unfoldable instruction, bail out.
3484 if (!MightBeFoldableInst(I))
3485 return true;
3486
Philip Reamesac115ed2016-03-09 23:13:12 +00003487 const bool OptSize = I->getFunction()->optForSize();
3488
Chandler Carruthc8925912013-01-05 02:09:22 +00003489 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003490 for (Use &U : I->uses()) {
3491 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003492
Chandler Carruthcdf47882014-03-09 03:16:01 +00003493 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3494 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003495 continue;
3496 }
Stephen Lin837bba12013-07-15 17:55:02 +00003497
Chandler Carruthcdf47882014-03-09 03:16:01 +00003498 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3499 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003500 if (opNo == 0) return true; // Storing addr, not into addr.
3501 MemoryUses.push_back(std::make_pair(SI, opNo));
3502 continue;
3503 }
Stephen Lin837bba12013-07-15 17:55:02 +00003504
Chandler Carruthcdf47882014-03-09 03:16:01 +00003505 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003506 // If this is a cold call, we can sink the addressing calculation into
3507 // the cold path. See optimizeCallInst
3508 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3509 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003510
Chandler Carruthc8925912013-01-05 02:09:22 +00003511 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3512 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003513
Chandler Carruthc8925912013-01-05 02:09:22 +00003514 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003515 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003516 return true;
3517 continue;
3518 }
Stephen Lin837bba12013-07-15 17:55:02 +00003519
Eric Christopher11e4df72015-02-26 22:38:43 +00003520 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003521 return true;
3522 }
3523
3524 return false;
3525}
3526
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003527/// Return true if Val is already known to be live at the use site that we're
3528/// folding it into. If so, there is no cost to include it in the addressing
3529/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3530/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003531bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003532 Value *KnownLive2) {
3533 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003534 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003535 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003536
Chandler Carruthc8925912013-01-05 02:09:22 +00003537 // All values other than instructions and arguments (e.g. constants) are live.
3538 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003539
Chandler Carruthc8925912013-01-05 02:09:22 +00003540 // If Val is a constant sized alloca in the entry block, it is live, this is
3541 // true because it is just a reference to the stack/frame pointer, which is
3542 // live for the whole function.
3543 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3544 if (AI->isStaticAlloca())
3545 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003546
Chandler Carruthc8925912013-01-05 02:09:22 +00003547 // Check to see if this value is already used in the memory instruction's
3548 // block. If so, it's already live into the block at the very least, so we
3549 // can reasonably fold it.
3550 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3551}
3552
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003553/// It is possible for the addressing mode of the machine to fold the specified
3554/// instruction into a load or store that ultimately uses it.
3555/// However, the specified instruction has multiple uses.
3556/// Given this, it may actually increase register pressure to fold it
3557/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003558///
3559/// X = ...
3560/// Y = X+1
3561/// use(Y) -> nonload/store
3562/// Z = Y+1
3563/// load Z
3564///
3565/// In this case, Y has multiple uses, and can be folded into the load of Z
3566/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3567/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3568/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3569/// number of computations either.
3570///
3571/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3572/// X was live across 'load Z' for other reasons, we actually *would* want to
3573/// fold the addressing mode in the Z case. This would make Y die earlier.
3574bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003575isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003576 ExtAddrMode &AMAfter) {
3577 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003578
Chandler Carruthc8925912013-01-05 02:09:22 +00003579 // AMBefore is the addressing mode before this instruction was folded into it,
3580 // and AMAfter is the addressing mode after the instruction was folded. Get
3581 // the set of registers referenced by AMAfter and subtract out those
3582 // referenced by AMBefore: this is the set of values which folding in this
3583 // address extends the lifetime of.
3584 //
3585 // Note that there are only two potential values being referenced here,
3586 // BaseReg and ScaleReg (global addresses are always available, as are any
3587 // folded immediates).
3588 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003589
Chandler Carruthc8925912013-01-05 02:09:22 +00003590 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3591 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003592 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003593 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003594 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003595 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003596
3597 // If folding this instruction (and it's subexprs) didn't extend any live
3598 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003599 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003600 return true;
3601
Philip Reamesac115ed2016-03-09 23:13:12 +00003602 // If all uses of this instruction can have the address mode sunk into them,
3603 // we can remove the addressing mode and effectively trade one live register
3604 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003605 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003606 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3607 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003608 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003609 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003610
Chandler Carruthc8925912013-01-05 02:09:22 +00003611 // Now that we know that all uses of this instruction are part of a chain of
3612 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003613 // into a memory use, loop over each of these memory operation uses and see
3614 // if they could *actually* fold the instruction. The assumption is that
3615 // addressing modes are cheap and that duplicating the computation involved
3616 // many times is worthwhile, even on a fastpath. For sinking candidates
3617 // (i.e. cold call sites), this serves as a way to prevent excessive code
3618 // growth since most architectures have some reasonable small and fast way to
3619 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003620 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3621 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3622 Instruction *User = MemoryUses[i].first;
3623 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003624
Chandler Carruthc8925912013-01-05 02:09:22 +00003625 // Get the access type of this use. If the use isn't a pointer, we don't
3626 // know what it accesses.
3627 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003628 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3629 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003630 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003631 Type *AddressAccessTy = AddrTy->getElementType();
3632 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003633
Chandler Carruthc8925912013-01-05 02:09:22 +00003634 // Do a match against the root of this address, ignoring profitability. This
3635 // will tell us if the addressing mode for the memory operation will
3636 // *actually* cover the shared instruction.
3637 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003638 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3639 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003640 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003641 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003642 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003643 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003644 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003645 (void)Success; assert(Success && "Couldn't select *anything*?");
3646
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003647 // The match was to check the profitability, the changes made are not
3648 // part of the original matcher. Therefore, they should be dropped
3649 // otherwise the original matcher will not present the right state.
3650 TPT.rollback(LastKnownGood);
3651
Chandler Carruthc8925912013-01-05 02:09:22 +00003652 // If the match didn't cover I, then it won't be shared by it.
3653 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3654 I) == MatchedAddrModeInsts.end())
3655 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003656
Chandler Carruthc8925912013-01-05 02:09:22 +00003657 MatchedAddrModeInsts.clear();
3658 }
Stephen Lin837bba12013-07-15 17:55:02 +00003659
Chandler Carruthc8925912013-01-05 02:09:22 +00003660 return true;
3661}
3662
3663} // end anonymous namespace
3664
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003665/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003666/// different basic block than BB.
3667static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3668 if (Instruction *I = dyn_cast<Instruction>(V))
3669 return I->getParent() != BB;
3670 return false;
3671}
3672
Philip Reamesac115ed2016-03-09 23:13:12 +00003673/// Sink addressing mode computation immediate before MemoryInst if doing so
3674/// can be done without increasing register pressure. The need for the
3675/// register pressure constraint means this can end up being an all or nothing
3676/// decision for all uses of the same addressing computation.
3677///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003678/// Load and Store Instructions often have addressing modes that can do
3679/// significant amounts of computation. As such, instruction selection will try
3680/// to get the load or store to do as much computation as possible for the
3681/// program. The problem is that isel can only see within a single block. As
3682/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003683///
3684/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003685/// operands. It's also used to sink addressing computations feeding into cold
3686/// call sites into their (cold) basic block.
3687///
3688/// The motivation for handling sinking into cold blocks is that doing so can
3689/// both enable other address mode sinking (by satisfying the register pressure
3690/// constraint above), and reduce register pressure globally (by removing the
3691/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003692bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003693 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003694 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003695
3696 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003697 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003698 SmallVector<Value*, 8> worklist;
3699 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003700 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003701
Owen Anderson8ba5f392010-11-27 08:15:55 +00003702 // Use a worklist to iteratively look through PHI nodes, and ensure that
3703 // the addressing mode obtained from the non-PHI roots of the graph
3704 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003705 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003706 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003707 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003708 SmallVector<Instruction*, 16> AddrModeInsts;
3709 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003710 TypePromotionTransaction TPT;
3711 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3712 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003713 while (!worklist.empty()) {
3714 Value *V = worklist.back();
3715 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003716
Owen Anderson8ba5f392010-11-27 08:15:55 +00003717 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003718 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003719 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003720 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003721 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003722
Owen Anderson8ba5f392010-11-27 08:15:55 +00003723 // For a PHI node, push all of its incoming values.
3724 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003725 for (Value *IncValue : P->incoming_values())
3726 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003727 continue;
3728 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003729
Philip Reamesac115ed2016-03-09 23:13:12 +00003730 // For non-PHIs, determine the addressing mode being computed. Note that
3731 // the result may differ depending on what other uses our candidate
3732 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003733 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003734 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003735 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003736 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003737
3738 // This check is broken into two cases with very similar code to avoid using
3739 // getNumUses() as much as possible. Some values have a lot of uses, so
3740 // calling getNumUses() unconditionally caused a significant compile-time
3741 // regression.
3742 if (!Consensus) {
3743 Consensus = V;
3744 AddrMode = NewAddrMode;
3745 AddrModeInsts = NewAddrModeInsts;
3746 continue;
3747 } else if (NewAddrMode == AddrMode) {
3748 if (!IsNumUsesConsensusValid) {
3749 NumUsesConsensus = Consensus->getNumUses();
3750 IsNumUsesConsensusValid = true;
3751 }
3752
3753 // Ensure that the obtained addressing mode is equivalent to that obtained
3754 // for all other roots of the PHI traversal. Also, when choosing one
3755 // such root as representative, select the one with the most uses in order
3756 // to keep the cost modeling heuristics in AddressingModeMatcher
3757 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003758 unsigned NumUses = V->getNumUses();
3759 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003760 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003761 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003762 AddrModeInsts = NewAddrModeInsts;
3763 }
3764 continue;
3765 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003766
Craig Topperc0196b12014-04-14 00:51:57 +00003767 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003768 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003769 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003770
Owen Anderson8ba5f392010-11-27 08:15:55 +00003771 // If the addressing mode couldn't be determined, or if multiple different
3772 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003773 if (!Consensus) {
3774 TPT.rollback(LastKnownGood);
3775 return false;
3776 }
3777 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003778
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003779 // Check to see if any of the instructions supersumed by this addr mode are
3780 // non-local to I's BB.
3781 bool AnyNonLocal = false;
3782 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003783 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003784 AnyNonLocal = true;
3785 break;
3786 }
3787 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003788
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003789 // If all the instructions matched are already in this BB, don't do anything.
3790 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003791 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003792 return false;
3793 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003794
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003795 // Insert this computation right after this user. Since our caller is
3796 // scanning from the top of the BB to the bottom, reuse of the expr are
3797 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003798 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003799
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003800 // Now that we determined the addressing expression we want to use and know
3801 // that we have to sink it into this block. Check to see if we have already
3802 // done this for some other load/store instr in this block. If so, reuse the
3803 // computation.
3804 Value *&SunkAddr = SunkAddrs[Addr];
3805 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003806 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003807 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003808 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003809 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003810 } else if (AddrSinkUsingGEPs ||
3811 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003812 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3813 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003814 // By default, we use the GEP-based method when AA is used later. This
3815 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3816 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003817 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003818 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003819 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003820
3821 // First, find the pointer.
3822 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3823 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003824 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003825 }
3826
3827 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3828 // We can't add more than one pointer together, nor can we scale a
3829 // pointer (both of which seem meaningless).
3830 if (ResultPtr || AddrMode.Scale != 1)
3831 return false;
3832
3833 ResultPtr = AddrMode.ScaledReg;
3834 AddrMode.Scale = 0;
3835 }
3836
3837 if (AddrMode.BaseGV) {
3838 if (ResultPtr)
3839 return false;
3840
3841 ResultPtr = AddrMode.BaseGV;
3842 }
3843
3844 // If the real base value actually came from an inttoptr, then the matcher
3845 // will look through it and provide only the integer value. In that case,
3846 // use it here.
3847 if (!ResultPtr && AddrMode.BaseReg) {
3848 ResultPtr =
3849 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003850 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003851 } else if (!ResultPtr && AddrMode.Scale == 1) {
3852 ResultPtr =
3853 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3854 AddrMode.Scale = 0;
3855 }
3856
3857 if (!ResultPtr &&
3858 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3859 SunkAddr = Constant::getNullValue(Addr->getType());
3860 } else if (!ResultPtr) {
3861 return false;
3862 } else {
3863 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003864 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3865 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003866
3867 // Start with the base register. Do this first so that subsequent address
3868 // matching finds it last, which will prevent it from trying to match it
3869 // as the scaled value in case it happens to be a mul. That would be
3870 // problematic if we've sunk a different mul for the scale, because then
3871 // we'd end up sinking both muls.
3872 if (AddrMode.BaseReg) {
3873 Value *V = AddrMode.BaseReg;
3874 if (V->getType() != IntPtrTy)
3875 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3876
3877 ResultIndex = V;
3878 }
3879
3880 // Add the scale value.
3881 if (AddrMode.Scale) {
3882 Value *V = AddrMode.ScaledReg;
3883 if (V->getType() == IntPtrTy) {
3884 // done.
3885 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3886 cast<IntegerType>(V->getType())->getBitWidth()) {
3887 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3888 } else {
3889 // It is only safe to sign extend the BaseReg if we know that the math
3890 // required to create it did not overflow before we extend it. Since
3891 // the original IR value was tossed in favor of a constant back when
3892 // the AddrMode was created we need to bail out gracefully if widths
3893 // do not match instead of extending it.
3894 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3895 if (I && (ResultIndex != AddrMode.BaseReg))
3896 I->eraseFromParent();
3897 return false;
3898 }
3899
3900 if (AddrMode.Scale != 1)
3901 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3902 "sunkaddr");
3903 if (ResultIndex)
3904 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3905 else
3906 ResultIndex = V;
3907 }
3908
3909 // Add in the Base Offset if present.
3910 if (AddrMode.BaseOffs) {
3911 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3912 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003913 // We need to add this separately from the scale above to help with
3914 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003915 if (ResultPtr->getType() != I8PtrTy)
3916 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003917 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003918 }
3919
3920 ResultIndex = V;
3921 }
3922
3923 if (!ResultIndex) {
3924 SunkAddr = ResultPtr;
3925 } else {
3926 if (ResultPtr->getType() != I8PtrTy)
3927 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003928 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003929 }
3930
3931 if (SunkAddr->getType() != Addr->getType())
3932 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3933 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003934 } else {
David Greene74e2d492010-01-05 01:27:11 +00003935 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003936 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003937 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003938 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003939
3940 // Start with the base register. Do this first so that subsequent address
3941 // matching finds it last, which will prevent it from trying to match it
3942 // as the scaled value in case it happens to be a mul. That would be
3943 // problematic if we've sunk a different mul for the scale, because then
3944 // we'd end up sinking both muls.
3945 if (AddrMode.BaseReg) {
3946 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003947 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003948 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003949 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003950 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003951 Result = V;
3952 }
3953
3954 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003955 if (AddrMode.Scale) {
3956 Value *V = AddrMode.ScaledReg;
3957 if (V->getType() == IntPtrTy) {
3958 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003959 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003960 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003961 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3962 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003963 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003964 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003965 // It is only safe to sign extend the BaseReg if we know that the math
3966 // required to create it did not overflow before we extend it. Since
3967 // the original IR value was tossed in favor of a constant back when
3968 // the AddrMode was created we need to bail out gracefully if widths
3969 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003970 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003971 if (I && (Result != AddrMode.BaseReg))
3972 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003973 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003974 }
3975 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003976 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3977 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003978 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003979 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003980 else
3981 Result = V;
3982 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003983
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003984 // Add in the BaseGV if present.
3985 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003986 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003987 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003988 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003989 else
3990 Result = V;
3991 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003992
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003993 // Add in the Base Offset if present.
3994 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003995 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003996 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003997 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003998 else
3999 Result = V;
4000 }
4001
Craig Topperc0196b12014-04-14 00:51:57 +00004002 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004003 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004004 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004005 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004006 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004007
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004008 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004009
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004010 // If we have no uses, recursively delete the value and all dead instructions
4011 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004012 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004013 // This can cause recursive deletion, which can invalidate our iterator.
4014 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004015 Value *CurValue = &*CurInstIterator;
4016 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004017 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004018
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004019 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004020
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004021 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004022 // If the iterator instruction was recursively deleted, start over at the
4023 // start of the block.
4024 CurInstIterator = BB->begin();
4025 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004026 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004027 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004028 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004029 return true;
4030}
4031
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004032/// If there are any memory operands, use OptimizeMemoryInst to sink their
4033/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004034bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004035 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004036
Eric Christopher11e4df72015-02-26 22:38:43 +00004037 const TargetRegisterInfo *TRI =
4038 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004039 TargetLowering::AsmOperandInfoVector TargetConstraints =
4040 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004041 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004042 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4043 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004044
Evan Cheng1da25002008-02-26 02:42:37 +00004045 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004046 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004047
Eli Friedman666bbe32008-02-26 18:37:49 +00004048 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4049 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004050 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004051 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004052 } else if (OpInfo.Type == InlineAsm::isInput)
4053 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004054 }
4055
4056 return MadeChange;
4057}
4058
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004059/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4060/// sign extensions.
4061static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4062 assert(!Inst->use_empty() && "Input must have at least one use");
4063 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4064 bool IsSExt = isa<SExtInst>(FirstUser);
4065 Type *ExtTy = FirstUser->getType();
4066 for (const User *U : Inst->users()) {
4067 const Instruction *UI = cast<Instruction>(U);
4068 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4069 return false;
4070 Type *CurTy = UI->getType();
4071 // Same input and output types: Same instruction after CSE.
4072 if (CurTy == ExtTy)
4073 continue;
4074
4075 // If IsSExt is true, we are in this situation:
4076 // a = Inst
4077 // b = sext ty1 a to ty2
4078 // c = sext ty1 a to ty3
4079 // Assuming ty2 is shorter than ty3, this could be turned into:
4080 // a = Inst
4081 // b = sext ty1 a to ty2
4082 // c = sext ty2 b to ty3
4083 // However, the last sext is not free.
4084 if (IsSExt)
4085 return false;
4086
4087 // This is a ZExt, maybe this is free to extend from one type to another.
4088 // In that case, we would not account for a different use.
4089 Type *NarrowTy;
4090 Type *LargeTy;
4091 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4092 CurTy->getScalarType()->getIntegerBitWidth()) {
4093 NarrowTy = CurTy;
4094 LargeTy = ExtTy;
4095 } else {
4096 NarrowTy = ExtTy;
4097 LargeTy = CurTy;
4098 }
4099
4100 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4101 return false;
4102 }
4103 // All uses are the same or can be derived from one another for free.
4104 return true;
4105}
4106
4107/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4108/// load instruction.
4109/// If an ext(load) can be formed, it is returned via \p LI for the load
4110/// and \p Inst for the extension.
4111/// Otherwise LI == nullptr and Inst == nullptr.
4112/// When some promotion happened, \p TPT contains the proper state to
4113/// revert them.
4114///
4115/// \return true when promoting was necessary to expose the ext(load)
4116/// opportunity, false otherwise.
4117///
4118/// Example:
4119/// \code
4120/// %ld = load i32* %addr
4121/// %add = add nuw i32 %ld, 4
4122/// %zext = zext i32 %add to i64
4123/// \endcode
4124/// =>
4125/// \code
4126/// %ld = load i32* %addr
4127/// %zext = zext i32 %ld to i64
4128/// %add = add nuw i64 %zext, 4
4129/// \encode
4130/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004131bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004132 LoadInst *&LI, Instruction *&Inst,
4133 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004134 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004135 // Iterate over all the extensions to see if one form an ext(load).
4136 for (auto I : Exts) {
4137 // Check if we directly have ext(load).
4138 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4139 Inst = I;
4140 // No promotion happened here.
4141 return false;
4142 }
4143 // Check whether or not we want to do any promotion.
4144 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4145 continue;
4146 // Get the action to perform the promotion.
4147 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004148 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004149 // Check if we can promote.
4150 if (!TPH)
4151 continue;
4152 // Save the current state.
4153 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4154 TPT.getRestorationPoint();
4155 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004156 unsigned NewCreatedInstsCost = 0;
4157 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004158 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004159 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4160 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004161 assert(PromotedVal &&
4162 "TypePromotionHelper should have filtered out those cases");
4163
4164 // We would be able to merge only one extension in a load.
4165 // Therefore, if we have more than 1 new extension we heuristically
4166 // cut this search path, because it means we degrade the code quality.
4167 // With exactly 2, the transformation is neutral, because we will merge
4168 // one extension but leave one. However, we optimistically keep going,
4169 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004170 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4171 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004172 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004173 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004174 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004175 // The promotion is not profitable, rollback to the previous state.
4176 TPT.rollback(LastKnownGood);
4177 continue;
4178 }
4179 // The promotion is profitable.
4180 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004181 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004182 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004183 // If we have created a new extension, i.e., now we have two
4184 // extensions. We must make sure one of them is merged with
4185 // the load, otherwise we may degrade the code quality.
4186 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4187 // Promotion happened.
4188 return true;
4189 // If this does not help to expose an ext(load) then, rollback.
4190 TPT.rollback(LastKnownGood);
4191 }
4192 // None of the extension can form an ext(load).
4193 LI = nullptr;
4194 Inst = nullptr;
4195 return false;
4196}
4197
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004198/// Move a zext or sext fed by a load into the same basic block as the load,
4199/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4200/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004201/// \p I[in/out] the extension may be modified during the process if some
4202/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004203///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004204bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004205 // Try to promote a chain of computation if it allows to form
4206 // an extended load.
4207 TypePromotionTransaction TPT;
4208 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4209 TPT.getRestorationPoint();
4210 SmallVector<Instruction *, 1> Exts;
4211 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004212 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004213 LoadInst *LI = nullptr;
4214 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004215 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004216 if (!LI || !I) {
4217 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4218 "the code must remain the same");
4219 I = OldExt;
4220 return false;
4221 }
Dan Gohman99429a02009-10-16 20:59:35 +00004222
4223 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004224 // Make the cheap checks first if we did not promote.
4225 // If we promoted, we need to check if it is indeed profitable.
4226 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004227 return false;
4228
Mehdi Amini44ede332015-07-09 02:09:04 +00004229 EVT VT = TLI->getValueType(*DL, I->getType());
4230 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004231
Dan Gohman99429a02009-10-16 20:59:35 +00004232 // If the load has other users and the truncate is not free, this probably
4233 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004234 if (!LI->hasOneUse() && TLI &&
4235 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004236 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4237 I = OldExt;
4238 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004239 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004240 }
Dan Gohman99429a02009-10-16 20:59:35 +00004241
4242 // Check whether the target supports casts folded into loads.
4243 unsigned LType;
4244 if (isa<ZExtInst>(I))
4245 LType = ISD::ZEXTLOAD;
4246 else {
4247 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4248 LType = ISD::SEXTLOAD;
4249 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004250 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004251 I = OldExt;
4252 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004253 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004254 }
Dan Gohman99429a02009-10-16 20:59:35 +00004255
4256 // Move the extend into the same block as the load, so that SelectionDAG
4257 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004258 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004259 I->removeFromParent();
4260 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004261 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004262 return true;
4263}
4264
Sanjay Patelfc580a62015-09-21 23:03:16 +00004265bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004266 BasicBlock *DefBB = I->getParent();
4267
Bob Wilsonff714f92010-09-21 21:44:14 +00004268 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004269 // other uses of the source with result of extension.
4270 Value *Src = I->getOperand(0);
4271 if (Src->hasOneUse())
4272 return false;
4273
Evan Cheng2011df42007-12-13 07:50:36 +00004274 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004275 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004276 return false;
4277
Evan Cheng7bc89422007-12-12 00:51:06 +00004278 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004279 // this block.
4280 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004281 return false;
4282
Evan Chengd3d80172007-12-05 23:58:20 +00004283 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004284 for (User *U : I->users()) {
4285 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004286
4287 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004288 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004289 if (UserBB == DefBB) continue;
4290 DefIsLiveOut = true;
4291 break;
4292 }
4293 if (!DefIsLiveOut)
4294 return false;
4295
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004296 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004297 for (User *U : Src->users()) {
4298 Instruction *UI = cast<Instruction>(U);
4299 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004300 if (UserBB == DefBB) continue;
4301 // Be conservative. We don't want this xform to end up introducing
4302 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004303 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004304 return false;
4305 }
4306
Evan Chengd3d80172007-12-05 23:58:20 +00004307 // InsertedTruncs - Only insert one trunc in each block once.
4308 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4309
4310 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004311 for (Use &U : Src->uses()) {
4312 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004313
4314 // Figure out which BB this ext is used in.
4315 BasicBlock *UserBB = User->getParent();
4316 if (UserBB == DefBB) continue;
4317
4318 // Both src and def are live in this block. Rewrite the use.
4319 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4320
4321 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004322 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004323 assert(InsertPt != UserBB->end());
4324 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004325 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004326 }
4327
4328 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004329 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004330 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004331 MadeChange = true;
4332 }
4333
4334 return MadeChange;
4335}
4336
Geoff Berry5256fca2015-11-20 22:34:39 +00004337// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4338// just after the load if the target can fold this into one extload instruction,
4339// with the hope of eliminating some of the other later "and" instructions using
4340// the loaded value. "and"s that are made trivially redundant by the insertion
4341// of the new "and" are removed by this function, while others (e.g. those whose
4342// path from the load goes through a phi) are left for isel to potentially
4343// remove.
4344//
4345// For example:
4346//
4347// b0:
4348// x = load i32
4349// ...
4350// b1:
4351// y = and x, 0xff
4352// z = use y
4353//
4354// becomes:
4355//
4356// b0:
4357// x = load i32
4358// x' = and x, 0xff
4359// ...
4360// b1:
4361// z = use x'
4362//
4363// whereas:
4364//
4365// b0:
4366// x1 = load i32
4367// ...
4368// b1:
4369// x2 = load i32
4370// ...
4371// b2:
4372// x = phi x1, x2
4373// y = and x, 0xff
4374//
4375// becomes (after a call to optimizeLoadExt for each load):
4376//
4377// b0:
4378// x1 = load i32
4379// x1' = and x1, 0xff
4380// ...
4381// b1:
4382// x2 = load i32
4383// x2' = and x2, 0xff
4384// ...
4385// b2:
4386// x = phi x1', x2'
4387// y = and x, 0xff
4388//
4389
4390bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4391
4392 if (!Load->isSimple() ||
4393 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4394 return false;
4395
4396 // Skip loads we've already transformed or have no reason to transform.
4397 if (Load->hasOneUse()) {
4398 User *LoadUser = *Load->user_begin();
4399 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4400 !dyn_cast<PHINode>(LoadUser))
4401 return false;
4402 }
4403
4404 // Look at all uses of Load, looking through phis, to determine how many bits
4405 // of the loaded value are needed.
4406 SmallVector<Instruction *, 8> WorkList;
4407 SmallPtrSet<Instruction *, 16> Visited;
4408 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4409 for (auto *U : Load->users())
4410 WorkList.push_back(cast<Instruction>(U));
4411
4412 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4413 unsigned BitWidth = LoadResultVT.getSizeInBits();
4414 APInt DemandBits(BitWidth, 0);
4415 APInt WidestAndBits(BitWidth, 0);
4416
4417 while (!WorkList.empty()) {
4418 Instruction *I = WorkList.back();
4419 WorkList.pop_back();
4420
4421 // Break use-def graph loops.
4422 if (!Visited.insert(I).second)
4423 continue;
4424
4425 // For a PHI node, push all of its users.
4426 if (auto *Phi = dyn_cast<PHINode>(I)) {
4427 for (auto *U : Phi->users())
4428 WorkList.push_back(cast<Instruction>(U));
4429 continue;
4430 }
4431
4432 switch (I->getOpcode()) {
4433 case llvm::Instruction::And: {
4434 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4435 if (!AndC)
4436 return false;
4437 APInt AndBits = AndC->getValue();
4438 DemandBits |= AndBits;
4439 // Keep track of the widest and mask we see.
4440 if (AndBits.ugt(WidestAndBits))
4441 WidestAndBits = AndBits;
4442 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4443 AndsToMaybeRemove.push_back(I);
4444 break;
4445 }
4446
4447 case llvm::Instruction::Shl: {
4448 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4449 if (!ShlC)
4450 return false;
4451 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4452 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4453 DemandBits |= ShlDemandBits;
4454 break;
4455 }
4456
4457 case llvm::Instruction::Trunc: {
4458 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4459 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4460 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4461 DemandBits |= TruncBits;
4462 break;
4463 }
4464
4465 default:
4466 return false;
4467 }
4468 }
4469
4470 uint32_t ActiveBits = DemandBits.getActiveBits();
4471 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4472 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4473 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4474 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4475 // followed by an AND.
4476 // TODO: Look into removing this restriction by fixing backends to either
4477 // return false for isLoadExtLegal for i1 or have them select this pattern to
4478 // a single instruction.
4479 //
4480 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4481 // mask, since these are the only ands that will be removed by isel.
4482 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4483 WidestAndBits != DemandBits)
4484 return false;
4485
4486 LLVMContext &Ctx = Load->getType()->getContext();
4487 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4488 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4489
4490 // Reject cases that won't be matched as extloads.
4491 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4492 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4493 return false;
4494
4495 IRBuilder<> Builder(Load->getNextNode());
4496 auto *NewAnd = dyn_cast<Instruction>(
4497 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4498
4499 // Replace all uses of load with new and (except for the use of load in the
4500 // new and itself).
4501 Load->replaceAllUsesWith(NewAnd);
4502 NewAnd->setOperand(0, Load);
4503
4504 // Remove any and instructions that are now redundant.
4505 for (auto *And : AndsToMaybeRemove)
4506 // Check that the and mask is the same as the one we decided to put on the
4507 // new and.
4508 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4509 And->replaceAllUsesWith(NewAnd);
4510 if (&*CurInstIterator == And)
4511 CurInstIterator = std::next(And->getIterator());
4512 And->eraseFromParent();
4513 ++NumAndUses;
4514 }
4515
4516 ++NumAndsAdded;
4517 return true;
4518}
4519
Sanjay Patel69a50a12015-10-19 21:59:12 +00004520/// Check if V (an operand of a select instruction) is an expensive instruction
4521/// that is only used once.
4522static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4523 auto *I = dyn_cast<Instruction>(V);
4524 // If it's safe to speculatively execute, then it should not have side
4525 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004526 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4527 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004528}
4529
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004530/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004531static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4532 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004533 // FIXME: This should use the same heuristics as IfConversion to determine
4534 // whether a select is better represented as a branch. This requires that
4535 // branch probability metadata is preserved for the select, which is not the
4536 // case currently.
4537
4538 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4539
Sanjay Patel4e652762015-09-28 22:14:51 +00004540 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4541 // comparison condition. If the compare has more than one use, there's
4542 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004543 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004544 return false;
4545
Sanjay Patel69a50a12015-10-19 21:59:12 +00004546 // If either operand of the select is expensive and only needed on one side
4547 // of the select, we should form a branch.
4548 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4549 sinkSelectOperand(TTI, SI->getFalseValue()))
4550 return true;
4551
4552 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004553}
4554
4555
Nadav Rotem9d832022012-09-02 12:10:19 +00004556/// If we have a SelectInst that will likely profit from branch prediction,
4557/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004558bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00004559 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4560
4561 // Can we convert the 'select' to CF ?
4562 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004563 return false;
4564
Nadav Rotem9d832022012-09-02 12:10:19 +00004565 TargetLowering::SelectSupportKind SelectKind;
4566 if (VectorCond)
4567 SelectKind = TargetLowering::VectorMaskSelect;
4568 else if (SI->getType()->isVectorTy())
4569 SelectKind = TargetLowering::ScalarCondVectorVal;
4570 else
4571 SelectKind = TargetLowering::ScalarValSelect;
4572
4573 // Do we have efficient codegen support for this kind of 'selects' ?
4574 if (TLI->isSelectSupported(SelectKind)) {
4575 // We have efficient codegen support for the select instruction.
4576 // Check if it is profitable to keep this 'select'.
4577 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00004578 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00004579 return false;
4580 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004581
4582 ModifiedDT = true;
4583
Sanjay Patel69a50a12015-10-19 21:59:12 +00004584 // Transform a sequence like this:
4585 // start:
4586 // %cmp = cmp uge i32 %a, %b
4587 // %sel = select i1 %cmp, i32 %c, i32 %d
4588 //
4589 // Into:
4590 // start:
4591 // %cmp = cmp uge i32 %a, %b
4592 // br i1 %cmp, label %select.true, label %select.false
4593 // select.true:
4594 // br label %select.end
4595 // select.false:
4596 // br label %select.end
4597 // select.end:
4598 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4599 //
4600 // In addition, we may sink instructions that produce %c or %d from
4601 // the entry block into the destination(s) of the new branch.
4602 // If the true or false blocks do not contain a sunken instruction, that
4603 // block and its branch may be optimized away. In that case, one side of the
4604 // first branch will point directly to select.end, and the corresponding PHI
4605 // predecessor block will be the start block.
4606
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004607 // First, we split the block containing the select into 2 blocks.
4608 BasicBlock *StartBlock = SI->getParent();
4609 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004610 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004611
Sanjay Patel69a50a12015-10-19 21:59:12 +00004612 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004613 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004614
4615 // These are the new basic blocks for the conditional branch.
4616 // At least one will become an actual new basic block.
4617 BasicBlock *TrueBlock = nullptr;
4618 BasicBlock *FalseBlock = nullptr;
4619
4620 // Sink expensive instructions into the conditional blocks to avoid executing
4621 // them speculatively.
4622 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4623 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4624 EndBlock->getParent(), EndBlock);
4625 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4626 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4627 TrueInst->moveBefore(TrueBranch);
4628 }
4629 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4630 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4631 EndBlock->getParent(), EndBlock);
4632 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4633 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4634 FalseInst->moveBefore(FalseBranch);
4635 }
4636
4637 // If there was nothing to sink, then arbitrarily choose the 'false' side
4638 // for a new input value to the PHI.
4639 if (TrueBlock == FalseBlock) {
4640 assert(TrueBlock == nullptr &&
4641 "Unexpected basic block transform while optimizing select");
4642
4643 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4644 EndBlock->getParent(), EndBlock);
4645 BranchInst::Create(EndBlock, FalseBlock);
4646 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004647
4648 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004649 // If we did not create a new block for one of the 'true' or 'false' paths
4650 // of the condition, it means that side of the branch goes to the end block
4651 // directly and the path originates from the start block from the point of
4652 // view of the new PHI.
4653 if (TrueBlock == nullptr) {
4654 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4655 TrueBlock = StartBlock;
4656 } else if (FalseBlock == nullptr) {
4657 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4658 FalseBlock = StartBlock;
4659 } else {
4660 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4661 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004662
4663 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004664 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004665 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004666 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4667 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4668
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004669 SI->replaceAllUsesWith(PN);
4670 SI->eraseFromParent();
4671
4672 // Instruct OptimizeBlock to skip to the next block.
4673 CurInstIterator = StartBlock->end();
4674 ++NumSelectsExpanded;
4675 return true;
4676}
4677
Benjamin Kramer573ff362014-03-01 17:24:40 +00004678static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004679 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4680 int SplatElem = -1;
4681 for (unsigned i = 0; i < Mask.size(); ++i) {
4682 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4683 return false;
4684 SplatElem = Mask[i];
4685 }
4686
4687 return true;
4688}
4689
4690/// Some targets have expensive vector shifts if the lanes aren't all the same
4691/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4692/// it's often worth sinking a shufflevector splat down to its use so that
4693/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004694bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004695 BasicBlock *DefBB = SVI->getParent();
4696
4697 // Only do this xform if variable vector shifts are particularly expensive.
4698 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4699 return false;
4700
4701 // We only expect better codegen by sinking a shuffle if we can recognise a
4702 // constant splat.
4703 if (!isBroadcastShuffle(SVI))
4704 return false;
4705
4706 // InsertedShuffles - Only insert a shuffle in each block once.
4707 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4708
4709 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004710 for (User *U : SVI->users()) {
4711 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004712
4713 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004714 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004715 if (UserBB == DefBB) continue;
4716
4717 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004718 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004719
4720 // Everything checks out, sink the shuffle if the user's block doesn't
4721 // already have a copy.
4722 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4723
4724 if (!InsertedShuffle) {
4725 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004726 assert(InsertPt != UserBB->end());
4727 InsertedShuffle =
4728 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4729 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004730 }
4731
Chandler Carruthcdf47882014-03-09 03:16:01 +00004732 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004733 MadeChange = true;
4734 }
4735
4736 // If we removed all uses, nuke the shuffle.
4737 if (SVI->use_empty()) {
4738 SVI->eraseFromParent();
4739 MadeChange = true;
4740 }
4741
4742 return MadeChange;
4743}
4744
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004745bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4746 if (!TLI || !DL)
4747 return false;
4748
4749 Value *Cond = SI->getCondition();
4750 Type *OldType = Cond->getType();
4751 LLVMContext &Context = Cond->getContext();
4752 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4753 unsigned RegWidth = RegType.getSizeInBits();
4754
4755 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4756 return false;
4757
4758 // If the register width is greater than the type width, expand the condition
4759 // of the switch instruction and each case constant to the width of the
4760 // register. By widening the type of the switch condition, subsequent
4761 // comparisons (for case comparisons) will not need to be extended to the
4762 // preferred register width, so we will potentially eliminate N-1 extends,
4763 // where N is the number of cases in the switch.
4764 auto *NewType = Type::getIntNTy(Context, RegWidth);
4765
4766 // Zero-extend the switch condition and case constants unless the switch
4767 // condition is a function argument that is already being sign-extended.
4768 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4769 // everything instead.
4770 Instruction::CastOps ExtType = Instruction::ZExt;
4771 if (auto *Arg = dyn_cast<Argument>(Cond))
4772 if (Arg->hasSExtAttr())
4773 ExtType = Instruction::SExt;
4774
4775 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4776 ExtInst->insertBefore(SI);
4777 SI->setCondition(ExtInst);
4778 for (SwitchInst::CaseIt Case : SI->cases()) {
4779 APInt NarrowConst = Case.getCaseValue()->getValue();
4780 APInt WideConst = (ExtType == Instruction::ZExt) ?
4781 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4782 Case.setValue(ConstantInt::get(Context, WideConst));
4783 }
4784
4785 return true;
4786}
4787
Quentin Colombetc32615d2014-10-31 17:52:53 +00004788namespace {
4789/// \brief Helper class to promote a scalar operation to a vector one.
4790/// This class is used to move downward extractelement transition.
4791/// E.g.,
4792/// a = vector_op <2 x i32>
4793/// b = extractelement <2 x i32> a, i32 0
4794/// c = scalar_op b
4795/// store c
4796///
4797/// =>
4798/// a = vector_op <2 x i32>
4799/// c = vector_op a (equivalent to scalar_op on the related lane)
4800/// * d = extractelement <2 x i32> c, i32 0
4801/// * store d
4802/// Assuming both extractelement and store can be combine, we get rid of the
4803/// transition.
4804class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004805 /// DataLayout associated with the current module.
4806 const DataLayout &DL;
4807
Quentin Colombetc32615d2014-10-31 17:52:53 +00004808 /// Used to perform some checks on the legality of vector operations.
4809 const TargetLowering &TLI;
4810
4811 /// Used to estimated the cost of the promoted chain.
4812 const TargetTransformInfo &TTI;
4813
4814 /// The transition being moved downwards.
4815 Instruction *Transition;
4816 /// The sequence of instructions to be promoted.
4817 SmallVector<Instruction *, 4> InstsToBePromoted;
4818 /// Cost of combining a store and an extract.
4819 unsigned StoreExtractCombineCost;
4820 /// Instruction that will be combined with the transition.
4821 Instruction *CombineInst;
4822
4823 /// \brief The instruction that represents the current end of the transition.
4824 /// Since we are faking the promotion until we reach the end of the chain
4825 /// of computation, we need a way to get the current end of the transition.
4826 Instruction *getEndOfTransition() const {
4827 if (InstsToBePromoted.empty())
4828 return Transition;
4829 return InstsToBePromoted.back();
4830 }
4831
4832 /// \brief Return the index of the original value in the transition.
4833 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4834 /// c, is at index 0.
4835 unsigned getTransitionOriginalValueIdx() const {
4836 assert(isa<ExtractElementInst>(Transition) &&
4837 "Other kind of transitions are not supported yet");
4838 return 0;
4839 }
4840
4841 /// \brief Return the index of the index in the transition.
4842 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4843 /// is at index 1.
4844 unsigned getTransitionIdx() const {
4845 assert(isa<ExtractElementInst>(Transition) &&
4846 "Other kind of transitions are not supported yet");
4847 return 1;
4848 }
4849
4850 /// \brief Get the type of the transition.
4851 /// This is the type of the original value.
4852 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4853 /// transition is <2 x i32>.
4854 Type *getTransitionType() const {
4855 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4856 }
4857
4858 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4859 /// I.e., we have the following sequence:
4860 /// Def = Transition <ty1> a to <ty2>
4861 /// b = ToBePromoted <ty2> Def, ...
4862 /// =>
4863 /// b = ToBePromoted <ty1> a, ...
4864 /// Def = Transition <ty1> ToBePromoted to <ty2>
4865 void promoteImpl(Instruction *ToBePromoted);
4866
4867 /// \brief Check whether or not it is profitable to promote all the
4868 /// instructions enqueued to be promoted.
4869 bool isProfitableToPromote() {
4870 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4871 unsigned Index = isa<ConstantInt>(ValIdx)
4872 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4873 : -1;
4874 Type *PromotedType = getTransitionType();
4875
4876 StoreInst *ST = cast<StoreInst>(CombineInst);
4877 unsigned AS = ST->getPointerAddressSpace();
4878 unsigned Align = ST->getAlignment();
4879 // Check if this store is supported.
4880 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004881 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4882 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004883 // If this is not supported, there is no way we can combine
4884 // the extract with the store.
4885 return false;
4886 }
4887
4888 // The scalar chain of computation has to pay for the transition
4889 // scalar to vector.
4890 // The vector chain has to account for the combining cost.
4891 uint64_t ScalarCost =
4892 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4893 uint64_t VectorCost = StoreExtractCombineCost;
4894 for (const auto &Inst : InstsToBePromoted) {
4895 // Compute the cost.
4896 // By construction, all instructions being promoted are arithmetic ones.
4897 // Moreover, one argument is a constant that can be viewed as a splat
4898 // constant.
4899 Value *Arg0 = Inst->getOperand(0);
4900 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4901 isa<ConstantFP>(Arg0);
4902 TargetTransformInfo::OperandValueKind Arg0OVK =
4903 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4904 : TargetTransformInfo::OK_AnyValue;
4905 TargetTransformInfo::OperandValueKind Arg1OVK =
4906 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4907 : TargetTransformInfo::OK_AnyValue;
4908 ScalarCost += TTI.getArithmeticInstrCost(
4909 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4910 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4911 Arg0OVK, Arg1OVK);
4912 }
4913 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4914 << ScalarCost << "\nVector: " << VectorCost << '\n');
4915 return ScalarCost > VectorCost;
4916 }
4917
4918 /// \brief Generate a constant vector with \p Val with the same
4919 /// number of elements as the transition.
4920 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004921 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004922 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4923 /// otherwise we generate a vector with as many undef as possible:
4924 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4925 /// used at the index of the extract.
4926 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4927 unsigned ExtractIdx = UINT_MAX;
4928 if (!UseSplat) {
4929 // If we cannot determine where the constant must be, we have to
4930 // use a splat constant.
4931 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4932 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4933 ExtractIdx = CstVal->getSExtValue();
4934 else
4935 UseSplat = true;
4936 }
4937
4938 unsigned End = getTransitionType()->getVectorNumElements();
4939 if (UseSplat)
4940 return ConstantVector::getSplat(End, Val);
4941
4942 SmallVector<Constant *, 4> ConstVec;
4943 UndefValue *UndefVal = UndefValue::get(Val->getType());
4944 for (unsigned Idx = 0; Idx != End; ++Idx) {
4945 if (Idx == ExtractIdx)
4946 ConstVec.push_back(Val);
4947 else
4948 ConstVec.push_back(UndefVal);
4949 }
4950 return ConstantVector::get(ConstVec);
4951 }
4952
4953 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4954 /// in \p Use can trigger undefined behavior.
4955 static bool canCauseUndefinedBehavior(const Instruction *Use,
4956 unsigned OperandIdx) {
4957 // This is not safe to introduce undef when the operand is on
4958 // the right hand side of a division-like instruction.
4959 if (OperandIdx != 1)
4960 return false;
4961 switch (Use->getOpcode()) {
4962 default:
4963 return false;
4964 case Instruction::SDiv:
4965 case Instruction::UDiv:
4966 case Instruction::SRem:
4967 case Instruction::URem:
4968 return true;
4969 case Instruction::FDiv:
4970 case Instruction::FRem:
4971 return !Use->hasNoNaNs();
4972 }
4973 llvm_unreachable(nullptr);
4974 }
4975
4976public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004977 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4978 const TargetTransformInfo &TTI, Instruction *Transition,
4979 unsigned CombineCost)
4980 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004981 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4982 assert(Transition && "Do not know how to promote null");
4983 }
4984
4985 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4986 bool canPromote(const Instruction *ToBePromoted) const {
4987 // We could support CastInst too.
4988 return isa<BinaryOperator>(ToBePromoted);
4989 }
4990
4991 /// \brief Check if it is profitable to promote \p ToBePromoted
4992 /// by moving downward the transition through.
4993 bool shouldPromote(const Instruction *ToBePromoted) const {
4994 // Promote only if all the operands can be statically expanded.
4995 // Indeed, we do not want to introduce any new kind of transitions.
4996 for (const Use &U : ToBePromoted->operands()) {
4997 const Value *Val = U.get();
4998 if (Val == getEndOfTransition()) {
4999 // If the use is a division and the transition is on the rhs,
5000 // we cannot promote the operation, otherwise we may create a
5001 // division by zero.
5002 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5003 return false;
5004 continue;
5005 }
5006 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5007 !isa<ConstantFP>(Val))
5008 return false;
5009 }
5010 // Check that the resulting operation is legal.
5011 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5012 if (!ISDOpcode)
5013 return false;
5014 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005015 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005016 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005017 }
5018
5019 /// \brief Check whether or not \p Use can be combined
5020 /// with the transition.
5021 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5022 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5023
5024 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5025 void enqueueForPromotion(Instruction *ToBePromoted) {
5026 InstsToBePromoted.push_back(ToBePromoted);
5027 }
5028
5029 /// \brief Set the instruction that will be combined with the transition.
5030 void recordCombineInstruction(Instruction *ToBeCombined) {
5031 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5032 CombineInst = ToBeCombined;
5033 }
5034
5035 /// \brief Promote all the instructions enqueued for promotion if it is
5036 /// is profitable.
5037 /// \return True if the promotion happened, false otherwise.
5038 bool promote() {
5039 // Check if there is something to promote.
5040 // Right now, if we do not have anything to combine with,
5041 // we assume the promotion is not profitable.
5042 if (InstsToBePromoted.empty() || !CombineInst)
5043 return false;
5044
5045 // Check cost.
5046 if (!StressStoreExtract && !isProfitableToPromote())
5047 return false;
5048
5049 // Promote.
5050 for (auto &ToBePromoted : InstsToBePromoted)
5051 promoteImpl(ToBePromoted);
5052 InstsToBePromoted.clear();
5053 return true;
5054 }
5055};
5056} // End of anonymous namespace.
5057
5058void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5059 // At this point, we know that all the operands of ToBePromoted but Def
5060 // can be statically promoted.
5061 // For Def, we need to use its parameter in ToBePromoted:
5062 // b = ToBePromoted ty1 a
5063 // Def = Transition ty1 b to ty2
5064 // Move the transition down.
5065 // 1. Replace all uses of the promoted operation by the transition.
5066 // = ... b => = ... Def.
5067 assert(ToBePromoted->getType() == Transition->getType() &&
5068 "The type of the result of the transition does not match "
5069 "the final type");
5070 ToBePromoted->replaceAllUsesWith(Transition);
5071 // 2. Update the type of the uses.
5072 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5073 Type *TransitionTy = getTransitionType();
5074 ToBePromoted->mutateType(TransitionTy);
5075 // 3. Update all the operands of the promoted operation with promoted
5076 // operands.
5077 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5078 for (Use &U : ToBePromoted->operands()) {
5079 Value *Val = U.get();
5080 Value *NewVal = nullptr;
5081 if (Val == Transition)
5082 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5083 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5084 isa<ConstantFP>(Val)) {
5085 // Use a splat constant if it is not safe to use undef.
5086 NewVal = getConstantVector(
5087 cast<Constant>(Val),
5088 isa<UndefValue>(Val) ||
5089 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5090 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005091 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5092 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005093 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5094 }
5095 Transition->removeFromParent();
5096 Transition->insertAfter(ToBePromoted);
5097 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5098}
5099
5100/// Some targets can do store(extractelement) with one instruction.
5101/// Try to push the extractelement towards the stores when the target
5102/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005103bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005104 unsigned CombineCost = UINT_MAX;
5105 if (DisableStoreExtract || !TLI ||
5106 (!StressStoreExtract &&
5107 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5108 Inst->getOperand(1), CombineCost)))
5109 return false;
5110
5111 // At this point we know that Inst is a vector to scalar transition.
5112 // Try to move it down the def-use chain, until:
5113 // - We can combine the transition with its single use
5114 // => we got rid of the transition.
5115 // - We escape the current basic block
5116 // => we would need to check that we are moving it at a cheaper place and
5117 // we do not do that for now.
5118 BasicBlock *Parent = Inst->getParent();
5119 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005120 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005121 // If the transition has more than one use, assume this is not going to be
5122 // beneficial.
5123 while (Inst->hasOneUse()) {
5124 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5125 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5126
5127 if (ToBePromoted->getParent() != Parent) {
5128 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5129 << ToBePromoted->getParent()->getName()
5130 << ") than the transition (" << Parent->getName() << ").\n");
5131 return false;
5132 }
5133
5134 if (VPH.canCombine(ToBePromoted)) {
5135 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5136 << "will be combined with: " << *ToBePromoted << '\n');
5137 VPH.recordCombineInstruction(ToBePromoted);
5138 bool Changed = VPH.promote();
5139 NumStoreExtractExposed += Changed;
5140 return Changed;
5141 }
5142
5143 DEBUG(dbgs() << "Try promoting.\n");
5144 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5145 return false;
5146
5147 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5148
5149 VPH.enqueueForPromotion(ToBePromoted);
5150 Inst = ToBePromoted;
5151 }
5152 return false;
5153}
5154
Sanjay Patelfc580a62015-09-21 23:03:16 +00005155bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005156 // Bail out if we inserted the instruction to prevent optimizations from
5157 // stepping on each other's toes.
5158 if (InsertedInsts.count(I))
5159 return false;
5160
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005161 if (PHINode *P = dyn_cast<PHINode>(I)) {
5162 // It is possible for very late stage optimizations (such as SimplifyCFG)
5163 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5164 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005165 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005166 P->replaceAllUsesWith(V);
5167 P->eraseFromParent();
5168 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005169 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005170 }
Chris Lattneree588de2011-01-15 07:29:01 +00005171 return false;
5172 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005173
Chris Lattneree588de2011-01-15 07:29:01 +00005174 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005175 // If the source of the cast is a constant, then this should have
5176 // already been constant folded. The only reason NOT to constant fold
5177 // it is if something (e.g. LSR) was careful to place the constant
5178 // evaluation in a block other than then one that uses it (e.g. to hoist
5179 // the address of globals out of a loop). If this is the case, we don't
5180 // want to forward-subst the cast.
5181 if (isa<Constant>(CI->getOperand(0)))
5182 return false;
5183
Mehdi Amini44ede332015-07-09 02:09:04 +00005184 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005185 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005186
Chris Lattneree588de2011-01-15 07:29:01 +00005187 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005188 /// Sink a zext or sext into its user blocks if the target type doesn't
5189 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005190 if (TLI &&
5191 TLI->getTypeAction(CI->getContext(),
5192 TLI->getValueType(*DL, CI->getType())) ==
5193 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005194 return SinkCast(CI);
5195 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005196 bool MadeChange = moveExtToFormExtLoad(I);
5197 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005198 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005199 }
Chris Lattneree588de2011-01-15 07:29:01 +00005200 return false;
5201 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005202
Chris Lattneree588de2011-01-15 07:29:01 +00005203 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005204 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005205 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005206
Chris Lattneree588de2011-01-15 07:29:01 +00005207 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005208 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005209 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005210 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005211 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005212 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5213 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005214 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005215 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005216 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005217
Chris Lattneree588de2011-01-15 07:29:01 +00005218 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005219 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005220 if (TLI) {
5221 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005222 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005223 SI->getOperand(0)->getType(), AS);
5224 }
Chris Lattneree588de2011-01-15 07:29:01 +00005225 return false;
5226 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005227
Yi Jiangd069f632014-04-21 19:34:27 +00005228 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5229
5230 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5231 BinOp->getOpcode() == Instruction::LShr)) {
5232 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5233 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005234 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005235
5236 return false;
5237 }
5238
Chris Lattneree588de2011-01-15 07:29:01 +00005239 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005240 if (GEPI->hasAllZeroIndices()) {
5241 /// The GEP operand must be a pointer, so must its result -> BitCast
5242 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5243 GEPI->getName(), GEPI);
5244 GEPI->replaceAllUsesWith(NC);
5245 GEPI->eraseFromParent();
5246 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005247 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005248 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005249 }
Chris Lattneree588de2011-01-15 07:29:01 +00005250 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005251 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005252
Chris Lattneree588de2011-01-15 07:29:01 +00005253 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005254 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005255
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005256 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005257 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005258
Tim Northoveraeb8e062014-02-19 10:02:43 +00005259 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005260 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005261
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005262 if (auto *Switch = dyn_cast<SwitchInst>(I))
5263 return optimizeSwitchInst(Switch);
5264
Quentin Colombetc32615d2014-10-31 17:52:53 +00005265 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005266 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005267
Chris Lattneree588de2011-01-15 07:29:01 +00005268 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005269}
5270
James Molloyf01488e2016-01-15 09:20:19 +00005271/// Given an OR instruction, check to see if this is a bitreverse
5272/// idiom. If so, insert the new intrinsic and return true.
5273static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5274 const TargetLowering &TLI) {
5275 if (!I.getType()->isIntegerTy() ||
5276 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5277 TLI.getValueType(DL, I.getType(), true)))
5278 return false;
5279
5280 SmallVector<Instruction*, 4> Insts;
5281 if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
5282 return false;
5283 Instruction *LastInst = Insts.back();
5284 I.replaceAllUsesWith(LastInst);
5285 RecursivelyDeleteTriviallyDeadInstructions(&I);
5286 return true;
5287}
5288
Chris Lattnerf2836d12007-03-31 04:06:36 +00005289// In this pass we look for GEP and cast instructions that are used
5290// across basic blocks and rewrite them to improve basic-block-at-a-time
5291// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005292bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005293 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005294 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005295
Chris Lattner7a277142011-01-15 07:14:54 +00005296 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005297 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005298 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005299 if (ModifiedDT)
5300 return true;
5301 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005302
James Molloyf01488e2016-01-15 09:20:19 +00005303 bool MadeBitReverse = true;
5304 while (TLI && MadeBitReverse) {
5305 MadeBitReverse = false;
5306 for (auto &I : reverse(BB)) {
5307 if (makeBitReverse(I, *DL, *TLI)) {
5308 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005309 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005310 break;
5311 }
5312 }
5313 }
James Molloy3ef84c42016-01-15 10:36:01 +00005314 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005315
Chris Lattnerf2836d12007-03-31 04:06:36 +00005316 return MadeChange;
5317}
Devang Patel53771ba2011-08-18 00:50:51 +00005318
5319// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005320// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005321// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005322bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005323 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005324 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005325 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005326 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005327 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005328 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005329 // Leave dbg.values that refer to an alloca alone. These
5330 // instrinsics describe the address of a variable (= the alloca)
5331 // being taken. They should not be moved next to the alloca
5332 // (and to the beginning of the scope), but rather stay close to
5333 // where said address is used.
5334 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005335 PrevNonDbgInst = Insn;
5336 continue;
5337 }
5338
5339 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5340 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005341 // If VI is a phi in a block with an EHPad terminator, we can't insert
5342 // after it.
5343 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5344 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005345 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5346 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005347 if (isa<PHINode>(VI))
5348 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5349 else
5350 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005351 MadeChange = true;
5352 ++NumDbgValueMoved;
5353 }
5354 }
5355 }
5356 return MadeChange;
5357}
Tim Northovercea0abb2014-03-29 08:22:29 +00005358
5359// If there is a sequence that branches based on comparing a single bit
5360// against zero that can be combined into a single instruction, and the
5361// target supports folding these into a single instruction, sink the
5362// mask and compare into the branch uses. Do this before OptimizeBlock ->
5363// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5364// searched for.
5365bool CodeGenPrepare::sinkAndCmp(Function &F) {
5366 if (!EnableAndCmpSinking)
5367 return false;
5368 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5369 return false;
5370 bool MadeChange = false;
5371 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005372 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00005373
5374 // Does this BB end with the following?
5375 // %andVal = and %val, #single-bit-set
5376 // %icmpVal = icmp %andResult, 0
5377 // br i1 %cmpVal label %dest1, label %dest2"
5378 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
5379 if (!Brcc || !Brcc->isConditional())
5380 continue;
5381 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5382 if (!Cmp || Cmp->getParent() != BB)
5383 continue;
5384 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5385 if (!Zero || !Zero->isZero())
5386 continue;
5387 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5388 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
5389 continue;
5390 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5391 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5392 continue;
5393 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
5394
5395 // Push the "and; icmp" for any users that are conditional branches.
5396 // Since there can only be one branch use per BB, we don't need to keep
5397 // track of which BBs we insert into.
5398 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
5399 UI != E; ) {
5400 Use &TheUse = *UI;
5401 // Find brcc use.
5402 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
5403 ++UI;
5404 if (!BrccUser || !BrccUser->isConditional())
5405 continue;
5406 BasicBlock *UserBB = BrccUser->getParent();
5407 if (UserBB == BB) continue;
5408 DEBUG(dbgs() << "found Brcc use\n");
5409
5410 // Sink the "and; icmp" to use.
5411 MadeChange = true;
5412 BinaryOperator *NewAnd =
5413 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5414 BrccUser);
5415 CmpInst *NewCmp =
5416 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5417 "", BrccUser);
5418 TheUse = NewCmp;
5419 ++NumAndCmpsMoved;
5420 DEBUG(BrccUser->getParent()->dump());
5421 }
5422 }
5423 return MadeChange;
5424}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005425
Juergen Ributzka194350a2014-12-09 17:32:12 +00005426/// \brief Retrieve the probabilities of a conditional branch. Returns true on
5427/// success, or returns false if no or invalid metadata was found.
5428static bool extractBranchMetadata(BranchInst *BI,
5429 uint64_t &ProbTrue, uint64_t &ProbFalse) {
5430 assert(BI->isConditional() &&
5431 "Looking for probabilities on unconditional branch?");
5432 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
5433 if (!ProfileData || ProfileData->getNumOperands() != 3)
5434 return false;
5435
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005436 const auto *CITrue =
5437 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
5438 const auto *CIFalse =
5439 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00005440 if (!CITrue || !CIFalse)
5441 return false;
5442
5443 ProbTrue = CITrue->getValue().getZExtValue();
5444 ProbFalse = CIFalse->getValue().getZExtValue();
5445
5446 return true;
5447}
5448
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005449/// \brief Scale down both weights to fit into uint32_t.
5450static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5451 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5452 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5453 NewTrue = NewTrue / Scale;
5454 NewFalse = NewFalse / Scale;
5455}
5456
5457/// \brief Some targets prefer to split a conditional branch like:
5458/// \code
5459/// %0 = icmp ne i32 %a, 0
5460/// %1 = icmp ne i32 %b, 0
5461/// %or.cond = or i1 %0, %1
5462/// br i1 %or.cond, label %TrueBB, label %FalseBB
5463/// \endcode
5464/// into multiple branch instructions like:
5465/// \code
5466/// bb1:
5467/// %0 = icmp ne i32 %a, 0
5468/// br i1 %0, label %TrueBB, label %bb2
5469/// bb2:
5470/// %1 = icmp ne i32 %b, 0
5471/// br i1 %1, label %TrueBB, label %FalseBB
5472/// \endcode
5473/// This usually allows instruction selection to do even further optimizations
5474/// and combine the compare with the branch instruction. Currently this is
5475/// applied for targets which have "cheap" jump instructions.
5476///
5477/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5478///
5479bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005480 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005481 return false;
5482
5483 bool MadeChange = false;
5484 for (auto &BB : F) {
5485 // Does this BB end with the following?
5486 // %cond1 = icmp|fcmp|binary instruction ...
5487 // %cond2 = icmp|fcmp|binary instruction ...
5488 // %cond.or = or|and i1 %cond1, cond2
5489 // br i1 %cond.or label %dest1, label %dest2"
5490 BinaryOperator *LogicOp;
5491 BasicBlock *TBB, *FBB;
5492 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5493 continue;
5494
Sanjay Patel42574202015-09-02 19:23:23 +00005495 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5496 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5497 continue;
5498
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005499 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005500 Value *Cond1, *Cond2;
5501 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5502 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005503 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005504 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5505 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005506 Opc = Instruction::Or;
5507 else
5508 continue;
5509
5510 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5511 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5512 continue;
5513
5514 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5515
5516 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005517 auto TmpBB =
5518 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5519 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005520
5521 // Update original basic block by using the first condition directly by the
5522 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005523 Br1->setCondition(Cond1);
5524 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005525
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005526 // Depending on the conditon we have to either replace the true or the false
5527 // successor of the original branch instruction.
5528 if (Opc == Instruction::And)
5529 Br1->setSuccessor(0, TmpBB);
5530 else
5531 Br1->setSuccessor(1, TmpBB);
5532
5533 // Fill in the new basic block.
5534 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005535 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5536 I->removeFromParent();
5537 I->insertBefore(Br2);
5538 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005539
5540 // Update PHI nodes in both successors. The original BB needs to be
5541 // replaced in one succesor's PHI nodes, because the branch comes now from
5542 // the newly generated BB (NewBB). In the other successor we need to add one
5543 // incoming edge to the PHI nodes, because both branch instructions target
5544 // now the same successor. Depending on the original branch condition
5545 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5546 // we perfrom the correct update for the PHI nodes.
5547 // This doesn't change the successor order of the just created branch
5548 // instruction (or any other instruction).
5549 if (Opc == Instruction::Or)
5550 std::swap(TBB, FBB);
5551
5552 // Replace the old BB with the new BB.
5553 for (auto &I : *TBB) {
5554 PHINode *PN = dyn_cast<PHINode>(&I);
5555 if (!PN)
5556 break;
5557 int i;
5558 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5559 PN->setIncomingBlock(i, TmpBB);
5560 }
5561
5562 // Add another incoming edge form the new BB.
5563 for (auto &I : *FBB) {
5564 PHINode *PN = dyn_cast<PHINode>(&I);
5565 if (!PN)
5566 break;
5567 auto *Val = PN->getIncomingValueForBlock(&BB);
5568 PN->addIncoming(Val, TmpBB);
5569 }
5570
5571 // Update the branch weights (from SelectionDAGBuilder::
5572 // FindMergedConditions).
5573 if (Opc == Instruction::Or) {
5574 // Codegen X | Y as:
5575 // BB1:
5576 // jmp_if_X TBB
5577 // jmp TmpBB
5578 // TmpBB:
5579 // jmp_if_Y TBB
5580 // jmp FBB
5581 //
5582
5583 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5584 // The requirement is that
5585 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5586 // = TrueProb for orignal BB.
5587 // Assuming the orignal weights are A and B, one choice is to set BB1's
5588 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5589 // assumes that
5590 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5591 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5592 // TmpBB, but the math is more complicated.
5593 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005594 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005595 uint64_t NewTrueWeight = TrueWeight;
5596 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5597 scaleWeights(NewTrueWeight, NewFalseWeight);
5598 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5599 .createBranchWeights(TrueWeight, FalseWeight));
5600
5601 NewTrueWeight = TrueWeight;
5602 NewFalseWeight = 2 * FalseWeight;
5603 scaleWeights(NewTrueWeight, NewFalseWeight);
5604 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5605 .createBranchWeights(TrueWeight, FalseWeight));
5606 }
5607 } else {
5608 // Codegen X & Y as:
5609 // BB1:
5610 // jmp_if_X TmpBB
5611 // jmp FBB
5612 // TmpBB:
5613 // jmp_if_Y TBB
5614 // jmp FBB
5615 //
5616 // This requires creation of TmpBB after CurBB.
5617
5618 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5619 // The requirement is that
5620 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5621 // = FalseProb for orignal BB.
5622 // Assuming the orignal weights are A and B, one choice is to set BB1's
5623 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5624 // assumes that
5625 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5626 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005627 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005628 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5629 uint64_t NewFalseWeight = FalseWeight;
5630 scaleWeights(NewTrueWeight, NewFalseWeight);
5631 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5632 .createBranchWeights(TrueWeight, FalseWeight));
5633
5634 NewTrueWeight = 2 * TrueWeight;
5635 NewFalseWeight = FalseWeight;
5636 scaleWeights(NewTrueWeight, NewFalseWeight);
5637 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5638 .createBranchWeights(TrueWeight, FalseWeight));
5639 }
5640 }
5641
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005642 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005643 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005644 ModifiedDT = true;
5645
5646 MadeChange = true;
5647
5648 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5649 TmpBB->dump());
5650 }
5651 return MadeChange;
5652}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005653
5654void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005655 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005656 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5657}