Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1 | //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass munges the code in the input function to better prepare it for |
Gordon Henriksen | 829046b | 2008-05-08 17:46:35 +0000 | [diff] [blame] | 11 | // SelectionDAG-based code generation. This works around limitations in it's |
| 12 | // basic-block-at-a-time approach. It should eventually be removed. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Quentin Colombet | a349084 | 2014-02-22 00:07:45 +0000 | [diff] [blame] | 16 | #include "llvm/CodeGen/Passes.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/DenseMap.h" |
| 18 | #include "llvm/ADT/SmallSet.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 23 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 24 | #include "llvm/IR/Constants.h" |
| 25 | #include "llvm/IR/DataLayout.h" |
| 26 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 27 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 29 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 30 | #include "llvm/IR/IRBuilder.h" |
| 31 | #include "llvm/IR/InlineAsm.h" |
| 32 | #include "llvm/IR/Instructions.h" |
| 33 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 34 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 35 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 36 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 37 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 38 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 39 | #include "llvm/Pass.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 40 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 41 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 42 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 43 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 44 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 46 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 49 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 50 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 51 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 52 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 53 | #define DEBUG_TYPE "codegenprepare" |
| 54 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 55 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 56 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 57 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 58 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 59 | "sunken Cmps"); |
| 60 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 61 | "of sunken Casts"); |
| 62 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 63 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 64 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 65 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
| 66 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 67 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 68 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 69 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 70 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 71 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 72 | static cl::opt<bool> DisableBranchOpts( |
| 73 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 74 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 75 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 76 | static cl::opt<bool> |
| 77 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 78 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 79 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 80 | static cl::opt<bool> DisableSelectToBranch( |
| 81 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 82 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 83 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 84 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 85 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 86 | cl::desc("Address sinking in CGP using GEPs.")); |
| 87 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 88 | static cl::opt<bool> EnableAndCmpSinking( |
| 89 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 90 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 91 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 92 | static cl::opt<bool> DisableStoreExtract( |
| 93 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 94 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 95 | |
| 96 | static cl::opt<bool> StressStoreExtract( |
| 97 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 98 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 99 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 100 | static cl::opt<bool> DisableExtLdPromotion( |
| 101 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 102 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 103 | "CodeGenPrepare")); |
| 104 | |
| 105 | static cl::opt<bool> StressExtLdPromotion( |
| 106 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 107 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 108 | "optimization in CodeGenPrepare")); |
| 109 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 110 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 111 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 112 | struct TypeIsSExt { |
| 113 | Type *Ty; |
| 114 | bool IsSExt; |
| 115 | TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {} |
| 116 | }; |
| 117 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 118 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 119 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 120 | class CodeGenPrepare : public FunctionPass { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 121 | /// TLI - Keep a pointer of a TargetLowering to consult for determining |
| 122 | /// transformation profitability. |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 123 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 124 | const TargetLowering *TLI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 125 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 126 | const TargetLibraryInfo *TLInfo; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 127 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 128 | /// CurInstIterator - As we scan instructions optimizing them, this is the |
| 129 | /// next instruction to optimize. Xforms that can invalidate this should |
| 130 | /// update it. |
| 131 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 132 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 133 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 134 | /// This allows us to avoid inserting duplicate code for blocks with |
| 135 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 136 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 137 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 138 | /// Keeps track of all instructions inserted for the current function. |
| 139 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 140 | /// Keeps track of the type of the related instruction before their |
| 141 | /// promotion for the current function. |
| 142 | InstrToOrigTy PromotedInsts; |
| 143 | |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 144 | /// ModifiedDT - If CFG is modified in anyway. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 145 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 146 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 147 | /// OptSize - True if optimizing for size. |
| 148 | bool OptSize; |
| 149 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 150 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 151 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 152 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 153 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 154 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 155 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 156 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 157 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 158 | const char *getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 159 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 160 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 161 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 162 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 163 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 164 | } |
| 165 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 166 | private: |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 167 | bool EliminateFallThrough(Function &F); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 168 | bool EliminateMostlyEmptyBlocks(Function &F); |
| 169 | bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 170 | void EliminateMostlyEmptyBlock(BasicBlock *BB); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 171 | bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 172 | bool OptimizeInst(Instruction *I, bool& ModifiedDT); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 173 | bool OptimizeMemoryInst(Instruction *I, Value *Addr, |
| 174 | Type *AccessTy, unsigned AS); |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 175 | bool OptimizeInlineAsmInst(CallInst *CS); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 176 | bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 177 | bool MoveExtToFormExtLoad(Instruction *&I); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 178 | bool OptimizeExtUses(Instruction *I); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 179 | bool OptimizeSelectInst(SelectInst *SI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 180 | bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 181 | bool OptimizeExtractElementInst(Instruction *Inst); |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 182 | bool DupRetToEnableTailCallOpts(BasicBlock *BB); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 183 | bool PlaceDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 184 | bool sinkAndCmp(Function &F); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 185 | bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI, |
| 186 | Instruction *&Inst, |
| 187 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 188 | unsigned CreatedInstCost); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 189 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 190 | bool simplifyOffsetableRelocate(Instruction &I); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 191 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 192 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 193 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 194 | char CodeGenPrepare::ID = 0; |
Jiangning Liu | d623c52 | 2014-06-11 07:04:37 +0000 | [diff] [blame] | 195 | INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare", |
| 196 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 197 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 198 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 199 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 200 | } |
| 201 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 202 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 203 | if (skipOptnoneFunction(F)) |
| 204 | return false; |
| 205 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 206 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 207 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 208 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 209 | PromotedInsts.clear(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 210 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 211 | ModifiedDT = false; |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 212 | if (TM) |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 213 | TLI = TM->getSubtargetImpl(F)->getTargetLowering(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 214 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 215 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Duncan P. N. Exon Smith | 70eb9c5 | 2015-02-14 01:44:41 +0000 | [diff] [blame] | 216 | OptSize = F.hasFnAttribute(Attribute::OptimizeForSize); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 217 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 218 | /// This optimization identifies DIV instructions that can be |
| 219 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 220 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 221 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 222 | TLI->getBypassSlowDivWidths(); |
Evan Cheng | 71be12b | 2012-09-14 21:25:34 +0000 | [diff] [blame] | 223 | for (Function::iterator I = F.begin(); I != F.end(); I++) |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 224 | EverMadeChange |= bypassSlowDivision(F, I, BypassWidths); |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 225 | } |
| 226 | |
| 227 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 228 | // unconditional branch. |
| 229 | EverMadeChange |= EliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 230 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 231 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 232 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 233 | // find a node corresponding to the value. |
| 234 | EverMadeChange |= PlaceDbgValues(F); |
| 235 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 236 | // If there is a mask, compare against zero, and branch that can be combined |
| 237 | // into a single target instruction, push the mask and compare into branch |
| 238 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 239 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 240 | if (!DisableBranchOpts) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 241 | EverMadeChange |= sinkAndCmp(F); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 242 | EverMadeChange |= splitBranchCondition(F); |
| 243 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 244 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 245 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 246 | while (MadeChange) { |
| 247 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 248 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 249 | BasicBlock *BB = I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 250 | bool ModifiedDTOnIteration = false; |
| 251 | MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 252 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 253 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 254 | if (ModifiedDTOnIteration) |
| 255 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 256 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 257 | EverMadeChange |= MadeChange; |
| 258 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 259 | |
| 260 | SunkAddrs.clear(); |
| 261 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 262 | if (!DisableBranchOpts) { |
| 263 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 264 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 265 | for (BasicBlock &BB : F) { |
| 266 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 267 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 268 | if (!MadeChange) continue; |
| 269 | |
| 270 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 271 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 272 | if (pred_begin(*II) == pred_end(*II)) |
| 273 | WorkList.insert(*II); |
| 274 | } |
| 275 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 276 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 277 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 278 | while (!WorkList.empty()) { |
| 279 | BasicBlock *BB = *WorkList.begin(); |
| 280 | WorkList.erase(BB); |
| 281 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 282 | |
| 283 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 284 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 285 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 286 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 287 | if (pred_begin(*II) == pred_end(*II)) |
| 288 | WorkList.insert(*II); |
| 289 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 290 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 291 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 292 | // a single edge. |
| 293 | if (EverMadeChange || MadeChange) |
| 294 | MadeChange |= EliminateFallThrough(F); |
| 295 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 296 | EverMadeChange |= MadeChange; |
| 297 | } |
| 298 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 299 | if (!DisableGCOpts) { |
| 300 | SmallVector<Instruction *, 2> Statepoints; |
| 301 | for (BasicBlock &BB : F) |
| 302 | for (Instruction &I : BB) |
| 303 | if (isStatepoint(I)) |
| 304 | Statepoints.push_back(&I); |
| 305 | for (auto &I : Statepoints) |
| 306 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 307 | } |
| 308 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 309 | return EverMadeChange; |
| 310 | } |
| 311 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 312 | /// EliminateFallThrough - Merge basic blocks which are connected |
| 313 | /// by a single edge, where one of the basic blocks has a single successor |
| 314 | /// pointing to the other basic block, which has a single predecessor. |
| 315 | bool CodeGenPrepare::EliminateFallThrough(Function &F) { |
| 316 | bool Changed = false; |
| 317 | // Scan all of the blocks in the function, except for the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 318 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 319 | BasicBlock *BB = I++; |
| 320 | // If the destination block has a single pred, then this is a trivial |
| 321 | // edge, just collapse it. |
| 322 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 323 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 324 | // Don't merge if BB's address is taken. |
| 325 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 326 | |
| 327 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 328 | if (Term && !Term->isConditional()) { |
| 329 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 330 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 331 | // Remember if SinglePred was the entry block of the function. |
| 332 | // If so, we will need to move BB back to the entry position. |
| 333 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 334 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 335 | |
| 336 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 337 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 338 | |
| 339 | // We have erased a block. Update the iterator. |
| 340 | I = BB; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 341 | } |
| 342 | } |
| 343 | return Changed; |
| 344 | } |
| 345 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 346 | /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes, |
| 347 | /// debug info directives, and an unconditional branch. Passes before isel |
| 348 | /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for |
| 349 | /// isel. Start by eliminating these blocks so we can split them the way we |
| 350 | /// want them. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 351 | bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) { |
| 352 | bool MadeChange = false; |
| 353 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 354 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 355 | BasicBlock *BB = I++; |
| 356 | |
| 357 | // If this block doesn't end with an uncond branch, ignore it. |
| 358 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 359 | if (!BI || !BI->isUnconditional()) |
| 360 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 361 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 362 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 363 | // node, then other stuff is happening here. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 364 | BasicBlock::iterator BBI = BI; |
| 365 | if (BBI != BB->begin()) { |
| 366 | --BBI; |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 367 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 368 | if (BBI == BB->begin()) |
| 369 | break; |
| 370 | --BBI; |
| 371 | } |
| 372 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 373 | continue; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 374 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 375 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 376 | // Do not break infinite loops. |
| 377 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 378 | if (DestBB == BB) |
| 379 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 380 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 381 | if (!CanMergeBlocks(BB, DestBB)) |
| 382 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 383 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 384 | EliminateMostlyEmptyBlock(BB); |
| 385 | MadeChange = true; |
| 386 | } |
| 387 | return MadeChange; |
| 388 | } |
| 389 | |
| 390 | /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a |
| 391 | /// single uncond branch between them, and BB contains no other non-phi |
| 392 | /// instructions. |
| 393 | bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB, |
| 394 | const BasicBlock *DestBB) const { |
| 395 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 396 | // the successor. If there are more complex condition (e.g. preheaders), |
| 397 | // don't mess around with them. |
| 398 | BasicBlock::const_iterator BBI = BB->begin(); |
| 399 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 400 | for (const User *U : PN->users()) { |
| 401 | const Instruction *UI = cast<Instruction>(U); |
| 402 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 403 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 404 | // If User is inside DestBB block and it is a PHINode then check |
| 405 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 406 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 407 | if (UI->getParent() == DestBB) { |
| 408 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 409 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 410 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 411 | if (Insn && Insn->getParent() == BB && |
| 412 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 413 | return false; |
| 414 | } |
| 415 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 416 | } |
| 417 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 418 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 419 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 420 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 421 | // can't merge the block. |
| 422 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 423 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 424 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 425 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 426 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 427 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 428 | // It is faster to get preds from a PHI than with pred_iterator. |
| 429 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 430 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 431 | } else { |
| 432 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 433 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 434 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 435 | // Walk the preds of DestBB. |
| 436 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 437 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 438 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 439 | BBI = DestBB->begin(); |
| 440 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 441 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 442 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 443 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 444 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 445 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 446 | if (V2PN->getParent() == BB) |
| 447 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 448 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 449 | // If there is a conflict, bail out. |
| 450 | if (V1 != V2) return false; |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | return true; |
| 456 | } |
| 457 | |
| 458 | |
| 459 | /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and |
| 460 | /// an unconditional branch in it. |
| 461 | void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) { |
| 462 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 463 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 464 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 465 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 466 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 467 | // If the destination block has a single pred, then this is a trivial edge, |
| 468 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 469 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 470 | if (SinglePred != DestBB) { |
| 471 | // Remember if SinglePred was the entry block of the function. If so, we |
| 472 | // will need to move BB back to the entry position. |
| 473 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 474 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 475 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 476 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 477 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 478 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 479 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 480 | return; |
| 481 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 482 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 483 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 484 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 485 | // to handle the new incoming edges it is about to have. |
| 486 | PHINode *PN; |
| 487 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 488 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 489 | // Remove the incoming value for BB, and remember it. |
| 490 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 491 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 492 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 493 | // value that dominates BB. |
| 494 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 495 | if (InValPhi && InValPhi->getParent() == BB) { |
| 496 | // Add all of the input values of the input PHI as inputs of this phi. |
| 497 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 498 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 499 | InValPhi->getIncomingBlock(i)); |
| 500 | } else { |
| 501 | // Otherwise, add one instance of the dominating value for each edge that |
| 502 | // we will be adding. |
| 503 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 504 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 505 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 506 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 507 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 508 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 509 | } |
| 510 | } |
| 511 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 512 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 513 | // The PHIs are now updated, change everything that refers to BB to use |
| 514 | // DestBB and remove BB. |
| 515 | BB->replaceAllUsesWith(DestBB); |
| 516 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 517 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 518 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 519 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 520 | } |
| 521 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 522 | // Computes a map of base pointer relocation instructions to corresponding |
| 523 | // derived pointer relocation instructions given a vector of all relocate calls |
| 524 | static void computeBaseDerivedRelocateMap( |
| 525 | const SmallVectorImpl<User *> &AllRelocateCalls, |
| 526 | DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> & |
| 527 | RelocateInstMap) { |
| 528 | // Collect information in two maps: one primarily for locating the base object |
| 529 | // while filling the second map; the second map is the final structure holding |
| 530 | // a mapping between Base and corresponding Derived relocate calls |
| 531 | DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap; |
| 532 | for (auto &U : AllRelocateCalls) { |
| 533 | GCRelocateOperands ThisRelocate(U); |
| 534 | IntrinsicInst *I = cast<IntrinsicInst>(U); |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 535 | auto K = std::make_pair(ThisRelocate.getBasePtrIndex(), |
| 536 | ThisRelocate.getDerivedPtrIndex()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 537 | RelocateIdxMap.insert(std::make_pair(K, I)); |
| 538 | } |
| 539 | for (auto &Item : RelocateIdxMap) { |
| 540 | std::pair<unsigned, unsigned> Key = Item.first; |
| 541 | if (Key.first == Key.second) |
| 542 | // Base relocation: nothing to insert |
| 543 | continue; |
| 544 | |
| 545 | IntrinsicInst *I = Item.second; |
| 546 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 547 | |
| 548 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 549 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 550 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 551 | // TODO: We might want to insert a new base object relocate and gep off |
| 552 | // that, if there are enough derived object relocates. |
| 553 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 554 | |
| 555 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 556 | } |
| 557 | } |
| 558 | |
| 559 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 560 | // small integer constants |
| 561 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 562 | SmallVectorImpl<Value *> &OffsetV) { |
| 563 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 564 | // Only accept small constant integer operands |
| 565 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 566 | if (!Op || Op->getZExtValue() > 20) |
| 567 | return false; |
| 568 | } |
| 569 | |
| 570 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 571 | OffsetV.push_back(GEP->getOperand(i)); |
| 572 | return true; |
| 573 | } |
| 574 | |
| 575 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 576 | // replace, computes a replacement, and affects it. |
| 577 | static bool |
| 578 | simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase, |
| 579 | const SmallVectorImpl<IntrinsicInst *> &Targets) { |
| 580 | bool MadeChange = false; |
| 581 | for (auto &ToReplace : Targets) { |
| 582 | GCRelocateOperands MasterRelocate(RelocatedBase); |
| 583 | GCRelocateOperands ThisRelocate(ToReplace); |
| 584 | |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 585 | assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 586 | "Not relocating a derived object of the original base object"); |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 587 | if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 588 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 589 | continue; |
| 590 | } |
| 591 | |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 592 | Value *Base = ThisRelocate.getBasePtr(); |
| 593 | auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 594 | if (!Derived || Derived->getPointerOperand() != Base) |
| 595 | continue; |
| 596 | |
| 597 | SmallVector<Value *, 2> OffsetV; |
| 598 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 599 | continue; |
| 600 | |
| 601 | // Create a Builder and replace the target callsite with a gep |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 602 | assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator"); |
| 603 | |
| 604 | // Insert after RelocatedBase |
| 605 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 606 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 607 | |
| 608 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 609 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 610 | // match, and we should reuse it to get the derived pointer. But it could be |
| 611 | // cases like this: |
| 612 | // bb1: |
| 613 | // ... |
| 614 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 615 | // br label %merge |
| 616 | // |
| 617 | // bb2: |
| 618 | // ... |
| 619 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 620 | // br label %merge |
| 621 | // |
| 622 | // merge: |
| 623 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 624 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 625 | // |
| 626 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 627 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 628 | // the extra bitcast should be optimized away in later passes. |
| 629 | Instruction *ActualRelocatedBase = RelocatedBase; |
| 630 | if (RelocatedBase->getType() != Base->getType()) { |
| 631 | ActualRelocatedBase = |
| 632 | cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType())); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 633 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 634 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 635 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 636 | Instruction *ReplacementInst = cast<Instruction>(Replacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 637 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 638 | // If the newly generated derived pointer's type does not match the original derived |
| 639 | // pointer's type, cast the new derived pointer to match it. Same reasoning as above. |
| 640 | Instruction *ActualReplacement = ReplacementInst; |
| 641 | if (ReplacementInst->getType() != ToReplace->getType()) { |
| 642 | ActualReplacement = |
| 643 | cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType())); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 644 | } |
| 645 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 646 | ToReplace->eraseFromParent(); |
| 647 | |
| 648 | MadeChange = true; |
| 649 | } |
| 650 | return MadeChange; |
| 651 | } |
| 652 | |
| 653 | // Turns this: |
| 654 | // |
| 655 | // %base = ... |
| 656 | // %ptr = gep %base + 15 |
| 657 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 658 | // %base' = relocate(%tok, i32 4, i32 4) |
| 659 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 660 | // %val = load %ptr' |
| 661 | // |
| 662 | // into this: |
| 663 | // |
| 664 | // %base = ... |
| 665 | // %ptr = gep %base + 15 |
| 666 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 667 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 668 | // %ptr' = gep %base' + 15 |
| 669 | // %val = load %ptr' |
| 670 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 671 | bool MadeChange = false; |
| 672 | SmallVector<User *, 2> AllRelocateCalls; |
| 673 | |
| 674 | for (auto *U : I.users()) |
| 675 | if (isGCRelocate(dyn_cast<Instruction>(U))) |
| 676 | // Collect all the relocate calls associated with a statepoint |
| 677 | AllRelocateCalls.push_back(U); |
| 678 | |
| 679 | // We need atleast one base pointer relocation + one derived pointer |
| 680 | // relocation to mangle |
| 681 | if (AllRelocateCalls.size() < 2) |
| 682 | return false; |
| 683 | |
| 684 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 685 | // corresponding derived relocate instructions |
| 686 | DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap; |
| 687 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 688 | if (RelocateInstMap.empty()) |
| 689 | return false; |
| 690 | |
| 691 | for (auto &Item : RelocateInstMap) |
| 692 | // Item.first is the RelocatedBase to offset against |
| 693 | // Item.second is the vector of Targets to replace |
| 694 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 695 | return MadeChange; |
| 696 | } |
| 697 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 698 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 699 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 700 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 701 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 702 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 703 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 704 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 705 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 706 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 707 | UI != E; ) { |
| 708 | Use &TheUse = UI.getUse(); |
| 709 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 710 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 711 | // Figure out which BB this cast is used in. For PHI's this is the |
| 712 | // appropriate predecessor block. |
| 713 | BasicBlock *UserBB = User->getParent(); |
| 714 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 715 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 716 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 717 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 718 | // Preincrement use iterator so we don't invalidate it. |
| 719 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 720 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 721 | // If this user is in the same block as the cast, don't change the cast. |
| 722 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 723 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 724 | // If we have already inserted a cast into this block, use it. |
| 725 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 726 | |
| 727 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 728 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 729 | InsertedCast = |
| 730 | CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 731 | InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 732 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 733 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 734 | // Replace a use of the cast with a use of the new cast. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 735 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 736 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 737 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 738 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 739 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 740 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 741 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 742 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 743 | MadeChange = true; |
| 744 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 745 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 746 | return MadeChange; |
| 747 | } |
| 748 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 749 | /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop |
| 750 | /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC), |
| 751 | /// sink it into user blocks to reduce the number of virtual |
| 752 | /// registers that must be created and coalesced. |
| 753 | /// |
| 754 | /// Return true if any changes are made. |
| 755 | /// |
| 756 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){ |
| 757 | // If this is a noop copy, |
| 758 | EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType()); |
| 759 | EVT DstVT = TLI.getValueType(CI->getType()); |
| 760 | |
| 761 | // This is an fp<->int conversion? |
| 762 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 763 | return false; |
| 764 | |
| 765 | // If this is an extension, it will be a zero or sign extension, which |
| 766 | // isn't a noop. |
| 767 | if (SrcVT.bitsLT(DstVT)) return false; |
| 768 | |
| 769 | // If these values will be promoted, find out what they will be promoted |
| 770 | // to. This helps us consider truncates on PPC as noop copies when they |
| 771 | // are. |
| 772 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 773 | TargetLowering::TypePromoteInteger) |
| 774 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 775 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 776 | TargetLowering::TypePromoteInteger) |
| 777 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 778 | |
| 779 | // If, after promotion, these are the same types, this is a noop copy. |
| 780 | if (SrcVT != DstVT) |
| 781 | return false; |
| 782 | |
| 783 | return SinkCast(CI); |
| 784 | } |
| 785 | |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 786 | /// CombineUAddWithOverflow - try to combine CI into a call to the |
| 787 | /// llvm.uadd.with.overflow intrinsic if possible. |
| 788 | /// |
| 789 | /// Return true if any changes were made. |
| 790 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 791 | Value *A, *B; |
| 792 | Instruction *AddI; |
| 793 | if (!match(CI, |
| 794 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 795 | return false; |
| 796 | |
| 797 | Type *Ty = AddI->getType(); |
| 798 | if (!isa<IntegerType>(Ty)) |
| 799 | return false; |
| 800 | |
| 801 | // We don't want to move around uses of condition values this late, so we we |
| 802 | // check if it is legal to create the call to the intrinsic in the basic |
| 803 | // block containing the icmp: |
| 804 | |
| 805 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 806 | return false; |
| 807 | |
| 808 | #ifndef NDEBUG |
| 809 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 810 | // for now: |
| 811 | if (AddI->hasOneUse()) |
| 812 | assert(*AddI->user_begin() == CI && "expected!"); |
| 813 | #endif |
| 814 | |
| 815 | Module *M = CI->getParent()->getParent()->getParent(); |
| 816 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 817 | |
| 818 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 819 | |
| 820 | auto *UAddWithOverflow = |
| 821 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 822 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 823 | auto *Overflow = |
| 824 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 825 | |
| 826 | CI->replaceAllUsesWith(Overflow); |
| 827 | AddI->replaceAllUsesWith(UAdd); |
| 828 | CI->eraseFromParent(); |
| 829 | AddI->eraseFromParent(); |
| 830 | return true; |
| 831 | } |
| 832 | |
| 833 | /// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 834 | /// the number of virtual registers that must be created and coalesced. This is |
Chris Lattner | 2740694 | 2007-08-02 16:53:43 +0000 | [diff] [blame] | 835 | /// a clear win except on targets with multiple condition code registers |
| 836 | /// (PowerPC), where it might lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 837 | /// |
| 838 | /// Return true if any changes are made. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 839 | static bool SinkCmpExpression(CmpInst *CI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 840 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 841 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 842 | /// InsertedCmp - Only insert a cmp in each block once. |
| 843 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 844 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 845 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 846 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 847 | UI != E; ) { |
| 848 | Use &TheUse = UI.getUse(); |
| 849 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 850 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 851 | // Preincrement use iterator so we don't invalidate it. |
| 852 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 853 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 854 | // Don't bother for PHI nodes. |
| 855 | if (isa<PHINode>(User)) |
| 856 | continue; |
| 857 | |
| 858 | // Figure out which BB this cmp is used in. |
| 859 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 860 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 861 | // If this user is in the same block as the cmp, don't change the cmp. |
| 862 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 863 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 864 | // If we have already inserted a cmp into this block, use it. |
| 865 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 866 | |
| 867 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 868 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 869 | InsertedCmp = |
Dan Gohman | ad1f0a1 | 2009-08-25 23:17:54 +0000 | [diff] [blame] | 870 | CmpInst::Create(CI->getOpcode(), |
Owen Anderson | 1e5f00e | 2009-07-09 23:48:35 +0000 | [diff] [blame] | 871 | CI->getPredicate(), CI->getOperand(0), |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 872 | CI->getOperand(1), "", InsertPt); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 873 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 874 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 875 | // Replace a use of the cmp with a use of the new cmp. |
| 876 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 877 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 878 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 879 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 880 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 881 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 882 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 883 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 884 | MadeChange = true; |
| 885 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 886 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 887 | return MadeChange; |
| 888 | } |
| 889 | |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 890 | static bool OptimizeCmpExpression(CmpInst *CI) { |
| 891 | if (SinkCmpExpression(CI)) |
| 892 | return true; |
| 893 | |
| 894 | if (CombineUAddWithOverflow(CI)) |
| 895 | return true; |
| 896 | |
| 897 | return false; |
| 898 | } |
| 899 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 900 | /// isExtractBitsCandidateUse - Check if the candidates could |
| 901 | /// be combined with shift instruction, which includes: |
| 902 | /// 1. Truncate instruction |
| 903 | /// 2. And instruction and the imm is a mask of the low bits: |
| 904 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 905 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 906 | if (!isa<TruncInst>(User)) { |
| 907 | if (User->getOpcode() != Instruction::And || |
| 908 | !isa<ConstantInt>(User->getOperand(1))) |
| 909 | return false; |
| 910 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 911 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 912 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 913 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 914 | return false; |
| 915 | } |
| 916 | return true; |
| 917 | } |
| 918 | |
| 919 | /// SinkShiftAndTruncate - sink both shift and truncate instruction |
| 920 | /// to the use of truncate's BB. |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 921 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 922 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 923 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
| 924 | const TargetLowering &TLI) { |
| 925 | BasicBlock *UserBB = User->getParent(); |
| 926 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 927 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 928 | bool MadeChange = false; |
| 929 | |
| 930 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 931 | TruncE = TruncI->user_end(); |
| 932 | TruncUI != TruncE;) { |
| 933 | |
| 934 | Use &TruncTheUse = TruncUI.getUse(); |
| 935 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 936 | // Preincrement use iterator so we don't invalidate it. |
| 937 | |
| 938 | ++TruncUI; |
| 939 | |
| 940 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 941 | if (!ISDOpcode) |
| 942 | continue; |
| 943 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 944 | // If the use is actually a legal node, there will not be an |
| 945 | // implicit truncate. |
| 946 | // FIXME: always querying the result type is just an |
| 947 | // approximation; some nodes' legality is determined by the |
| 948 | // operand or other means. There's no good way to find out though. |
Ahmed Bougacha | 0788d49 | 2014-11-12 22:16:55 +0000 | [diff] [blame] | 949 | if (TLI.isOperationLegalOrCustom( |
| 950 | ISDOpcode, TLI.getValueType(TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 951 | continue; |
| 952 | |
| 953 | // Don't bother for PHI nodes. |
| 954 | if (isa<PHINode>(TruncUser)) |
| 955 | continue; |
| 956 | |
| 957 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 958 | |
| 959 | if (UserBB == TruncUserBB) |
| 960 | continue; |
| 961 | |
| 962 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 963 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 964 | |
| 965 | if (!InsertedShift && !InsertedTrunc) { |
| 966 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
| 967 | // Sink the shift |
| 968 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 969 | InsertedShift = |
| 970 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 971 | else |
| 972 | InsertedShift = |
| 973 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 974 | |
| 975 | // Sink the trunc |
| 976 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 977 | TruncInsertPt++; |
| 978 | |
| 979 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
| 980 | TruncI->getType(), "", TruncInsertPt); |
| 981 | |
| 982 | MadeChange = true; |
| 983 | |
| 984 | TruncTheUse = InsertedTrunc; |
| 985 | } |
| 986 | } |
| 987 | return MadeChange; |
| 988 | } |
| 989 | |
| 990 | /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if |
| 991 | /// the uses could potentially be combined with this shift instruction and |
| 992 | /// generate BitExtract instruction. It will only be applied if the architecture |
| 993 | /// supports BitExtract instruction. Here is an example: |
| 994 | /// BB1: |
| 995 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 996 | /// BB2: |
| 997 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 998 | /// ==> |
| 999 | /// |
| 1000 | /// BB2: |
| 1001 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1002 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1003 | /// |
| 1004 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1005 | /// instruction. |
| 1006 | /// Return true if any changes are made. |
| 1007 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
| 1008 | const TargetLowering &TLI) { |
| 1009 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1010 | |
| 1011 | /// Only insert instructions in each block once. |
| 1012 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1013 | |
| 1014 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType())); |
| 1015 | |
| 1016 | bool MadeChange = false; |
| 1017 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1018 | UI != E;) { |
| 1019 | Use &TheUse = UI.getUse(); |
| 1020 | Instruction *User = cast<Instruction>(*UI); |
| 1021 | // Preincrement use iterator so we don't invalidate it. |
| 1022 | ++UI; |
| 1023 | |
| 1024 | // Don't bother for PHI nodes. |
| 1025 | if (isa<PHINode>(User)) |
| 1026 | continue; |
| 1027 | |
| 1028 | if (!isExtractBitsCandidateUse(User)) |
| 1029 | continue; |
| 1030 | |
| 1031 | BasicBlock *UserBB = User->getParent(); |
| 1032 | |
| 1033 | if (UserBB == DefBB) { |
| 1034 | // If the shift and truncate instruction are in the same BB. The use of |
| 1035 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1036 | // legal. In this case, we would like to sink both shift and truncate |
| 1037 | // instruction to the BB of TruncUse. |
| 1038 | // for example: |
| 1039 | // BB1: |
| 1040 | // i64 shift.result = lshr i64 opnd, imm |
| 1041 | // trunc.result = trunc shift.result to i16 |
| 1042 | // |
| 1043 | // BB2: |
| 1044 | // ----> We will have an implicit truncate here if the architecture does |
| 1045 | // not have i16 compare. |
| 1046 | // cmp i16 trunc.result, opnd2 |
| 1047 | // |
| 1048 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1049 | // If the type of the truncate is legal, no trucate will be |
| 1050 | // introduced in other basic blocks. |
| 1051 | && (!TLI.isTypeLegal(TLI.getValueType(User->getType())))) |
| 1052 | MadeChange = |
| 1053 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI); |
| 1054 | |
| 1055 | continue; |
| 1056 | } |
| 1057 | // If we have already inserted a shift into this block, use it. |
| 1058 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1059 | |
| 1060 | if (!InsertedShift) { |
| 1061 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 1062 | |
| 1063 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 1064 | InsertedShift = |
| 1065 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 1066 | else |
| 1067 | InsertedShift = |
| 1068 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 1069 | |
| 1070 | MadeChange = true; |
| 1071 | } |
| 1072 | |
| 1073 | // Replace a use of the shift with a use of the new shift. |
| 1074 | TheUse = InsertedShift; |
| 1075 | } |
| 1076 | |
| 1077 | // If we removed all uses, nuke the shift. |
| 1078 | if (ShiftI->use_empty()) |
| 1079 | ShiftI->eraseFromParent(); |
| 1080 | |
| 1081 | return MadeChange; |
| 1082 | } |
| 1083 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1084 | // ScalarizeMaskedLoad() translates masked load intrinsic, like |
| 1085 | // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, |
| 1086 | // <16 x i1> %mask, <16 x i32> %passthru) |
| 1087 | // to a chain of basic blocks, whith loading element one-by-one if |
| 1088 | // the appropriate mask bit is set |
| 1089 | // |
| 1090 | // %1 = bitcast i8* %addr to i32* |
| 1091 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1092 | // %3 = icmp eq i1 %2, true |
| 1093 | // br i1 %3, label %cond.load, label %else |
| 1094 | // |
| 1095 | //cond.load: ; preds = %0 |
| 1096 | // %4 = getelementptr i32* %1, i32 0 |
| 1097 | // %5 = load i32* %4 |
| 1098 | // %6 = insertelement <16 x i32> undef, i32 %5, i32 0 |
| 1099 | // br label %else |
| 1100 | // |
| 1101 | //else: ; preds = %0, %cond.load |
| 1102 | // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] |
| 1103 | // %7 = extractelement <16 x i1> %mask, i32 1 |
| 1104 | // %8 = icmp eq i1 %7, true |
| 1105 | // br i1 %8, label %cond.load1, label %else2 |
| 1106 | // |
| 1107 | //cond.load1: ; preds = %else |
| 1108 | // %9 = getelementptr i32* %1, i32 1 |
| 1109 | // %10 = load i32* %9 |
| 1110 | // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 |
| 1111 | // br label %else2 |
| 1112 | // |
| 1113 | //else2: ; preds = %else, %cond.load1 |
| 1114 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1115 | // %12 = extractelement <16 x i1> %mask, i32 2 |
| 1116 | // %13 = icmp eq i1 %12, true |
| 1117 | // br i1 %13, label %cond.load4, label %else5 |
| 1118 | // |
| 1119 | static void ScalarizeMaskedLoad(CallInst *CI) { |
| 1120 | Value *Ptr = CI->getArgOperand(0); |
| 1121 | Value *Src0 = CI->getArgOperand(3); |
| 1122 | Value *Mask = CI->getArgOperand(2); |
| 1123 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
| 1124 | Type *EltTy = VecType->getElementType(); |
| 1125 | |
| 1126 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1127 | |
| 1128 | IRBuilder<> Builder(CI->getContext()); |
| 1129 | Instruction *InsertPt = CI; |
| 1130 | BasicBlock *IfBlock = CI->getParent(); |
| 1131 | BasicBlock *CondBlock = nullptr; |
| 1132 | BasicBlock *PrevIfBlock = CI->getParent(); |
| 1133 | Builder.SetInsertPoint(InsertPt); |
| 1134 | |
| 1135 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1136 | |
| 1137 | // Bitcast %addr fron i8* to EltTy* |
| 1138 | Type *NewPtrType = |
| 1139 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1140 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
| 1141 | Value *UndefVal = UndefValue::get(VecType); |
| 1142 | |
| 1143 | // The result vector |
| 1144 | Value *VResult = UndefVal; |
| 1145 | |
| 1146 | PHINode *Phi = nullptr; |
| 1147 | Value *PrevPhi = UndefVal; |
| 1148 | |
| 1149 | unsigned VectorWidth = VecType->getNumElements(); |
| 1150 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1151 | |
| 1152 | // Fill the "else" block, created in the previous iteration |
| 1153 | // |
| 1154 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1155 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1156 | // %to_load = icmp eq i1 %mask_1, true |
| 1157 | // br i1 %to_load, label %cond.load, label %else |
| 1158 | // |
| 1159 | if (Idx > 0) { |
| 1160 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1161 | Phi->addIncoming(VResult, CondBlock); |
| 1162 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1163 | PrevPhi = Phi; |
| 1164 | VResult = Phi; |
| 1165 | } |
| 1166 | |
| 1167 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1168 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1169 | ConstantInt::get(Predicate->getType(), 1)); |
| 1170 | |
| 1171 | // Create "cond" block |
| 1172 | // |
| 1173 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1174 | // %Elt = load i32* %EltAddr |
| 1175 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1176 | // |
| 1177 | CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); |
| 1178 | Builder.SetInsertPoint(InsertPt); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1179 | |
| 1180 | Value *Gep = |
| 1181 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1182 | LoadInst* Load = Builder.CreateLoad(Gep, false); |
| 1183 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); |
| 1184 | |
| 1185 | // Create "else" block, fill it in the next iteration |
| 1186 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1187 | Builder.SetInsertPoint(InsertPt); |
| 1188 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1189 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1190 | OldBr->eraseFromParent(); |
| 1191 | PrevIfBlock = IfBlock; |
| 1192 | IfBlock = NewIfBlock; |
| 1193 | } |
| 1194 | |
| 1195 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1196 | Phi->addIncoming(VResult, CondBlock); |
| 1197 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1198 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1199 | CI->replaceAllUsesWith(NewI); |
| 1200 | CI->eraseFromParent(); |
| 1201 | } |
| 1202 | |
| 1203 | // ScalarizeMaskedStore() translates masked store intrinsic, like |
| 1204 | // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, |
| 1205 | // <16 x i1> %mask) |
| 1206 | // to a chain of basic blocks, that stores element one-by-one if |
| 1207 | // the appropriate mask bit is set |
| 1208 | // |
| 1209 | // %1 = bitcast i8* %addr to i32* |
| 1210 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1211 | // %3 = icmp eq i1 %2, true |
| 1212 | // br i1 %3, label %cond.store, label %else |
| 1213 | // |
| 1214 | // cond.store: ; preds = %0 |
| 1215 | // %4 = extractelement <16 x i32> %val, i32 0 |
| 1216 | // %5 = getelementptr i32* %1, i32 0 |
| 1217 | // store i32 %4, i32* %5 |
| 1218 | // br label %else |
| 1219 | // |
| 1220 | // else: ; preds = %0, %cond.store |
| 1221 | // %6 = extractelement <16 x i1> %mask, i32 1 |
| 1222 | // %7 = icmp eq i1 %6, true |
| 1223 | // br i1 %7, label %cond.store1, label %else2 |
| 1224 | // |
| 1225 | // cond.store1: ; preds = %else |
| 1226 | // %8 = extractelement <16 x i32> %val, i32 1 |
| 1227 | // %9 = getelementptr i32* %1, i32 1 |
| 1228 | // store i32 %8, i32* %9 |
| 1229 | // br label %else2 |
| 1230 | // . . . |
| 1231 | static void ScalarizeMaskedStore(CallInst *CI) { |
| 1232 | Value *Ptr = CI->getArgOperand(1); |
| 1233 | Value *Src = CI->getArgOperand(0); |
| 1234 | Value *Mask = CI->getArgOperand(3); |
| 1235 | |
| 1236 | VectorType *VecType = dyn_cast<VectorType>(Src->getType()); |
| 1237 | Type *EltTy = VecType->getElementType(); |
| 1238 | |
| 1239 | assert(VecType && "Unexpected data type in masked store intrinsic"); |
| 1240 | |
| 1241 | IRBuilder<> Builder(CI->getContext()); |
| 1242 | Instruction *InsertPt = CI; |
| 1243 | BasicBlock *IfBlock = CI->getParent(); |
| 1244 | Builder.SetInsertPoint(InsertPt); |
| 1245 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1246 | |
| 1247 | // Bitcast %addr fron i8* to EltTy* |
| 1248 | Type *NewPtrType = |
| 1249 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1250 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
| 1251 | |
| 1252 | unsigned VectorWidth = VecType->getNumElements(); |
| 1253 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1254 | |
| 1255 | // Fill the "else" block, created in the previous iteration |
| 1256 | // |
| 1257 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1258 | // %to_store = icmp eq i1 %mask_1, true |
| 1259 | // br i1 %to_load, label %cond.store, label %else |
| 1260 | // |
| 1261 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1262 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1263 | ConstantInt::get(Predicate->getType(), 1)); |
| 1264 | |
| 1265 | // Create "cond" block |
| 1266 | // |
| 1267 | // %OneElt = extractelement <16 x i32> %Src, i32 Idx |
| 1268 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1269 | // %store i32 %OneElt, i32* %EltAddr |
| 1270 | // |
| 1271 | BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); |
| 1272 | Builder.SetInsertPoint(InsertPt); |
| 1273 | |
| 1274 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1275 | Value *Gep = |
| 1276 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1277 | Builder.CreateStore(OneElt, Gep); |
| 1278 | |
| 1279 | // Create "else" block, fill it in the next iteration |
| 1280 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1281 | Builder.SetInsertPoint(InsertPt); |
| 1282 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1283 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1284 | OldBr->eraseFromParent(); |
| 1285 | IfBlock = NewIfBlock; |
| 1286 | } |
| 1287 | CI->eraseFromParent(); |
| 1288 | } |
| 1289 | |
| 1290 | bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1291 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1292 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1293 | // Lower inline assembly if we can. |
| 1294 | // If we found an inline asm expession, and if the target knows how to |
| 1295 | // lower it to normal LLVM code, do so now. |
| 1296 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 1297 | if (TLI->ExpandInlineAsm(CI)) { |
| 1298 | // Avoid invalidating the iterator. |
| 1299 | CurInstIterator = BB->begin(); |
| 1300 | // Avoid processing instructions out of order, which could cause |
| 1301 | // reuse before a value is defined. |
| 1302 | SunkAddrs.clear(); |
| 1303 | return true; |
| 1304 | } |
| 1305 | // Sink address computing for memory operands into the block. |
| 1306 | if (OptimizeInlineAsmInst(CI)) |
| 1307 | return true; |
| 1308 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1309 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1310 | const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr; |
| 1311 | |
| 1312 | // Align the pointer arguments to this call if the target thinks it's a good |
| 1313 | // idea |
| 1314 | unsigned MinSize, PrefAlign; |
| 1315 | if (TLI && TD && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
| 1316 | for (auto &Arg : CI->arg_operands()) { |
| 1317 | // We want to align both objects whose address is used directly and |
| 1318 | // objects whose address is used in casts and GEPs, though it only makes |
| 1319 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 1320 | // if size - offset meets the size threshold. |
| 1321 | if (!Arg->getType()->isPointerTy()) |
| 1322 | continue; |
| 1323 | APInt Offset(TD->getPointerSizeInBits( |
| 1324 | cast<PointerType>(Arg->getType())->getAddressSpace()), 0); |
| 1325 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*TD, Offset); |
| 1326 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1327 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 1328 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1329 | AllocaInst *AI; |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1330 | if ((AI = dyn_cast<AllocaInst>(Val)) && |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1331 | AI->getAlignment() < PrefAlign && |
| 1332 | TD->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
| 1333 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1334 | // Global variables can only be aligned if they are defined in this |
| 1335 | // object (i.e. they are uniquely initialized in this object), and |
| 1336 | // over-aligning global variables that have an explicit section is |
| 1337 | // forbidden. |
| 1338 | GlobalVariable *GV; |
| 1339 | if ((GV = dyn_cast<GlobalVariable>(Val)) && |
| 1340 | GV->hasUniqueInitializer() && |
| 1341 | !GV->hasSection() && |
| 1342 | GV->getAlignment() < PrefAlign && |
| 1343 | TD->getTypeAllocSize( |
| 1344 | GV->getType()->getElementType()) >= MinSize + Offset2) |
| 1345 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1346 | } |
| 1347 | // If this is a memcpy (or similar) then we may be able to improve the |
| 1348 | // alignment |
| 1349 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
| 1350 | unsigned Align = getKnownAlignment(MI->getDest(), *TD); |
| 1351 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
| 1352 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *TD)); |
| 1353 | if (Align > MI->getAlignment()) |
| 1354 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
| 1355 | } |
| 1356 | } |
| 1357 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1358 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1359 | if (II) { |
| 1360 | switch (II->getIntrinsicID()) { |
| 1361 | default: break; |
| 1362 | case Intrinsic::objectsize: { |
| 1363 | // Lower all uses of llvm.objectsize.* |
| 1364 | bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1); |
| 1365 | Type *ReturnTy = CI->getType(); |
| 1366 | Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1367 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1368 | // Substituting this can cause recursive simplifications, which can |
| 1369 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 1370 | // happens. |
| 1371 | WeakVH IterHandle(CurInstIterator); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1372 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1373 | replaceAndRecursivelySimplify(CI, RetVal, |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 1374 | TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1375 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1376 | // If the iterator instruction was recursively deleted, start over at the |
| 1377 | // start of the block. |
| 1378 | if (IterHandle != CurInstIterator) { |
| 1379 | CurInstIterator = BB->begin(); |
| 1380 | SunkAddrs.clear(); |
| 1381 | } |
| 1382 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 1383 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1384 | case Intrinsic::masked_load: { |
| 1385 | // Scalarize unsupported vector masked load |
| 1386 | if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) { |
| 1387 | ScalarizeMaskedLoad(CI); |
| 1388 | ModifiedDT = true; |
| 1389 | return true; |
| 1390 | } |
| 1391 | return false; |
| 1392 | } |
| 1393 | case Intrinsic::masked_store: { |
| 1394 | if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) { |
| 1395 | ScalarizeMaskedStore(CI); |
| 1396 | ModifiedDT = true; |
| 1397 | return true; |
| 1398 | } |
| 1399 | return false; |
| 1400 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1401 | case Intrinsic::aarch64_stlxr: |
| 1402 | case Intrinsic::aarch64_stxr: { |
| 1403 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 1404 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 1405 | ExtVal->getParent() == CI->getParent()) |
| 1406 | return false; |
| 1407 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 1408 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 1409 | // Mark this instruction as "inserted by CGP", so that other |
| 1410 | // optimizations don't touch it. |
| 1411 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1412 | return true; |
| 1413 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1414 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1415 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1416 | if (TLI) { |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1417 | // Unknown address space. |
| 1418 | // TODO: Target hook to pick which address space the intrinsic cares |
| 1419 | // about? |
| 1420 | unsigned AddrSpace = ~0u; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1421 | SmallVector<Value*, 2> PtrOps; |
| 1422 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1423 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1424 | while (!PtrOps.empty()) |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1425 | if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1426 | return true; |
| 1427 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 1428 | } |
| 1429 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1430 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1431 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 1432 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 1433 | // Lower all default uses of _chk calls. This is very similar |
| 1434 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1435 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 1436 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1437 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1438 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 1439 | CI->replaceAllUsesWith(V); |
| 1440 | CI->eraseFromParent(); |
| 1441 | return true; |
| 1442 | } |
| 1443 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1444 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1445 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1446 | /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return |
| 1447 | /// instructions to the predecessor to enable tail call optimizations. The |
| 1448 | /// case it is currently looking for is: |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1449 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1450 | /// bb0: |
| 1451 | /// %tmp0 = tail call i32 @f0() |
| 1452 | /// br label %return |
| 1453 | /// bb1: |
| 1454 | /// %tmp1 = tail call i32 @f1() |
| 1455 | /// br label %return |
| 1456 | /// bb2: |
| 1457 | /// %tmp2 = tail call i32 @f2() |
| 1458 | /// br label %return |
| 1459 | /// return: |
| 1460 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 1461 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1462 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1463 | /// |
| 1464 | /// => |
| 1465 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1466 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1467 | /// bb0: |
| 1468 | /// %tmp0 = tail call i32 @f0() |
| 1469 | /// ret i32 %tmp0 |
| 1470 | /// bb1: |
| 1471 | /// %tmp1 = tail call i32 @f1() |
| 1472 | /// ret i32 %tmp1 |
| 1473 | /// bb2: |
| 1474 | /// %tmp2 = tail call i32 @f2() |
| 1475 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1476 | /// @endcode |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 1477 | bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 1478 | if (!TLI) |
| 1479 | return false; |
| 1480 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 1481 | ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 1482 | if (!RI) |
| 1483 | return false; |
| 1484 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1485 | PHINode *PN = nullptr; |
| 1486 | BitCastInst *BCI = nullptr; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1487 | Value *V = RI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1488 | if (V) { |
| 1489 | BCI = dyn_cast<BitCastInst>(V); |
| 1490 | if (BCI) |
| 1491 | V = BCI->getOperand(0); |
| 1492 | |
| 1493 | PN = dyn_cast<PHINode>(V); |
| 1494 | if (!PN) |
| 1495 | return false; |
| 1496 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1497 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1498 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1499 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1500 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1501 | // It's not safe to eliminate the sign / zero extension of the return value. |
| 1502 | // See llvm::isInTailCallPosition(). |
| 1503 | const Function *F = BB->getParent(); |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1504 | AttributeSet CallerAttrs = F->getAttributes(); |
| 1505 | if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || |
| 1506 | CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1507 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1508 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1509 | // Make sure there are no instructions between the PHI and return, or that the |
| 1510 | // return is the first instruction in the block. |
| 1511 | if (PN) { |
| 1512 | BasicBlock::iterator BI = BB->begin(); |
| 1513 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1514 | if (&*BI == BCI) |
| 1515 | // Also skip over the bitcast. |
| 1516 | ++BI; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1517 | if (&*BI != RI) |
| 1518 | return false; |
| 1519 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1520 | BasicBlock::iterator BI = BB->begin(); |
| 1521 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
| 1522 | if (&*BI != RI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1523 | return false; |
| 1524 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1525 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1526 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 1527 | /// call. |
| 1528 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1529 | if (PN) { |
| 1530 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 1531 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 1532 | // Make sure the phi value is indeed produced by the tail call. |
| 1533 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
| 1534 | TLI->mayBeEmittedAsTailCall(CI)) |
| 1535 | TailCalls.push_back(CI); |
| 1536 | } |
| 1537 | } else { |
| 1538 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1539 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 1540 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1541 | continue; |
| 1542 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1543 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1544 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 1545 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1546 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 1547 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1548 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1549 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1550 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Cameron Zwarich | 2edfe77 | 2011-03-24 15:54:11 +0000 | [diff] [blame] | 1551 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1552 | TailCalls.push_back(CI); |
| 1553 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1554 | } |
| 1555 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1556 | bool Changed = false; |
| 1557 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1558 | CallInst *CI = TailCalls[i]; |
| 1559 | CallSite CS(CI); |
| 1560 | |
| 1561 | // Conservatively require the attributes of the call to match those of the |
| 1562 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1563 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 1564 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1565 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1566 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1567 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1568 | continue; |
| 1569 | |
| 1570 | // Make sure the call instruction is followed by an unconditional branch to |
| 1571 | // the return block. |
| 1572 | BasicBlock *CallBB = CI->getParent(); |
| 1573 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 1574 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 1575 | continue; |
| 1576 | |
| 1577 | // Duplicate the return into CallBB. |
| 1578 | (void)FoldReturnIntoUncondBranch(RI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 1579 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1580 | ++NumRetsDup; |
| 1581 | } |
| 1582 | |
| 1583 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 1584 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1585 | BB->eraseFromParent(); |
| 1586 | |
| 1587 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1588 | } |
| 1589 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1590 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1591 | // Memory Optimization |
| 1592 | //===----------------------------------------------------------------------===// |
| 1593 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1594 | namespace { |
| 1595 | |
| 1596 | /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode |
| 1597 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 1598 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1599 | Value *BaseReg; |
| 1600 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1601 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1602 | void print(raw_ostream &OS) const; |
| 1603 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1604 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1605 | bool operator==(const ExtAddrMode& O) const { |
| 1606 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 1607 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 1608 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 1609 | } |
| 1610 | }; |
| 1611 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 1612 | #ifndef NDEBUG |
| 1613 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 1614 | AM.print(OS); |
| 1615 | return OS; |
| 1616 | } |
| 1617 | #endif |
| 1618 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1619 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 1620 | bool NeedPlus = false; |
| 1621 | OS << "["; |
| 1622 | if (BaseGV) { |
| 1623 | OS << (NeedPlus ? " + " : "") |
| 1624 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1625 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1626 | NeedPlus = true; |
| 1627 | } |
| 1628 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 1629 | if (BaseOffs) { |
| 1630 | OS << (NeedPlus ? " + " : "") |
| 1631 | << BaseOffs; |
| 1632 | NeedPlus = true; |
| 1633 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1634 | |
| 1635 | if (BaseReg) { |
| 1636 | OS << (NeedPlus ? " + " : "") |
| 1637 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1638 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1639 | NeedPlus = true; |
| 1640 | } |
| 1641 | if (Scale) { |
| 1642 | OS << (NeedPlus ? " + " : "") |
| 1643 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1644 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1645 | } |
| 1646 | |
| 1647 | OS << ']'; |
| 1648 | } |
| 1649 | |
| 1650 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 1651 | void ExtAddrMode::dump() const { |
| 1652 | print(dbgs()); |
| 1653 | dbgs() << '\n'; |
| 1654 | } |
| 1655 | #endif |
| 1656 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1657 | /// \brief This class provides transaction based operation on the IR. |
| 1658 | /// Every change made through this class is recorded in the internal state and |
| 1659 | /// can be undone (rollback) until commit is called. |
| 1660 | class TypePromotionTransaction { |
| 1661 | |
| 1662 | /// \brief This represents the common interface of the individual transaction. |
| 1663 | /// Each class implements the logic for doing one specific modification on |
| 1664 | /// the IR via the TypePromotionTransaction. |
| 1665 | class TypePromotionAction { |
| 1666 | protected: |
| 1667 | /// The Instruction modified. |
| 1668 | Instruction *Inst; |
| 1669 | |
| 1670 | public: |
| 1671 | /// \brief Constructor of the action. |
| 1672 | /// The constructor performs the related action on the IR. |
| 1673 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 1674 | |
| 1675 | virtual ~TypePromotionAction() {} |
| 1676 | |
| 1677 | /// \brief Undo the modification done by this action. |
| 1678 | /// When this method is called, the IR must be in the same state as it was |
| 1679 | /// before this action was applied. |
| 1680 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 1681 | /// state as it was directly after this action was applied. |
| 1682 | virtual void undo() = 0; |
| 1683 | |
| 1684 | /// \brief Advocate every change made by this action. |
| 1685 | /// When the results on the IR of the action are to be kept, it is important |
| 1686 | /// to call this function, otherwise hidden information may be kept forever. |
| 1687 | virtual void commit() { |
| 1688 | // Nothing to be done, this action is not doing anything. |
| 1689 | } |
| 1690 | }; |
| 1691 | |
| 1692 | /// \brief Utility to remember the position of an instruction. |
| 1693 | class InsertionHandler { |
| 1694 | /// Position of an instruction. |
| 1695 | /// Either an instruction: |
| 1696 | /// - Is the first in a basic block: BB is used. |
| 1697 | /// - Has a previous instructon: PrevInst is used. |
| 1698 | union { |
| 1699 | Instruction *PrevInst; |
| 1700 | BasicBlock *BB; |
| 1701 | } Point; |
| 1702 | /// Remember whether or not the instruction had a previous instruction. |
| 1703 | bool HasPrevInstruction; |
| 1704 | |
| 1705 | public: |
| 1706 | /// \brief Record the position of \p Inst. |
| 1707 | InsertionHandler(Instruction *Inst) { |
| 1708 | BasicBlock::iterator It = Inst; |
| 1709 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 1710 | if (HasPrevInstruction) |
| 1711 | Point.PrevInst = --It; |
| 1712 | else |
| 1713 | Point.BB = Inst->getParent(); |
| 1714 | } |
| 1715 | |
| 1716 | /// \brief Insert \p Inst at the recorded position. |
| 1717 | void insert(Instruction *Inst) { |
| 1718 | if (HasPrevInstruction) { |
| 1719 | if (Inst->getParent()) |
| 1720 | Inst->removeFromParent(); |
| 1721 | Inst->insertAfter(Point.PrevInst); |
| 1722 | } else { |
| 1723 | Instruction *Position = Point.BB->getFirstInsertionPt(); |
| 1724 | if (Inst->getParent()) |
| 1725 | Inst->moveBefore(Position); |
| 1726 | else |
| 1727 | Inst->insertBefore(Position); |
| 1728 | } |
| 1729 | } |
| 1730 | }; |
| 1731 | |
| 1732 | /// \brief Move an instruction before another. |
| 1733 | class InstructionMoveBefore : public TypePromotionAction { |
| 1734 | /// Original position of the instruction. |
| 1735 | InsertionHandler Position; |
| 1736 | |
| 1737 | public: |
| 1738 | /// \brief Move \p Inst before \p Before. |
| 1739 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 1740 | : TypePromotionAction(Inst), Position(Inst) { |
| 1741 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 1742 | Inst->moveBefore(Before); |
| 1743 | } |
| 1744 | |
| 1745 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1746 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1747 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 1748 | Position.insert(Inst); |
| 1749 | } |
| 1750 | }; |
| 1751 | |
| 1752 | /// \brief Set the operand of an instruction with a new value. |
| 1753 | class OperandSetter : public TypePromotionAction { |
| 1754 | /// Original operand of the instruction. |
| 1755 | Value *Origin; |
| 1756 | /// Index of the modified instruction. |
| 1757 | unsigned Idx; |
| 1758 | |
| 1759 | public: |
| 1760 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 1761 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 1762 | : TypePromotionAction(Inst), Idx(Idx) { |
| 1763 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 1764 | << "for:" << *Inst << "\n" |
| 1765 | << "with:" << *NewVal << "\n"); |
| 1766 | Origin = Inst->getOperand(Idx); |
| 1767 | Inst->setOperand(Idx, NewVal); |
| 1768 | } |
| 1769 | |
| 1770 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1771 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1772 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 1773 | << "for: " << *Inst << "\n" |
| 1774 | << "with: " << *Origin << "\n"); |
| 1775 | Inst->setOperand(Idx, Origin); |
| 1776 | } |
| 1777 | }; |
| 1778 | |
| 1779 | /// \brief Hide the operands of an instruction. |
| 1780 | /// Do as if this instruction was not using any of its operands. |
| 1781 | class OperandsHider : public TypePromotionAction { |
| 1782 | /// The list of original operands. |
| 1783 | SmallVector<Value *, 4> OriginalValues; |
| 1784 | |
| 1785 | public: |
| 1786 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 1787 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 1788 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 1789 | unsigned NumOpnds = Inst->getNumOperands(); |
| 1790 | OriginalValues.reserve(NumOpnds); |
| 1791 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 1792 | // Save the current operand. |
| 1793 | Value *Val = Inst->getOperand(It); |
| 1794 | OriginalValues.push_back(Val); |
| 1795 | // Set a dummy one. |
| 1796 | // We could use OperandSetter here, but that would implied an overhead |
| 1797 | // that we are not willing to pay. |
| 1798 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 1799 | } |
| 1800 | } |
| 1801 | |
| 1802 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1803 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1804 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 1805 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 1806 | Inst->setOperand(It, OriginalValues[It]); |
| 1807 | } |
| 1808 | }; |
| 1809 | |
| 1810 | /// \brief Build a truncate instruction. |
| 1811 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1812 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1813 | public: |
| 1814 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 1815 | /// result. |
| 1816 | /// trunc Opnd to Ty. |
| 1817 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 1818 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1819 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 1820 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1821 | } |
| 1822 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1823 | /// \brief Get the built value. |
| 1824 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1825 | |
| 1826 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1827 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1828 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 1829 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 1830 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1831 | } |
| 1832 | }; |
| 1833 | |
| 1834 | /// \brief Build a sign extension instruction. |
| 1835 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1836 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1837 | public: |
| 1838 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 1839 | /// result. |
| 1840 | /// sext Opnd to Ty. |
| 1841 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1842 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1843 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1844 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 1845 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1846 | } |
| 1847 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1848 | /// \brief Get the built value. |
| 1849 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1850 | |
| 1851 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1852 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1853 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 1854 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 1855 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1856 | } |
| 1857 | }; |
| 1858 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1859 | /// \brief Build a zero extension instruction. |
| 1860 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1861 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1862 | public: |
| 1863 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 1864 | /// result. |
| 1865 | /// zext Opnd to Ty. |
| 1866 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1867 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1868 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1869 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 1870 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1871 | } |
| 1872 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1873 | /// \brief Get the built value. |
| 1874 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1875 | |
| 1876 | /// \brief Remove the built instruction. |
| 1877 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1878 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 1879 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 1880 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1881 | } |
| 1882 | }; |
| 1883 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1884 | /// \brief Mutate an instruction to another type. |
| 1885 | class TypeMutator : public TypePromotionAction { |
| 1886 | /// Record the original type. |
| 1887 | Type *OrigTy; |
| 1888 | |
| 1889 | public: |
| 1890 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 1891 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 1892 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 1893 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 1894 | << "\n"); |
| 1895 | Inst->mutateType(NewTy); |
| 1896 | } |
| 1897 | |
| 1898 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1899 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1900 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 1901 | << "\n"); |
| 1902 | Inst->mutateType(OrigTy); |
| 1903 | } |
| 1904 | }; |
| 1905 | |
| 1906 | /// \brief Replace the uses of an instruction by another instruction. |
| 1907 | class UsesReplacer : public TypePromotionAction { |
| 1908 | /// Helper structure to keep track of the replaced uses. |
| 1909 | struct InstructionAndIdx { |
| 1910 | /// The instruction using the instruction. |
| 1911 | Instruction *Inst; |
| 1912 | /// The index where this instruction is used for Inst. |
| 1913 | unsigned Idx; |
| 1914 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 1915 | : Inst(Inst), Idx(Idx) {} |
| 1916 | }; |
| 1917 | |
| 1918 | /// Keep track of the original uses (pair Instruction, Index). |
| 1919 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 1920 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 1921 | |
| 1922 | public: |
| 1923 | /// \brief Replace all the use of \p Inst by \p New. |
| 1924 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 1925 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 1926 | << "\n"); |
| 1927 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1928 | for (Use &U : Inst->uses()) { |
| 1929 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 1930 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1931 | } |
| 1932 | // Now, we can replace the uses. |
| 1933 | Inst->replaceAllUsesWith(New); |
| 1934 | } |
| 1935 | |
| 1936 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1937 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1938 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 1939 | for (use_iterator UseIt = OriginalUses.begin(), |
| 1940 | EndIt = OriginalUses.end(); |
| 1941 | UseIt != EndIt; ++UseIt) { |
| 1942 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 1943 | } |
| 1944 | } |
| 1945 | }; |
| 1946 | |
| 1947 | /// \brief Remove an instruction from the IR. |
| 1948 | class InstructionRemover : public TypePromotionAction { |
| 1949 | /// Original position of the instruction. |
| 1950 | InsertionHandler Inserter; |
| 1951 | /// Helper structure to hide all the link to the instruction. In other |
| 1952 | /// words, this helps to do as if the instruction was removed. |
| 1953 | OperandsHider Hider; |
| 1954 | /// Keep track of the uses replaced, if any. |
| 1955 | UsesReplacer *Replacer; |
| 1956 | |
| 1957 | public: |
| 1958 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 1959 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1960 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 1961 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1962 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1963 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1964 | if (New) |
| 1965 | Replacer = new UsesReplacer(Inst, New); |
| 1966 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 1967 | Inst->removeFromParent(); |
| 1968 | } |
| 1969 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 1970 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1971 | |
| 1972 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1973 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1974 | |
| 1975 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 1976 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1977 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1978 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 1979 | Inserter.insert(Inst); |
| 1980 | if (Replacer) |
| 1981 | Replacer->undo(); |
| 1982 | Hider.undo(); |
| 1983 | } |
| 1984 | }; |
| 1985 | |
| 1986 | public: |
| 1987 | /// Restoration point. |
| 1988 | /// The restoration point is a pointer to an action instead of an iterator |
| 1989 | /// because the iterator may be invalidated but not the pointer. |
| 1990 | typedef const TypePromotionAction *ConstRestorationPt; |
| 1991 | /// Advocate every changes made in that transaction. |
| 1992 | void commit(); |
| 1993 | /// Undo all the changes made after the given point. |
| 1994 | void rollback(ConstRestorationPt Point); |
| 1995 | /// Get the current restoration point. |
| 1996 | ConstRestorationPt getRestorationPoint() const; |
| 1997 | |
| 1998 | /// \name API for IR modification with state keeping to support rollback. |
| 1999 | /// @{ |
| 2000 | /// Same as Instruction::setOperand. |
| 2001 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2002 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2003 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2004 | /// Same as Value::replaceAllUsesWith. |
| 2005 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2006 | /// Same as Value::mutateType. |
| 2007 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2008 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2009 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2010 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2011 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2012 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2013 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2014 | /// Same as Instruction::moveBefore. |
| 2015 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2016 | /// @} |
| 2017 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2018 | private: |
| 2019 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2020 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2021 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2022 | }; |
| 2023 | |
| 2024 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2025 | Value *NewVal) { |
| 2026 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2027 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2028 | } |
| 2029 | |
| 2030 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2031 | Value *NewVal) { |
| 2032 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2033 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2034 | } |
| 2035 | |
| 2036 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2037 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2038 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2039 | } |
| 2040 | |
| 2041 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2042 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2043 | } |
| 2044 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2045 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2046 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2047 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2048 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2049 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2050 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2051 | } |
| 2052 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2053 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2054 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2055 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2056 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2057 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2058 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2059 | } |
| 2060 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2061 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2062 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2063 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2064 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2065 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2066 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2067 | } |
| 2068 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2069 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2070 | Instruction *Before) { |
| 2071 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2072 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2073 | } |
| 2074 | |
| 2075 | TypePromotionTransaction::ConstRestorationPt |
| 2076 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2077 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2078 | } |
| 2079 | |
| 2080 | void TypePromotionTransaction::commit() { |
| 2081 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2082 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2083 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2084 | Actions.clear(); |
| 2085 | } |
| 2086 | |
| 2087 | void TypePromotionTransaction::rollback( |
| 2088 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2089 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2090 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2091 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2092 | } |
| 2093 | } |
| 2094 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2095 | /// \brief A helper class for matching addressing modes. |
| 2096 | /// |
| 2097 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2098 | class AddressingModeMatcher { |
| 2099 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2100 | const TargetMachine &TM; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2101 | const TargetLowering &TLI; |
| 2102 | |
| 2103 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2104 | /// the memory instruction that we're computing this address for. |
| 2105 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2106 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2107 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2108 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2109 | /// AddrMode - This is the addressing mode that we're building up. This is |
| 2110 | /// part of the return value of this addressing mode matching stuff. |
| 2111 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2112 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2113 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2114 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2115 | /// A map from the instructions to their type before promotion. |
| 2116 | InstrToOrigTy &PromotedInsts; |
| 2117 | /// The ongoing transaction where every action should be registered. |
| 2118 | TypePromotionTransaction &TPT; |
| 2119 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2120 | /// IgnoreProfitability - This is set to true when we should not do |
| 2121 | /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode |
| 2122 | /// always returns true. |
| 2123 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2124 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2125 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2126 | const TargetMachine &TM, Type *AT, unsigned AS, |
| 2127 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2128 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2129 | InstrToOrigTy &PromotedInsts, |
| 2130 | TypePromotionTransaction &TPT) |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2131 | : AddrModeInsts(AMI), TM(TM), |
| 2132 | TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent()) |
| 2133 | ->getTargetLowering()), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2134 | AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM), |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2135 | InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2136 | IgnoreProfitability = false; |
| 2137 | } |
| 2138 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2139 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2140 | /// Match - Find the maximal addressing mode that a load/store of V can fold, |
| 2141 | /// give an access type of AccessTy. This returns a list of involved |
| 2142 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2143 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2144 | /// optimizations. |
| 2145 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2146 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2147 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2148 | Instruction *MemoryInst, |
| 2149 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2150 | const TargetMachine &TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2151 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2152 | InstrToOrigTy &PromotedInsts, |
| 2153 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2154 | ExtAddrMode Result; |
| 2155 | |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2156 | bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2157 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2158 | PromotedInsts, TPT).MatchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2159 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2160 | return Result; |
| 2161 | } |
| 2162 | private: |
| 2163 | bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 2164 | bool MatchAddr(Value *V, unsigned Depth); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2165 | bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2166 | bool *MovedAway = nullptr); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2167 | bool IsProfitableToFoldIntoAddressingMode(Instruction *I, |
| 2168 | ExtAddrMode &AMBefore, |
| 2169 | ExtAddrMode &AMAfter); |
| 2170 | bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2171 | bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2172 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2173 | }; |
| 2174 | |
| 2175 | /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode. |
| 2176 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 2177 | /// false if not. |
| 2178 | bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale, |
| 2179 | unsigned Depth) { |
| 2180 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 2181 | // mode. Just process that directly. |
| 2182 | if (Scale == 1) |
| 2183 | return MatchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2184 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2185 | // If the scale is 0, it takes nothing to add this. |
| 2186 | if (Scale == 0) |
| 2187 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2188 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2189 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 2190 | // need an available scale field. |
| 2191 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 2192 | return false; |
| 2193 | |
| 2194 | ExtAddrMode TestAddrMode = AddrMode; |
| 2195 | |
| 2196 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 2197 | // [A+B + A*7] -> [B+A*8]. |
| 2198 | TestAddrMode.Scale += Scale; |
| 2199 | TestAddrMode.ScaledReg = ScaleReg; |
| 2200 | |
| 2201 | // If the new address isn't legal, bail out. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2202 | if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2203 | return false; |
| 2204 | |
| 2205 | // It was legal, so commit it. |
| 2206 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2207 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2208 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 2209 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 2210 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2211 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2212 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 2213 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 2214 | TestAddrMode.ScaledReg = AddLHS; |
| 2215 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2216 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2217 | // If this addressing mode is legal, commit it and remember that we folded |
| 2218 | // this instruction. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2219 | if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2220 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 2221 | AddrMode = TestAddrMode; |
| 2222 | return true; |
| 2223 | } |
| 2224 | } |
| 2225 | |
| 2226 | // Otherwise, not (x+c)*scale, just return what we have. |
| 2227 | return true; |
| 2228 | } |
| 2229 | |
| 2230 | /// MightBeFoldableInst - This is a little filter, which returns true if an |
| 2231 | /// addressing computation involving I might be folded into a load/store |
| 2232 | /// accessing it. This doesn't need to be perfect, but needs to accept at least |
| 2233 | /// the set of instructions that MatchOperationAddr can. |
| 2234 | static bool MightBeFoldableInst(Instruction *I) { |
| 2235 | switch (I->getOpcode()) { |
| 2236 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 2237 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2238 | // Don't touch identity bitcasts. |
| 2239 | if (I->getType() == I->getOperand(0)->getType()) |
| 2240 | return false; |
| 2241 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 2242 | case Instruction::PtrToInt: |
| 2243 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2244 | return true; |
| 2245 | case Instruction::IntToPtr: |
| 2246 | // We know the input is intptr_t, so this is foldable. |
| 2247 | return true; |
| 2248 | case Instruction::Add: |
| 2249 | return true; |
| 2250 | case Instruction::Mul: |
| 2251 | case Instruction::Shl: |
| 2252 | // Can only handle X*C and X << C. |
| 2253 | return isa<ConstantInt>(I->getOperand(1)); |
| 2254 | case Instruction::GetElementPtr: |
| 2255 | return true; |
| 2256 | default: |
| 2257 | return false; |
| 2258 | } |
| 2259 | } |
| 2260 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2261 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 2262 | /// \note \p Val is assumed to be the product of some type promotion. |
| 2263 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 2264 | /// to be legal, as the non-promoted value would have had the same state. |
| 2265 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) { |
| 2266 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 2267 | if (!PromotedInst) |
| 2268 | return false; |
| 2269 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 2270 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 2271 | if (!ISDOpcode) |
| 2272 | return true; |
| 2273 | // Otherwise, check if the promoted instruction is legal or not. |
| 2274 | return TLI.isOperationLegalOrCustom( |
| 2275 | ISDOpcode, TLI.getValueType(PromotedInst->getType())); |
| 2276 | } |
| 2277 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2278 | /// \brief Hepler class to perform type promotion. |
| 2279 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2280 | /// \brief Utility function to check whether or not a sign or zero extension |
| 2281 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 2282 | /// either using the operands of \p Inst or promoting \p Inst. |
| 2283 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2284 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2285 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2286 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2287 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2288 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2289 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2290 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2291 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 2292 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2293 | |
| 2294 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 2295 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2296 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2297 | if (isa<SelectInst>(Inst) && OpIdx == 0) |
| 2298 | return false; |
| 2299 | return true; |
| 2300 | } |
| 2301 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2302 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2303 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2304 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2305 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2306 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2307 | /// Newly added extensions are inserted in \p Exts. |
| 2308 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2309 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2310 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2311 | static Value *promoteOperandForTruncAndAnyExt( |
| 2312 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2313 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2314 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2315 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2316 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2317 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2318 | /// operand is promotable and is not a supported trunc or sext. |
| 2319 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2320 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2321 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2322 | /// Newly added extensions are inserted in \p Exts. |
| 2323 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2324 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2325 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2326 | static Value *promoteOperandForOther(Instruction *Ext, |
| 2327 | TypePromotionTransaction &TPT, |
| 2328 | InstrToOrigTy &PromotedInsts, |
| 2329 | unsigned &CreatedInstsCost, |
| 2330 | SmallVectorImpl<Instruction *> *Exts, |
| 2331 | SmallVectorImpl<Instruction *> *Truncs, |
| 2332 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2333 | |
| 2334 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2335 | static Value *signExtendOperandForOther( |
| 2336 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2337 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2338 | SmallVectorImpl<Instruction *> *Exts, |
| 2339 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2340 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2341 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2342 | } |
| 2343 | |
| 2344 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2345 | static Value *zeroExtendOperandForOther( |
| 2346 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2347 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2348 | SmallVectorImpl<Instruction *> *Exts, |
| 2349 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2350 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2351 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2352 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2353 | |
| 2354 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2355 | /// Type for the utility function that promotes the operand of Ext. |
| 2356 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2357 | InstrToOrigTy &PromotedInsts, |
| 2358 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2359 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2360 | SmallVectorImpl<Instruction *> *Truncs, |
| 2361 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2362 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 2363 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2364 | /// \return NULL if no promotable action is possible with the current |
| 2365 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2366 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 2367 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2368 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 2369 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 2370 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2371 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2372 | const TargetLowering &TLI, |
| 2373 | const InstrToOrigTy &PromotedInsts); |
| 2374 | }; |
| 2375 | |
| 2376 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2377 | Type *ConsideredExtType, |
| 2378 | const InstrToOrigTy &PromotedInsts, |
| 2379 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2380 | // The promotion helper does not know how to deal with vector types yet. |
| 2381 | // To be able to fix that, we would need to fix the places where we |
| 2382 | // statically extend, e.g., constants and such. |
| 2383 | if (Inst->getType()->isVectorTy()) |
| 2384 | return false; |
| 2385 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2386 | // We can always get through zext. |
| 2387 | if (isa<ZExtInst>(Inst)) |
| 2388 | return true; |
| 2389 | |
| 2390 | // sext(sext) is ok too. |
| 2391 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2392 | return true; |
| 2393 | |
| 2394 | // We can get through binary operator, if it is legal. In other words, the |
| 2395 | // binary operator must have a nuw or nsw flag. |
| 2396 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 2397 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2398 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 2399 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2400 | return true; |
| 2401 | |
| 2402 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2403 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2404 | if (!isa<TruncInst>(Inst)) |
| 2405 | return false; |
| 2406 | |
| 2407 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2408 | // Check if we can use this operand in the extension. |
| 2409 | // If the type is larger than the result type of the extension, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2410 | // we cannot. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2411 | if (!OpndVal->getType()->isIntegerTy() || |
| 2412 | OpndVal->getType()->getIntegerBitWidth() > |
| 2413 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2414 | return false; |
| 2415 | |
| 2416 | // If the operand of the truncate is not an instruction, we will not have |
| 2417 | // any information on the dropped bits. |
| 2418 | // (Actually we could for constant but it is not worth the extra logic). |
| 2419 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 2420 | if (!Opnd) |
| 2421 | return false; |
| 2422 | |
| 2423 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2424 | // I.e., check that trunc just drops extended bits of the same kind of |
| 2425 | // the extension. |
| 2426 | // #1 get the type of the operand and check the kind of the extended bits. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2427 | const Type *OpndType; |
| 2428 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2429 | if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt) |
| 2430 | OpndType = It->second.Ty; |
| 2431 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 2432 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2433 | else |
| 2434 | return false; |
| 2435 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2436 | // #2 check that the truncate just drop extended bits. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2437 | if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth()) |
| 2438 | return true; |
| 2439 | |
| 2440 | return false; |
| 2441 | } |
| 2442 | |
| 2443 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2444 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2445 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2446 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 2447 | "Unexpected instruction type"); |
| 2448 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 2449 | Type *ExtTy = Ext->getType(); |
| 2450 | bool IsSExt = isa<SExtInst>(Ext); |
| 2451 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2452 | // get through. |
| 2453 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2454 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2455 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2456 | |
| 2457 | // Do not promote if the operand has been added by codegenprepare. |
| 2458 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 2459 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2460 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2461 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2462 | |
| 2463 | // SExt or Trunc instructions. |
| 2464 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2465 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 2466 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2467 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2468 | |
| 2469 | // Regular instruction. |
| 2470 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2471 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2472 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2473 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2474 | } |
| 2475 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2476 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2477 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2478 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2479 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2480 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2481 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 2482 | // get through it and this method should not be called. |
| 2483 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2484 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2485 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2486 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2487 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2488 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2489 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2490 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2491 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 2492 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 2493 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2494 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2495 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2496 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 2497 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2498 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 2499 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2500 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2501 | |
| 2502 | // Remove dead code. |
| 2503 | if (SExtOpnd->use_empty()) |
| 2504 | TPT.eraseInstruction(SExtOpnd); |
| 2505 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2506 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2507 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2508 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2509 | if (ExtInst) { |
| 2510 | if (Exts) |
| 2511 | Exts->push_back(ExtInst); |
| 2512 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 2513 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2514 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2515 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2516 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2517 | // At this point we have: ext ty opnd to ty. |
| 2518 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 2519 | Value *NextVal = ExtInst->getOperand(0); |
| 2520 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2521 | return NextVal; |
| 2522 | } |
| 2523 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2524 | Value *TypePromotionHelper::promoteOperandForOther( |
| 2525 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2526 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2527 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2528 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 2529 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2530 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2531 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2532 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2533 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2534 | if (!ExtOpnd->hasOneUse()) { |
| 2535 | // ExtOpnd will be promoted. |
| 2536 | // All its uses, but Ext, will need to use a truncated value of the |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2537 | // promoted version. |
| 2538 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2539 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2540 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 2541 | ITrunc->removeFromParent(); |
| 2542 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2543 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2544 | if (Truncs) |
| 2545 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2546 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2547 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2548 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
| 2549 | // Restore the operand of Ext (which has been replace by the previous call |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2550 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2551 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2552 | } |
| 2553 | |
| 2554 | // Get through the Instruction: |
| 2555 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2556 | // 2. Replace the uses of Ext by Inst. |
| 2557 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2558 | |
| 2559 | // Remember the original type of the instruction before promotion. |
| 2560 | // This is useful to know that the high bits are sign extended bits. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2561 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 2562 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2563 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2564 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2565 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2566 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2567 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2568 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2569 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2570 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 2571 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2572 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2573 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 2574 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 2575 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2576 | DEBUG(dbgs() << "No need to propagate\n"); |
| 2577 | continue; |
| 2578 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2579 | // Check if we can statically extend the operand. |
| 2580 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2581 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2582 | DEBUG(dbgs() << "Statically extend\n"); |
| 2583 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 2584 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 2585 | : Cst->getValue().zext(BitWidth); |
| 2586 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2587 | continue; |
| 2588 | } |
| 2589 | // UndefValue are typed, so we have to statically sign extend them. |
| 2590 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2591 | DEBUG(dbgs() << "Statically extend\n"); |
| 2592 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2593 | continue; |
| 2594 | } |
| 2595 | |
| 2596 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2597 | // Check if Ext was reused to extend an operand. |
| 2598 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2599 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2600 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 2601 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 2602 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 2603 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 2604 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 2605 | continue; |
| 2606 | } |
| 2607 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2608 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2609 | if (Exts) |
| 2610 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2611 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2612 | |
| 2613 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2614 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 2615 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2616 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2617 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2618 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2619 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2620 | if (ExtForOpnd == Ext) { |
| 2621 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 2622 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2623 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2624 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2625 | } |
| 2626 | |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2627 | /// IsPromotionProfitable - Check whether or not promoting an instruction |
| 2628 | /// to a wider type was profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2629 | /// \p NewCost gives the cost of extension instructions created by the |
| 2630 | /// promotion. |
| 2631 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 2632 | /// plus the number of instructions that have been |
| 2633 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2634 | /// \p PromotedOperand is the value that has been promoted. |
| 2635 | /// \return True if the promotion is profitable, false otherwise. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2636 | bool AddressingModeMatcher::IsPromotionProfitable( |
| 2637 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 2638 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 2639 | // The cost of the new extensions is greater than the cost of the |
| 2640 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2641 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2642 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2643 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2644 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2645 | return true; |
| 2646 | // The promotion is neutral but it may help folding the sign extension in |
| 2647 | // loads for instance. |
| 2648 | // Check that we did not create an illegal instruction. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2649 | return isPromotedInstructionLegal(TLI, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2650 | } |
| 2651 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2652 | /// MatchOperationAddr - Given an instruction or constant expr, see if we can |
| 2653 | /// fold the operation into the addressing mode. If so, update the addressing |
| 2654 | /// mode and return true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2655 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 2656 | /// not AddrInst has to be folded into the addressing mode on success. |
| 2657 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 2658 | /// because it has been moved away. |
| 2659 | /// Thus AddrInst must not be added in the matched instructions. |
| 2660 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 2661 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 2662 | /// not be referenced anymore. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2663 | bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2664 | unsigned Depth, |
| 2665 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2666 | // Avoid exponential behavior on extremely deep expression trees. |
| 2667 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2668 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2669 | // By default, all matched instructions stay in place. |
| 2670 | if (MovedAway) |
| 2671 | *MovedAway = false; |
| 2672 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2673 | switch (Opcode) { |
| 2674 | case Instruction::PtrToInt: |
| 2675 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2676 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2677 | case Instruction::IntToPtr: |
| 2678 | // This inttoptr is a no-op if the integer type is pointer sized. |
| 2679 | if (TLI.getValueType(AddrInst->getOperand(0)->getType()) == |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 2680 | TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace())) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2681 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2682 | return false; |
| 2683 | case Instruction::BitCast: |
| 2684 | // BitCast is always a noop, and we can handle it as long as it is |
| 2685 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 2686 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 2687 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 2688 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 2689 | // and we don't want to mess around with them. Assume it knows what it |
| 2690 | // is doing. |
| 2691 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
| 2692 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2693 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 2694 | case Instruction::AddrSpaceCast: { |
| 2695 | unsigned SrcAS |
| 2696 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 2697 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 2698 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
| 2699 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2700 | return false; |
| 2701 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2702 | case Instruction::Add: { |
| 2703 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 2704 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2705 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2706 | // Start a transaction at this point. |
| 2707 | // The LHS may match but not the RHS. |
| 2708 | // Therefore, we need a higher level restoration point to undo partially |
| 2709 | // matched operation. |
| 2710 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2711 | TPT.getRestorationPoint(); |
| 2712 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2713 | if (MatchAddr(AddrInst->getOperand(1), Depth+1) && |
| 2714 | MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2715 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2716 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2717 | // Restore the old addr mode info. |
| 2718 | AddrMode = BackupAddrMode; |
| 2719 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2720 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2721 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2722 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. |
| 2723 | if (MatchAddr(AddrInst->getOperand(0), Depth+1) && |
| 2724 | MatchAddr(AddrInst->getOperand(1), Depth+1)) |
| 2725 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2726 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2727 | // Otherwise we definitely can't merge the ADD in. |
| 2728 | AddrMode = BackupAddrMode; |
| 2729 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2730 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2731 | break; |
| 2732 | } |
| 2733 | //case Instruction::Or: |
| 2734 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 2735 | //break; |
| 2736 | case Instruction::Mul: |
| 2737 | case Instruction::Shl: { |
| 2738 | // Can only handle X*C and X << C. |
| 2739 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2740 | if (!RHS) |
| 2741 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2742 | int64_t Scale = RHS->getSExtValue(); |
| 2743 | if (Opcode == Instruction::Shl) |
| 2744 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2745 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2746 | return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
| 2747 | } |
| 2748 | case Instruction::GetElementPtr: { |
| 2749 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 2750 | // one variable offset. |
| 2751 | int VariableOperand = -1; |
| 2752 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2753 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2754 | int64_t ConstantOffset = 0; |
| 2755 | const DataLayout *TD = TLI.getDataLayout(); |
| 2756 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 2757 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
| 2758 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 2759 | const StructLayout *SL = TD->getStructLayout(STy); |
| 2760 | unsigned Idx = |
| 2761 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 2762 | ConstantOffset += SL->getElementOffset(Idx); |
| 2763 | } else { |
| 2764 | uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType()); |
| 2765 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 2766 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 2767 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 2768 | // We only allow one variable index at the moment. |
| 2769 | if (VariableOperand != -1) |
| 2770 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2771 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2772 | // Remember the variable index. |
| 2773 | VariableOperand = i; |
| 2774 | VariableScale = TypeSize; |
| 2775 | } |
| 2776 | } |
| 2777 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2778 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2779 | // A common case is for the GEP to only do a constant offset. In this case, |
| 2780 | // just add it to the disp field and check validity. |
| 2781 | if (VariableOperand == -1) { |
| 2782 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2783 | if (ConstantOffset == 0 || |
| 2784 | TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2785 | // Check to see if we can fold the base pointer in too. |
| 2786 | if (MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2787 | return true; |
| 2788 | } |
| 2789 | AddrMode.BaseOffs -= ConstantOffset; |
| 2790 | return false; |
| 2791 | } |
| 2792 | |
| 2793 | // Save the valid addressing mode in case we can't match. |
| 2794 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2795 | unsigned OldSize = AddrModeInsts.size(); |
| 2796 | |
| 2797 | // See if the scale and offset amount is valid for this target. |
| 2798 | AddrMode.BaseOffs += ConstantOffset; |
| 2799 | |
| 2800 | // Match the base operand of the GEP. |
| 2801 | if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) { |
| 2802 | // If it couldn't be matched, just stuff the value in a register. |
| 2803 | if (AddrMode.HasBaseReg) { |
| 2804 | AddrMode = BackupAddrMode; |
| 2805 | AddrModeInsts.resize(OldSize); |
| 2806 | return false; |
| 2807 | } |
| 2808 | AddrMode.HasBaseReg = true; |
| 2809 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2810 | } |
| 2811 | |
| 2812 | // Match the remaining variable portion of the GEP. |
| 2813 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
| 2814 | Depth)) { |
| 2815 | // If it couldn't be matched, try stuffing the base into a register |
| 2816 | // instead of matching it, and retrying the match of the scale. |
| 2817 | AddrMode = BackupAddrMode; |
| 2818 | AddrModeInsts.resize(OldSize); |
| 2819 | if (AddrMode.HasBaseReg) |
| 2820 | return false; |
| 2821 | AddrMode.HasBaseReg = true; |
| 2822 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2823 | AddrMode.BaseOffs += ConstantOffset; |
| 2824 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), |
| 2825 | VariableScale, Depth)) { |
| 2826 | // If even that didn't work, bail. |
| 2827 | AddrMode = BackupAddrMode; |
| 2828 | AddrModeInsts.resize(OldSize); |
| 2829 | return false; |
| 2830 | } |
| 2831 | } |
| 2832 | |
| 2833 | return true; |
| 2834 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2835 | case Instruction::SExt: |
| 2836 | case Instruction::ZExt: { |
| 2837 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 2838 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2839 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 2840 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2841 | // Try to move this ext out of the way of the addressing mode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2842 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2843 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2844 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2845 | if (!TPH) |
| 2846 | return false; |
| 2847 | |
| 2848 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2849 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2850 | unsigned CreatedInstsCost = 0; |
| 2851 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2852 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2853 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2854 | // SExt has been moved away. |
| 2855 | // Thus either it will be rematched later in the recursive calls or it is |
| 2856 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 2857 | // E.g., |
| 2858 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2859 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2860 | // addr = gep base, idx |
| 2861 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2862 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2863 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 2864 | // addr = gep base, op <- match |
| 2865 | if (MovedAway) |
| 2866 | *MovedAway = true; |
| 2867 | |
| 2868 | assert(PromotedOperand && |
| 2869 | "TypePromotionHelper should have filtered out those cases"); |
| 2870 | |
| 2871 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2872 | unsigned OldSize = AddrModeInsts.size(); |
| 2873 | |
| 2874 | if (!MatchAddr(PromotedOperand, Depth) || |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2875 | // The total of the new cost is equals to the cost of the created |
| 2876 | // instructions. |
| 2877 | // The total of the old cost is equals to the cost of the extension plus |
| 2878 | // what we have saved in the addressing mode. |
| 2879 | !IsPromotionProfitable(CreatedInstsCost, |
| 2880 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2881 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2882 | AddrMode = BackupAddrMode; |
| 2883 | AddrModeInsts.resize(OldSize); |
| 2884 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 2885 | TPT.rollback(LastKnownGood); |
| 2886 | return false; |
| 2887 | } |
| 2888 | return true; |
| 2889 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2890 | } |
| 2891 | return false; |
| 2892 | } |
| 2893 | |
| 2894 | /// MatchAddr - If we can, try to add the value of 'Addr' into the current |
| 2895 | /// addressing mode. If Addr can't be added to AddrMode this returns false and |
| 2896 | /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type |
| 2897 | /// or intptr_t for the target. |
| 2898 | /// |
| 2899 | bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2900 | // Start a transaction at this point that we will rollback if the matching |
| 2901 | // fails. |
| 2902 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2903 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2904 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 2905 | // Fold in immediates if legal for the target. |
| 2906 | AddrMode.BaseOffs += CI->getSExtValue(); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2907 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2908 | return true; |
| 2909 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 2910 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 2911 | // If this is a global variable, try to fold it into the addressing mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2912 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2913 | AddrMode.BaseGV = GV; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2914 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2915 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2916 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2917 | } |
| 2918 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 2919 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2920 | unsigned OldSize = AddrModeInsts.size(); |
| 2921 | |
| 2922 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2923 | bool MovedAway = false; |
| 2924 | if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
| 2925 | // This instruction may have been move away. If so, there is nothing |
| 2926 | // to check here. |
| 2927 | if (MovedAway) |
| 2928 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2929 | // Okay, it's possible to fold this. Check to see if it is actually |
| 2930 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 2931 | // register pressure too much. |
| 2932 | if (I->hasOneUse() || |
| 2933 | IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
| 2934 | AddrModeInsts.push_back(I); |
| 2935 | return true; |
| 2936 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2937 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2938 | // It isn't profitable to do this, roll back. |
| 2939 | //cerr << "NOT FOLDING: " << *I; |
| 2940 | AddrMode = BackupAddrMode; |
| 2941 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2942 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2943 | } |
| 2944 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
| 2945 | if (MatchOperationAddr(CE, CE->getOpcode(), Depth)) |
| 2946 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2947 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2948 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 2949 | // Null pointer gets folded without affecting the addressing mode. |
| 2950 | return true; |
| 2951 | } |
| 2952 | |
| 2953 | // Worse case, the target should support [reg] addressing modes. :) |
| 2954 | if (!AddrMode.HasBaseReg) { |
| 2955 | AddrMode.HasBaseReg = true; |
| 2956 | AddrMode.BaseReg = Addr; |
| 2957 | // Still check for legality in case the target supports [imm] but not [i+r]. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2958 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2959 | return true; |
| 2960 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2961 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2962 | } |
| 2963 | |
| 2964 | // If the base register is already taken, see if we can do [r+r]. |
| 2965 | if (AddrMode.Scale == 0) { |
| 2966 | AddrMode.Scale = 1; |
| 2967 | AddrMode.ScaledReg = Addr; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2968 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2969 | return true; |
| 2970 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2971 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2972 | } |
| 2973 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2974 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2975 | return false; |
| 2976 | } |
| 2977 | |
| 2978 | /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified |
| 2979 | /// inline asm call are due to memory operands. If so, return true, otherwise |
| 2980 | /// return false. |
| 2981 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 2982 | const TargetMachine &TM) { |
| 2983 | const Function *F = CI->getParent()->getParent(); |
| 2984 | const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering(); |
| 2985 | const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2986 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 2987 | TLI->ParseConstraints(TRI, ImmutableCallSite(CI)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2988 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 2989 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2990 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2991 | // Compute the constraint code and ConstraintType to use. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 2992 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2993 | |
| 2994 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 2995 | // operand, we can't fold it! |
| 2996 | if (OpInfo.CallOperandVal == OpVal && |
| 2997 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 2998 | !OpInfo.isIndirect)) |
| 2999 | return false; |
| 3000 | } |
| 3001 | |
| 3002 | return true; |
| 3003 | } |
| 3004 | |
| 3005 | /// FindAllMemoryUses - Recursively walk all the uses of I until we find a |
| 3006 | /// memory use. If we find an obviously non-foldable instruction, return true. |
| 3007 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3008 | static bool FindAllMemoryUses( |
| 3009 | Instruction *I, |
| 3010 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
| 3011 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3012 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3013 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3014 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3015 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3016 | // If this is an obviously unfoldable instruction, bail out. |
| 3017 | if (!MightBeFoldableInst(I)) |
| 3018 | return true; |
| 3019 | |
| 3020 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3021 | for (Use &U : I->uses()) { |
| 3022 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3023 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3024 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3025 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3026 | continue; |
| 3027 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3028 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3029 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3030 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3031 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 3032 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3033 | continue; |
| 3034 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3035 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3036 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3037 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 3038 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3039 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3040 | // If this is a memory operand, we're cool, otherwise bail out. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3041 | if (!IsOperandAMemoryOperand(CI, IA, I, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3042 | return true; |
| 3043 | continue; |
| 3044 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3045 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3046 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3047 | return true; |
| 3048 | } |
| 3049 | |
| 3050 | return false; |
| 3051 | } |
| 3052 | |
| 3053 | /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at |
| 3054 | /// the use site that we're folding it into. If so, there is no cost to |
| 3055 | /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values |
| 3056 | /// that we know are live at the instruction already. |
| 3057 | bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
| 3058 | Value *KnownLive2) { |
| 3059 | // If Val is either of the known-live values, we know it is live! |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3060 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3061 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3062 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3063 | // All values other than instructions and arguments (e.g. constants) are live. |
| 3064 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3065 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3066 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 3067 | // true because it is just a reference to the stack/frame pointer, which is |
| 3068 | // live for the whole function. |
| 3069 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 3070 | if (AI->isStaticAlloca()) |
| 3071 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3072 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3073 | // Check to see if this value is already used in the memory instruction's |
| 3074 | // block. If so, it's already live into the block at the very least, so we |
| 3075 | // can reasonably fold it. |
| 3076 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 3077 | } |
| 3078 | |
| 3079 | /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing |
| 3080 | /// mode of the machine to fold the specified instruction into a load or store |
| 3081 | /// that ultimately uses it. However, the specified instruction has multiple |
| 3082 | /// uses. Given this, it may actually increase register pressure to fold it |
| 3083 | /// into the load. For example, consider this code: |
| 3084 | /// |
| 3085 | /// X = ... |
| 3086 | /// Y = X+1 |
| 3087 | /// use(Y) -> nonload/store |
| 3088 | /// Z = Y+1 |
| 3089 | /// load Z |
| 3090 | /// |
| 3091 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 3092 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 3093 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 3094 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 3095 | /// number of computations either. |
| 3096 | /// |
| 3097 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 3098 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 3099 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 3100 | bool AddressingModeMatcher:: |
| 3101 | IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
| 3102 | ExtAddrMode &AMAfter) { |
| 3103 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3104 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3105 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 3106 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 3107 | // the set of registers referenced by AMAfter and subtract out those |
| 3108 | // referenced by AMBefore: this is the set of values which folding in this |
| 3109 | // address extends the lifetime of. |
| 3110 | // |
| 3111 | // Note that there are only two potential values being referenced here, |
| 3112 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 3113 | // folded immediates). |
| 3114 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3115 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3116 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 3117 | // lifetime wasn't extended by adding this instruction. |
| 3118 | if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3119 | BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3120 | if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3121 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3122 | |
| 3123 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 3124 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3125 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3126 | return true; |
| 3127 | |
| 3128 | // If all uses of this instruction are ultimately load/store/inlineasm's, |
| 3129 | // check to see if their addressing modes will include this instruction. If |
| 3130 | // so, we can fold it into all uses, so it doesn't matter if it has multiple |
| 3131 | // uses. |
| 3132 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 3133 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3134 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3135 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3136 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3137 | // Now that we know that all uses of this instruction are part of a chain of |
| 3138 | // computation involving only operations that could theoretically be folded |
| 3139 | // into a memory use, loop over each of these uses and see if they could |
| 3140 | // *actually* fold the instruction. |
| 3141 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 3142 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 3143 | Instruction *User = MemoryUses[i].first; |
| 3144 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3145 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3146 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 3147 | // know what it accesses. |
| 3148 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3149 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 3150 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3151 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3152 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 3153 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3154 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3155 | // Do a match against the root of this address, ignoring profitability. This |
| 3156 | // will tell us if the addressing mode for the memory operation will |
| 3157 | // *actually* cover the shared instruction. |
| 3158 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3159 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3160 | TPT.getRestorationPoint(); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3161 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3162 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3163 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3164 | Matcher.IgnoreProfitability = true; |
| 3165 | bool Success = Matcher.MatchAddr(Address, 0); |
| 3166 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3167 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3168 | // The match was to check the profitability, the changes made are not |
| 3169 | // part of the original matcher. Therefore, they should be dropped |
| 3170 | // otherwise the original matcher will not present the right state. |
| 3171 | TPT.rollback(LastKnownGood); |
| 3172 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3173 | // If the match didn't cover I, then it won't be shared by it. |
| 3174 | if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(), |
| 3175 | I) == MatchedAddrModeInsts.end()) |
| 3176 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3177 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3178 | MatchedAddrModeInsts.clear(); |
| 3179 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3180 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3181 | return true; |
| 3182 | } |
| 3183 | |
| 3184 | } // end anonymous namespace |
| 3185 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3186 | /// IsNonLocalValue - Return true if the specified values are defined in a |
| 3187 | /// different basic block than BB. |
| 3188 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 3189 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 3190 | return I->getParent() != BB; |
| 3191 | return false; |
| 3192 | } |
| 3193 | |
Bob Wilson | 53bdae3 | 2009-12-03 21:47:07 +0000 | [diff] [blame] | 3194 | /// OptimizeMemoryInst - Load and Store Instructions often have |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3195 | /// addressing modes that can do significant amounts of computation. As such, |
| 3196 | /// instruction selection will try to get the load or store to do as much |
| 3197 | /// computation as possible for the program. The problem is that isel can only |
| 3198 | /// see within a single block. As such, we sink as much legal addressing mode |
| 3199 | /// stuff into the block as possible. |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 3200 | /// |
| 3201 | /// This method is used to optimize both load/store and inline asms with memory |
| 3202 | /// operands. |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 3203 | bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3204 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3205 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3206 | |
| 3207 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3208 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 3209 | SmallVector<Value*, 8> worklist; |
| 3210 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3211 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3212 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3213 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 3214 | // the addressing mode obtained from the non-PHI roots of the graph |
| 3215 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3216 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3217 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3218 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3219 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 3220 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3221 | TypePromotionTransaction TPT; |
| 3222 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3223 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3224 | while (!worklist.empty()) { |
| 3225 | Value *V = worklist.back(); |
| 3226 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3227 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3228 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3229 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3230 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3231 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3232 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3233 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3234 | // For a PHI node, push all of its incoming values. |
| 3235 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 3236 | for (Value *IncValue : P->incoming_values()) |
| 3237 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3238 | continue; |
| 3239 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3240 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3241 | // For non-PHIs, determine the addressing mode being computed. |
| 3242 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3243 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3244 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3245 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3246 | |
| 3247 | // This check is broken into two cases with very similar code to avoid using |
| 3248 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 3249 | // calling getNumUses() unconditionally caused a significant compile-time |
| 3250 | // regression. |
| 3251 | if (!Consensus) { |
| 3252 | Consensus = V; |
| 3253 | AddrMode = NewAddrMode; |
| 3254 | AddrModeInsts = NewAddrModeInsts; |
| 3255 | continue; |
| 3256 | } else if (NewAddrMode == AddrMode) { |
| 3257 | if (!IsNumUsesConsensusValid) { |
| 3258 | NumUsesConsensus = Consensus->getNumUses(); |
| 3259 | IsNumUsesConsensusValid = true; |
| 3260 | } |
| 3261 | |
| 3262 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 3263 | // for all other roots of the PHI traversal. Also, when choosing one |
| 3264 | // such root as representative, select the one with the most uses in order |
| 3265 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 3266 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3267 | unsigned NumUses = V->getNumUses(); |
| 3268 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3269 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3270 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3271 | AddrModeInsts = NewAddrModeInsts; |
| 3272 | } |
| 3273 | continue; |
| 3274 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3275 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3276 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3277 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3278 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3279 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3280 | // If the addressing mode couldn't be determined, or if multiple different |
| 3281 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3282 | if (!Consensus) { |
| 3283 | TPT.rollback(LastKnownGood); |
| 3284 | return false; |
| 3285 | } |
| 3286 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3287 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3288 | // Check to see if any of the instructions supersumed by this addr mode are |
| 3289 | // non-local to I's BB. |
| 3290 | bool AnyNonLocal = false; |
| 3291 | for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) { |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 3292 | if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) { |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3293 | AnyNonLocal = true; |
| 3294 | break; |
| 3295 | } |
| 3296 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3297 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3298 | // If all the instructions matched are already in this BB, don't do anything. |
| 3299 | if (!AnyNonLocal) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3300 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3301 | return false; |
| 3302 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3303 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3304 | // Insert this computation right after this user. Since our caller is |
| 3305 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 3306 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3307 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3308 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3309 | // Now that we determined the addressing expression we want to use and know |
| 3310 | // that we have to sink it into this block. Check to see if we have already |
| 3311 | // done this for some other load/store instr in this block. If so, reuse the |
| 3312 | // computation. |
| 3313 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 3314 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3315 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3316 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3317 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 3318 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 3319 | } else if (AddrSinkUsingGEPs || |
| 3320 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Eric Christopher | 2c63549 | 2015-01-27 07:54:39 +0000 | [diff] [blame] | 3321 | TM->getSubtargetImpl(*MemoryInst->getParent()->getParent()) |
| 3322 | ->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3323 | // By default, we use the GEP-based method when AA is used later. This |
| 3324 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 3325 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3326 | << *MemoryInst << "\n"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3327 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3328 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3329 | |
| 3330 | // First, find the pointer. |
| 3331 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 3332 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3333 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3334 | } |
| 3335 | |
| 3336 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 3337 | // We can't add more than one pointer together, nor can we scale a |
| 3338 | // pointer (both of which seem meaningless). |
| 3339 | if (ResultPtr || AddrMode.Scale != 1) |
| 3340 | return false; |
| 3341 | |
| 3342 | ResultPtr = AddrMode.ScaledReg; |
| 3343 | AddrMode.Scale = 0; |
| 3344 | } |
| 3345 | |
| 3346 | if (AddrMode.BaseGV) { |
| 3347 | if (ResultPtr) |
| 3348 | return false; |
| 3349 | |
| 3350 | ResultPtr = AddrMode.BaseGV; |
| 3351 | } |
| 3352 | |
| 3353 | // If the real base value actually came from an inttoptr, then the matcher |
| 3354 | // will look through it and provide only the integer value. In that case, |
| 3355 | // use it here. |
| 3356 | if (!ResultPtr && AddrMode.BaseReg) { |
| 3357 | ResultPtr = |
| 3358 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3359 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3360 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 3361 | ResultPtr = |
| 3362 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 3363 | AddrMode.Scale = 0; |
| 3364 | } |
| 3365 | |
| 3366 | if (!ResultPtr && |
| 3367 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 3368 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 3369 | } else if (!ResultPtr) { |
| 3370 | return false; |
| 3371 | } else { |
| 3372 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3373 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 3374 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3375 | |
| 3376 | // Start with the base register. Do this first so that subsequent address |
| 3377 | // matching finds it last, which will prevent it from trying to match it |
| 3378 | // as the scaled value in case it happens to be a mul. That would be |
| 3379 | // problematic if we've sunk a different mul for the scale, because then |
| 3380 | // we'd end up sinking both muls. |
| 3381 | if (AddrMode.BaseReg) { |
| 3382 | Value *V = AddrMode.BaseReg; |
| 3383 | if (V->getType() != IntPtrTy) |
| 3384 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 3385 | |
| 3386 | ResultIndex = V; |
| 3387 | } |
| 3388 | |
| 3389 | // Add the scale value. |
| 3390 | if (AddrMode.Scale) { |
| 3391 | Value *V = AddrMode.ScaledReg; |
| 3392 | if (V->getType() == IntPtrTy) { |
| 3393 | // done. |
| 3394 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3395 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 3396 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 3397 | } else { |
| 3398 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3399 | // required to create it did not overflow before we extend it. Since |
| 3400 | // the original IR value was tossed in favor of a constant back when |
| 3401 | // the AddrMode was created we need to bail out gracefully if widths |
| 3402 | // do not match instead of extending it. |
| 3403 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 3404 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 3405 | I->eraseFromParent(); |
| 3406 | return false; |
| 3407 | } |
| 3408 | |
| 3409 | if (AddrMode.Scale != 1) |
| 3410 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3411 | "sunkaddr"); |
| 3412 | if (ResultIndex) |
| 3413 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 3414 | else |
| 3415 | ResultIndex = V; |
| 3416 | } |
| 3417 | |
| 3418 | // Add in the Base Offset if present. |
| 3419 | if (AddrMode.BaseOffs) { |
| 3420 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 3421 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 3422 | // We need to add this separately from the scale above to help with |
| 3423 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3424 | if (ResultPtr->getType() != I8PtrTy) |
| 3425 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3426 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3427 | } |
| 3428 | |
| 3429 | ResultIndex = V; |
| 3430 | } |
| 3431 | |
| 3432 | if (!ResultIndex) { |
| 3433 | SunkAddr = ResultPtr; |
| 3434 | } else { |
| 3435 | if (ResultPtr->getType() != I8PtrTy) |
| 3436 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3437 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3438 | } |
| 3439 | |
| 3440 | if (SunkAddr->getType() != Addr->getType()) |
| 3441 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 3442 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3443 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3444 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3445 | << *MemoryInst << "\n"); |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 3446 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3447 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3448 | |
| 3449 | // Start with the base register. Do this first so that subsequent address |
| 3450 | // matching finds it last, which will prevent it from trying to match it |
| 3451 | // as the scaled value in case it happens to be a mul. That would be |
| 3452 | // problematic if we've sunk a different mul for the scale, because then |
| 3453 | // we'd end up sinking both muls. |
| 3454 | if (AddrMode.BaseReg) { |
| 3455 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3456 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3457 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3458 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3459 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3460 | Result = V; |
| 3461 | } |
| 3462 | |
| 3463 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3464 | if (AddrMode.Scale) { |
| 3465 | Value *V = AddrMode.ScaledReg; |
| 3466 | if (V->getType() == IntPtrTy) { |
| 3467 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3468 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3469 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3470 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3471 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3472 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3473 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3474 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3475 | // required to create it did not overflow before we extend it. Since |
| 3476 | // the original IR value was tossed in favor of a constant back when |
| 3477 | // the AddrMode was created we need to bail out gracefully if widths |
| 3478 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 3479 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 3480 | if (I && (Result != AddrMode.BaseReg)) |
| 3481 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3482 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3483 | } |
| 3484 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3485 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3486 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3487 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3488 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3489 | else |
| 3490 | Result = V; |
| 3491 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3492 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3493 | // Add in the BaseGV if present. |
| 3494 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3495 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3496 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3497 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3498 | else |
| 3499 | Result = V; |
| 3500 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3501 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3502 | // Add in the Base Offset if present. |
| 3503 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 3504 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3505 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3506 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3507 | else |
| 3508 | Result = V; |
| 3509 | } |
| 3510 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3511 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3512 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3513 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3514 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3515 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3516 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3517 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3518 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3519 | // If we have no uses, recursively delete the value and all dead instructions |
| 3520 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3521 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3522 | // This can cause recursive deletion, which can invalidate our iterator. |
| 3523 | // Use a WeakVH to hold onto it in case this happens. |
| 3524 | WeakVH IterHandle(CurInstIterator); |
| 3525 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3526 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 3527 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3528 | |
| 3529 | if (IterHandle != CurInstIterator) { |
| 3530 | // If the iterator instruction was recursively deleted, start over at the |
| 3531 | // start of the block. |
| 3532 | CurInstIterator = BB->begin(); |
| 3533 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3534 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 3535 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 3536 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3537 | return true; |
| 3538 | } |
| 3539 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3540 | /// OptimizeInlineAsmInst - If there are any memory operands, use |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 3541 | /// OptimizeMemoryInst to sink their address computing into the block when |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3542 | /// possible / profitable. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 3543 | bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3544 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3545 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3546 | const TargetRegisterInfo *TRI = |
| 3547 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3548 | TargetLowering::AsmOperandInfoVector |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3549 | TargetConstraints = TLI->ParseConstraints(TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 3550 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 3551 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3552 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3553 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3554 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 3555 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3556 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 3557 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 3558 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 3559 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3560 | MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 3561 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 3562 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3563 | } |
| 3564 | |
| 3565 | return MadeChange; |
| 3566 | } |
| 3567 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3568 | /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or |
| 3569 | /// sign extensions. |
| 3570 | static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) { |
| 3571 | assert(!Inst->use_empty() && "Input must have at least one use"); |
| 3572 | const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin()); |
| 3573 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 3574 | Type *ExtTy = FirstUser->getType(); |
| 3575 | for (const User *U : Inst->users()) { |
| 3576 | const Instruction *UI = cast<Instruction>(U); |
| 3577 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 3578 | return false; |
| 3579 | Type *CurTy = UI->getType(); |
| 3580 | // Same input and output types: Same instruction after CSE. |
| 3581 | if (CurTy == ExtTy) |
| 3582 | continue; |
| 3583 | |
| 3584 | // If IsSExt is true, we are in this situation: |
| 3585 | // a = Inst |
| 3586 | // b = sext ty1 a to ty2 |
| 3587 | // c = sext ty1 a to ty3 |
| 3588 | // Assuming ty2 is shorter than ty3, this could be turned into: |
| 3589 | // a = Inst |
| 3590 | // b = sext ty1 a to ty2 |
| 3591 | // c = sext ty2 b to ty3 |
| 3592 | // However, the last sext is not free. |
| 3593 | if (IsSExt) |
| 3594 | return false; |
| 3595 | |
| 3596 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 3597 | // In that case, we would not account for a different use. |
| 3598 | Type *NarrowTy; |
| 3599 | Type *LargeTy; |
| 3600 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 3601 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 3602 | NarrowTy = CurTy; |
| 3603 | LargeTy = ExtTy; |
| 3604 | } else { |
| 3605 | NarrowTy = ExtTy; |
| 3606 | LargeTy = CurTy; |
| 3607 | } |
| 3608 | |
| 3609 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 3610 | return false; |
| 3611 | } |
| 3612 | // All uses are the same or can be derived from one another for free. |
| 3613 | return true; |
| 3614 | } |
| 3615 | |
| 3616 | /// \brief Try to form ExtLd by promoting \p Exts until they reach a |
| 3617 | /// load instruction. |
| 3618 | /// If an ext(load) can be formed, it is returned via \p LI for the load |
| 3619 | /// and \p Inst for the extension. |
| 3620 | /// Otherwise LI == nullptr and Inst == nullptr. |
| 3621 | /// When some promotion happened, \p TPT contains the proper state to |
| 3622 | /// revert them. |
| 3623 | /// |
| 3624 | /// \return true when promoting was necessary to expose the ext(load) |
| 3625 | /// opportunity, false otherwise. |
| 3626 | /// |
| 3627 | /// Example: |
| 3628 | /// \code |
| 3629 | /// %ld = load i32* %addr |
| 3630 | /// %add = add nuw i32 %ld, 4 |
| 3631 | /// %zext = zext i32 %add to i64 |
| 3632 | /// \endcode |
| 3633 | /// => |
| 3634 | /// \code |
| 3635 | /// %ld = load i32* %addr |
| 3636 | /// %zext = zext i32 %ld to i64 |
| 3637 | /// %add = add nuw i64 %zext, 4 |
| 3638 | /// \encode |
| 3639 | /// Thanks to the promotion, we can match zext(load i32*) to i64. |
| 3640 | bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT, |
| 3641 | LoadInst *&LI, Instruction *&Inst, |
| 3642 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3643 | unsigned CreatedInstsCost = 0) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3644 | // Iterate over all the extensions to see if one form an ext(load). |
| 3645 | for (auto I : Exts) { |
| 3646 | // Check if we directly have ext(load). |
| 3647 | if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) { |
| 3648 | Inst = I; |
| 3649 | // No promotion happened here. |
| 3650 | return false; |
| 3651 | } |
| 3652 | // Check whether or not we want to do any promotion. |
| 3653 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
| 3654 | continue; |
| 3655 | // Get the action to perform the promotion. |
| 3656 | TypePromotionHelper::Action TPH = TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3657 | I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3658 | // Check if we can promote. |
| 3659 | if (!TPH) |
| 3660 | continue; |
| 3661 | // Save the current state. |
| 3662 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3663 | TPT.getRestorationPoint(); |
| 3664 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3665 | unsigned NewCreatedInstsCost = 0; |
| 3666 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3667 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3668 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 3669 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3670 | assert(PromotedVal && |
| 3671 | "TypePromotionHelper should have filtered out those cases"); |
| 3672 | |
| 3673 | // We would be able to merge only one extension in a load. |
| 3674 | // Therefore, if we have more than 1 new extension we heuristically |
| 3675 | // cut this search path, because it means we degrade the code quality. |
| 3676 | // With exactly 2, the transformation is neutral, because we will merge |
| 3677 | // one extension but leave one. However, we optimistically keep going, |
| 3678 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3679 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
| 3680 | TotalCreatedInstsCost -= ExtCost; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3681 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3682 | (TotalCreatedInstsCost > 1 || |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3683 | !isPromotedInstructionLegal(*TLI, PromotedVal))) { |
| 3684 | // The promotion is not profitable, rollback to the previous state. |
| 3685 | TPT.rollback(LastKnownGood); |
| 3686 | continue; |
| 3687 | } |
| 3688 | // The promotion is profitable. |
| 3689 | // Check if it exposes an ext(load). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3690 | (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost); |
| 3691 | if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3692 | // If we have created a new extension, i.e., now we have two |
| 3693 | // extensions. We must make sure one of them is merged with |
| 3694 | // the load, otherwise we may degrade the code quality. |
| 3695 | (LI->hasOneUse() || hasSameExtUse(LI, *TLI)))) |
| 3696 | // Promotion happened. |
| 3697 | return true; |
| 3698 | // If this does not help to expose an ext(load) then, rollback. |
| 3699 | TPT.rollback(LastKnownGood); |
| 3700 | } |
| 3701 | // None of the extension can form an ext(load). |
| 3702 | LI = nullptr; |
| 3703 | Inst = nullptr; |
| 3704 | return false; |
| 3705 | } |
| 3706 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3707 | /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same |
| 3708 | /// basic block as the load, unless conditions are unfavorable. This allows |
| 3709 | /// SelectionDAG to fold the extend into the load. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3710 | /// \p I[in/out] the extension may be modified during the process if some |
| 3711 | /// promotions apply. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3712 | /// |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3713 | bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) { |
| 3714 | // Try to promote a chain of computation if it allows to form |
| 3715 | // an extended load. |
| 3716 | TypePromotionTransaction TPT; |
| 3717 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3718 | TPT.getRestorationPoint(); |
| 3719 | SmallVector<Instruction *, 1> Exts; |
| 3720 | Exts.push_back(I); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3721 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3722 | LoadInst *LI = nullptr; |
| 3723 | Instruction *OldExt = I; |
| 3724 | bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts); |
| 3725 | if (!LI || !I) { |
| 3726 | assert(!HasPromoted && !LI && "If we did not match any load instruction " |
| 3727 | "the code must remain the same"); |
| 3728 | I = OldExt; |
| 3729 | return false; |
| 3730 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3731 | |
| 3732 | // If they're already in the same block, there's nothing to do. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3733 | // Make the cheap checks first if we did not promote. |
| 3734 | // If we promoted, we need to check if it is indeed profitable. |
| 3735 | if (!HasPromoted && LI->getParent() == I->getParent()) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3736 | return false; |
| 3737 | |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 3738 | EVT VT = TLI->getValueType(I->getType()); |
| 3739 | EVT LoadVT = TLI->getValueType(LI->getType()); |
| 3740 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3741 | // If the load has other users and the truncate is not free, this probably |
| 3742 | // isn't worthwhile. |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 3743 | if (!LI->hasOneUse() && TLI && |
| 3744 | (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3745 | !TLI->isTruncateFree(I->getType(), LI->getType())) { |
| 3746 | I = OldExt; |
| 3747 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3748 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3749 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3750 | |
| 3751 | // Check whether the target supports casts folded into loads. |
| 3752 | unsigned LType; |
| 3753 | if (isa<ZExtInst>(I)) |
| 3754 | LType = ISD::ZEXTLOAD; |
| 3755 | else { |
| 3756 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 3757 | LType = ISD::SEXTLOAD; |
| 3758 | } |
Ahmed Bougacha | 2b6917b | 2015-01-08 00:51:32 +0000 | [diff] [blame] | 3759 | if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3760 | I = OldExt; |
| 3761 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3762 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3763 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3764 | |
| 3765 | // Move the extend into the same block as the load, so that SelectionDAG |
| 3766 | // can fold it. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3767 | TPT.commit(); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3768 | I->removeFromParent(); |
| 3769 | I->insertAfter(LI); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 3770 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 3771 | return true; |
| 3772 | } |
| 3773 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3774 | bool CodeGenPrepare::OptimizeExtUses(Instruction *I) { |
| 3775 | BasicBlock *DefBB = I->getParent(); |
| 3776 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 3777 | // If the result of a {s|z}ext and its source are both live out, rewrite all |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3778 | // other uses of the source with result of extension. |
| 3779 | Value *Src = I->getOperand(0); |
| 3780 | if (Src->hasOneUse()) |
| 3781 | return false; |
| 3782 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 3783 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 3784 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 3785 | return false; |
| 3786 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 3787 | // Only safe to perform the optimization if the source is also defined in |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 3788 | // this block. |
| 3789 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 3790 | return false; |
| 3791 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3792 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3793 | for (User *U : I->users()) { |
| 3794 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3795 | |
| 3796 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3797 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3798 | if (UserBB == DefBB) continue; |
| 3799 | DefIsLiveOut = true; |
| 3800 | break; |
| 3801 | } |
| 3802 | if (!DefIsLiveOut) |
| 3803 | return false; |
| 3804 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 3805 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3806 | for (User *U : Src->users()) { |
| 3807 | Instruction *UI = cast<Instruction>(U); |
| 3808 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 3809 | if (UserBB == DefBB) continue; |
| 3810 | // Be conservative. We don't want this xform to end up introducing |
| 3811 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3812 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 3813 | return false; |
| 3814 | } |
| 3815 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3816 | // InsertedTruncs - Only insert one trunc in each block once. |
| 3817 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 3818 | |
| 3819 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3820 | for (Use &U : Src->uses()) { |
| 3821 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3822 | |
| 3823 | // Figure out which BB this ext is used in. |
| 3824 | BasicBlock *UserBB = User->getParent(); |
| 3825 | if (UserBB == DefBB) continue; |
| 3826 | |
| 3827 | // Both src and def are live in this block. Rewrite the use. |
| 3828 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 3829 | |
| 3830 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 3831 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3832 | InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3833 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3834 | } |
| 3835 | |
| 3836 | // Replace a use of the {s|z}ext source with a use of the result. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3837 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 3838 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3839 | MadeChange = true; |
| 3840 | } |
| 3841 | |
| 3842 | return MadeChange; |
| 3843 | } |
| 3844 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3845 | /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be |
| 3846 | /// turned into an explicit branch. |
| 3847 | static bool isFormingBranchFromSelectProfitable(SelectInst *SI) { |
| 3848 | // FIXME: This should use the same heuristics as IfConversion to determine |
| 3849 | // whether a select is better represented as a branch. This requires that |
| 3850 | // branch probability metadata is preserved for the select, which is not the |
| 3851 | // case currently. |
| 3852 | |
| 3853 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 3854 | |
| 3855 | // If the branch is predicted right, an out of order CPU can avoid blocking on |
| 3856 | // the compare. Emit cmovs on compares with a memory operand as branches to |
| 3857 | // avoid stalls on the load from memory. If the compare has more than one use |
| 3858 | // there's probably another cmov or setcc around so it's not worth emitting a |
| 3859 | // branch. |
| 3860 | if (!Cmp) |
| 3861 | return false; |
| 3862 | |
| 3863 | Value *CmpOp0 = Cmp->getOperand(0); |
| 3864 | Value *CmpOp1 = Cmp->getOperand(1); |
| 3865 | |
| 3866 | // We check that the memory operand has one use to avoid uses of the loaded |
| 3867 | // value directly after the compare, making branches unprofitable. |
| 3868 | return Cmp->hasOneUse() && |
| 3869 | ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) || |
| 3870 | (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse())); |
| 3871 | } |
| 3872 | |
| 3873 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3874 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 3875 | /// turn it into a branch. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3876 | bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) { |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3877 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 3878 | |
| 3879 | // Can we convert the 'select' to CF ? |
| 3880 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3881 | return false; |
| 3882 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3883 | TargetLowering::SelectSupportKind SelectKind; |
| 3884 | if (VectorCond) |
| 3885 | SelectKind = TargetLowering::VectorMaskSelect; |
| 3886 | else if (SI->getType()->isVectorTy()) |
| 3887 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 3888 | else |
| 3889 | SelectKind = TargetLowering::ScalarValSelect; |
| 3890 | |
| 3891 | // Do we have efficient codegen support for this kind of 'selects' ? |
| 3892 | if (TLI->isSelectSupported(SelectKind)) { |
| 3893 | // We have efficient codegen support for the select instruction. |
| 3894 | // Check if it is profitable to keep this 'select'. |
| 3895 | if (!TLI->isPredictableSelectExpensive() || |
| 3896 | !isFormingBranchFromSelectProfitable(SI)) |
| 3897 | return false; |
| 3898 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3899 | |
| 3900 | ModifiedDT = true; |
| 3901 | |
| 3902 | // First, we split the block containing the select into 2 blocks. |
| 3903 | BasicBlock *StartBlock = SI->getParent(); |
| 3904 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI)); |
| 3905 | BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
| 3906 | |
| 3907 | // Create a new block serving as the landing pad for the branch. |
| 3908 | BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid", |
| 3909 | NextBlock->getParent(), NextBlock); |
| 3910 | |
| 3911 | // Move the unconditional branch from the block with the select in it into our |
| 3912 | // landing pad block. |
| 3913 | StartBlock->getTerminator()->eraseFromParent(); |
| 3914 | BranchInst::Create(NextBlock, SmallBlock); |
| 3915 | |
| 3916 | // Insert the real conditional branch based on the original condition. |
| 3917 | BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI); |
| 3918 | |
| 3919 | // The select itself is replaced with a PHI Node. |
| 3920 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin()); |
| 3921 | PN->takeName(SI); |
| 3922 | PN->addIncoming(SI->getTrueValue(), StartBlock); |
| 3923 | PN->addIncoming(SI->getFalseValue(), SmallBlock); |
| 3924 | SI->replaceAllUsesWith(PN); |
| 3925 | SI->eraseFromParent(); |
| 3926 | |
| 3927 | // Instruct OptimizeBlock to skip to the next block. |
| 3928 | CurInstIterator = StartBlock->end(); |
| 3929 | ++NumSelectsExpanded; |
| 3930 | return true; |
| 3931 | } |
| 3932 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 3933 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3934 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 3935 | int SplatElem = -1; |
| 3936 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 3937 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 3938 | return false; |
| 3939 | SplatElem = Mask[i]; |
| 3940 | } |
| 3941 | |
| 3942 | return true; |
| 3943 | } |
| 3944 | |
| 3945 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 3946 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 3947 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 3948 | /// codegen can spot all lanes are identical. |
| 3949 | bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
| 3950 | BasicBlock *DefBB = SVI->getParent(); |
| 3951 | |
| 3952 | // Only do this xform if variable vector shifts are particularly expensive. |
| 3953 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 3954 | return false; |
| 3955 | |
| 3956 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 3957 | // constant splat. |
| 3958 | if (!isBroadcastShuffle(SVI)) |
| 3959 | return false; |
| 3960 | |
| 3961 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 3962 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 3963 | |
| 3964 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3965 | for (User *U : SVI->users()) { |
| 3966 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3967 | |
| 3968 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3969 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3970 | if (UserBB == DefBB) continue; |
| 3971 | |
| 3972 | // For now only apply this when the splat is used by a shift instruction. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3973 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3974 | |
| 3975 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 3976 | // already have a copy. |
| 3977 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 3978 | |
| 3979 | if (!InsertedShuffle) { |
| 3980 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 3981 | InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0), |
| 3982 | SVI->getOperand(1), |
| 3983 | SVI->getOperand(2), "", InsertPt); |
| 3984 | } |
| 3985 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3986 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3987 | MadeChange = true; |
| 3988 | } |
| 3989 | |
| 3990 | // If we removed all uses, nuke the shuffle. |
| 3991 | if (SVI->use_empty()) { |
| 3992 | SVI->eraseFromParent(); |
| 3993 | MadeChange = true; |
| 3994 | } |
| 3995 | |
| 3996 | return MadeChange; |
| 3997 | } |
| 3998 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 3999 | namespace { |
| 4000 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 4001 | /// This class is used to move downward extractelement transition. |
| 4002 | /// E.g., |
| 4003 | /// a = vector_op <2 x i32> |
| 4004 | /// b = extractelement <2 x i32> a, i32 0 |
| 4005 | /// c = scalar_op b |
| 4006 | /// store c |
| 4007 | /// |
| 4008 | /// => |
| 4009 | /// a = vector_op <2 x i32> |
| 4010 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 4011 | /// * d = extractelement <2 x i32> c, i32 0 |
| 4012 | /// * store d |
| 4013 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 4014 | /// transition. |
| 4015 | class VectorPromoteHelper { |
| 4016 | /// Used to perform some checks on the legality of vector operations. |
| 4017 | const TargetLowering &TLI; |
| 4018 | |
| 4019 | /// Used to estimated the cost of the promoted chain. |
| 4020 | const TargetTransformInfo &TTI; |
| 4021 | |
| 4022 | /// The transition being moved downwards. |
| 4023 | Instruction *Transition; |
| 4024 | /// The sequence of instructions to be promoted. |
| 4025 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 4026 | /// Cost of combining a store and an extract. |
| 4027 | unsigned StoreExtractCombineCost; |
| 4028 | /// Instruction that will be combined with the transition. |
| 4029 | Instruction *CombineInst; |
| 4030 | |
| 4031 | /// \brief The instruction that represents the current end of the transition. |
| 4032 | /// Since we are faking the promotion until we reach the end of the chain |
| 4033 | /// of computation, we need a way to get the current end of the transition. |
| 4034 | Instruction *getEndOfTransition() const { |
| 4035 | if (InstsToBePromoted.empty()) |
| 4036 | return Transition; |
| 4037 | return InstsToBePromoted.back(); |
| 4038 | } |
| 4039 | |
| 4040 | /// \brief Return the index of the original value in the transition. |
| 4041 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 4042 | /// c, is at index 0. |
| 4043 | unsigned getTransitionOriginalValueIdx() const { |
| 4044 | assert(isa<ExtractElementInst>(Transition) && |
| 4045 | "Other kind of transitions are not supported yet"); |
| 4046 | return 0; |
| 4047 | } |
| 4048 | |
| 4049 | /// \brief Return the index of the index in the transition. |
| 4050 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 4051 | /// is at index 1. |
| 4052 | unsigned getTransitionIdx() const { |
| 4053 | assert(isa<ExtractElementInst>(Transition) && |
| 4054 | "Other kind of transitions are not supported yet"); |
| 4055 | return 1; |
| 4056 | } |
| 4057 | |
| 4058 | /// \brief Get the type of the transition. |
| 4059 | /// This is the type of the original value. |
| 4060 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 4061 | /// transition is <2 x i32>. |
| 4062 | Type *getTransitionType() const { |
| 4063 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 4064 | } |
| 4065 | |
| 4066 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 4067 | /// I.e., we have the following sequence: |
| 4068 | /// Def = Transition <ty1> a to <ty2> |
| 4069 | /// b = ToBePromoted <ty2> Def, ... |
| 4070 | /// => |
| 4071 | /// b = ToBePromoted <ty1> a, ... |
| 4072 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 4073 | void promoteImpl(Instruction *ToBePromoted); |
| 4074 | |
| 4075 | /// \brief Check whether or not it is profitable to promote all the |
| 4076 | /// instructions enqueued to be promoted. |
| 4077 | bool isProfitableToPromote() { |
| 4078 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 4079 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 4080 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 4081 | : -1; |
| 4082 | Type *PromotedType = getTransitionType(); |
| 4083 | |
| 4084 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 4085 | unsigned AS = ST->getPointerAddressSpace(); |
| 4086 | unsigned Align = ST->getAlignment(); |
| 4087 | // Check if this store is supported. |
| 4088 | if (!TLI.allowsMisalignedMemoryAccesses( |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 4089 | TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4090 | // If this is not supported, there is no way we can combine |
| 4091 | // the extract with the store. |
| 4092 | return false; |
| 4093 | } |
| 4094 | |
| 4095 | // The scalar chain of computation has to pay for the transition |
| 4096 | // scalar to vector. |
| 4097 | // The vector chain has to account for the combining cost. |
| 4098 | uint64_t ScalarCost = |
| 4099 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 4100 | uint64_t VectorCost = StoreExtractCombineCost; |
| 4101 | for (const auto &Inst : InstsToBePromoted) { |
| 4102 | // Compute the cost. |
| 4103 | // By construction, all instructions being promoted are arithmetic ones. |
| 4104 | // Moreover, one argument is a constant that can be viewed as a splat |
| 4105 | // constant. |
| 4106 | Value *Arg0 = Inst->getOperand(0); |
| 4107 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 4108 | isa<ConstantFP>(Arg0); |
| 4109 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 4110 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4111 | : TargetTransformInfo::OK_AnyValue; |
| 4112 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 4113 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4114 | : TargetTransformInfo::OK_AnyValue; |
| 4115 | ScalarCost += TTI.getArithmeticInstrCost( |
| 4116 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 4117 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 4118 | Arg0OVK, Arg1OVK); |
| 4119 | } |
| 4120 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 4121 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 4122 | return ScalarCost > VectorCost; |
| 4123 | } |
| 4124 | |
| 4125 | /// \brief Generate a constant vector with \p Val with the same |
| 4126 | /// number of elements as the transition. |
| 4127 | /// \p UseSplat defines whether or not \p Val should be replicated |
| 4128 | /// accross the whole vector. |
| 4129 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 4130 | /// otherwise we generate a vector with as many undef as possible: |
| 4131 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 4132 | /// used at the index of the extract. |
| 4133 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 4134 | unsigned ExtractIdx = UINT_MAX; |
| 4135 | if (!UseSplat) { |
| 4136 | // If we cannot determine where the constant must be, we have to |
| 4137 | // use a splat constant. |
| 4138 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 4139 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 4140 | ExtractIdx = CstVal->getSExtValue(); |
| 4141 | else |
| 4142 | UseSplat = true; |
| 4143 | } |
| 4144 | |
| 4145 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 4146 | if (UseSplat) |
| 4147 | return ConstantVector::getSplat(End, Val); |
| 4148 | |
| 4149 | SmallVector<Constant *, 4> ConstVec; |
| 4150 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 4151 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 4152 | if (Idx == ExtractIdx) |
| 4153 | ConstVec.push_back(Val); |
| 4154 | else |
| 4155 | ConstVec.push_back(UndefVal); |
| 4156 | } |
| 4157 | return ConstantVector::get(ConstVec); |
| 4158 | } |
| 4159 | |
| 4160 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 4161 | /// in \p Use can trigger undefined behavior. |
| 4162 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 4163 | unsigned OperandIdx) { |
| 4164 | // This is not safe to introduce undef when the operand is on |
| 4165 | // the right hand side of a division-like instruction. |
| 4166 | if (OperandIdx != 1) |
| 4167 | return false; |
| 4168 | switch (Use->getOpcode()) { |
| 4169 | default: |
| 4170 | return false; |
| 4171 | case Instruction::SDiv: |
| 4172 | case Instruction::UDiv: |
| 4173 | case Instruction::SRem: |
| 4174 | case Instruction::URem: |
| 4175 | return true; |
| 4176 | case Instruction::FDiv: |
| 4177 | case Instruction::FRem: |
| 4178 | return !Use->hasNoNaNs(); |
| 4179 | } |
| 4180 | llvm_unreachable(nullptr); |
| 4181 | } |
| 4182 | |
| 4183 | public: |
| 4184 | VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI, |
| 4185 | Instruction *Transition, unsigned CombineCost) |
| 4186 | : TLI(TLI), TTI(TTI), Transition(Transition), |
| 4187 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 4188 | assert(Transition && "Do not know how to promote null"); |
| 4189 | } |
| 4190 | |
| 4191 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 4192 | bool canPromote(const Instruction *ToBePromoted) const { |
| 4193 | // We could support CastInst too. |
| 4194 | return isa<BinaryOperator>(ToBePromoted); |
| 4195 | } |
| 4196 | |
| 4197 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 4198 | /// by moving downward the transition through. |
| 4199 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 4200 | // Promote only if all the operands can be statically expanded. |
| 4201 | // Indeed, we do not want to introduce any new kind of transitions. |
| 4202 | for (const Use &U : ToBePromoted->operands()) { |
| 4203 | const Value *Val = U.get(); |
| 4204 | if (Val == getEndOfTransition()) { |
| 4205 | // If the use is a division and the transition is on the rhs, |
| 4206 | // we cannot promote the operation, otherwise we may create a |
| 4207 | // division by zero. |
| 4208 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 4209 | return false; |
| 4210 | continue; |
| 4211 | } |
| 4212 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 4213 | !isa<ConstantFP>(Val)) |
| 4214 | return false; |
| 4215 | } |
| 4216 | // Check that the resulting operation is legal. |
| 4217 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 4218 | if (!ISDOpcode) |
| 4219 | return false; |
| 4220 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 4221 | TLI.isOperationLegalOrCustom( |
| 4222 | ISDOpcode, TLI.getValueType(getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4223 | } |
| 4224 | |
| 4225 | /// \brief Check whether or not \p Use can be combined |
| 4226 | /// with the transition. |
| 4227 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 4228 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 4229 | |
| 4230 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 4231 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 4232 | InstsToBePromoted.push_back(ToBePromoted); |
| 4233 | } |
| 4234 | |
| 4235 | /// \brief Set the instruction that will be combined with the transition. |
| 4236 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 4237 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 4238 | CombineInst = ToBeCombined; |
| 4239 | } |
| 4240 | |
| 4241 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 4242 | /// is profitable. |
| 4243 | /// \return True if the promotion happened, false otherwise. |
| 4244 | bool promote() { |
| 4245 | // Check if there is something to promote. |
| 4246 | // Right now, if we do not have anything to combine with, |
| 4247 | // we assume the promotion is not profitable. |
| 4248 | if (InstsToBePromoted.empty() || !CombineInst) |
| 4249 | return false; |
| 4250 | |
| 4251 | // Check cost. |
| 4252 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 4253 | return false; |
| 4254 | |
| 4255 | // Promote. |
| 4256 | for (auto &ToBePromoted : InstsToBePromoted) |
| 4257 | promoteImpl(ToBePromoted); |
| 4258 | InstsToBePromoted.clear(); |
| 4259 | return true; |
| 4260 | } |
| 4261 | }; |
| 4262 | } // End of anonymous namespace. |
| 4263 | |
| 4264 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 4265 | // At this point, we know that all the operands of ToBePromoted but Def |
| 4266 | // can be statically promoted. |
| 4267 | // For Def, we need to use its parameter in ToBePromoted: |
| 4268 | // b = ToBePromoted ty1 a |
| 4269 | // Def = Transition ty1 b to ty2 |
| 4270 | // Move the transition down. |
| 4271 | // 1. Replace all uses of the promoted operation by the transition. |
| 4272 | // = ... b => = ... Def. |
| 4273 | assert(ToBePromoted->getType() == Transition->getType() && |
| 4274 | "The type of the result of the transition does not match " |
| 4275 | "the final type"); |
| 4276 | ToBePromoted->replaceAllUsesWith(Transition); |
| 4277 | // 2. Update the type of the uses. |
| 4278 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 4279 | Type *TransitionTy = getTransitionType(); |
| 4280 | ToBePromoted->mutateType(TransitionTy); |
| 4281 | // 3. Update all the operands of the promoted operation with promoted |
| 4282 | // operands. |
| 4283 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 4284 | for (Use &U : ToBePromoted->operands()) { |
| 4285 | Value *Val = U.get(); |
| 4286 | Value *NewVal = nullptr; |
| 4287 | if (Val == Transition) |
| 4288 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 4289 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 4290 | isa<ConstantFP>(Val)) { |
| 4291 | // Use a splat constant if it is not safe to use undef. |
| 4292 | NewVal = getConstantVector( |
| 4293 | cast<Constant>(Val), |
| 4294 | isa<UndefValue>(Val) || |
| 4295 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 4296 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 4297 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 4298 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4299 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 4300 | } |
| 4301 | Transition->removeFromParent(); |
| 4302 | Transition->insertAfter(ToBePromoted); |
| 4303 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 4304 | } |
| 4305 | |
| 4306 | /// Some targets can do store(extractelement) with one instruction. |
| 4307 | /// Try to push the extractelement towards the stores when the target |
| 4308 | /// has this feature and this is profitable. |
| 4309 | bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) { |
| 4310 | unsigned CombineCost = UINT_MAX; |
| 4311 | if (DisableStoreExtract || !TLI || |
| 4312 | (!StressStoreExtract && |
| 4313 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 4314 | Inst->getOperand(1), CombineCost))) |
| 4315 | return false; |
| 4316 | |
| 4317 | // At this point we know that Inst is a vector to scalar transition. |
| 4318 | // Try to move it down the def-use chain, until: |
| 4319 | // - We can combine the transition with its single use |
| 4320 | // => we got rid of the transition. |
| 4321 | // - We escape the current basic block |
| 4322 | // => we would need to check that we are moving it at a cheaper place and |
| 4323 | // we do not do that for now. |
| 4324 | BasicBlock *Parent = Inst->getParent(); |
| 4325 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
| 4326 | VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost); |
| 4327 | // If the transition has more than one use, assume this is not going to be |
| 4328 | // beneficial. |
| 4329 | while (Inst->hasOneUse()) { |
| 4330 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 4331 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 4332 | |
| 4333 | if (ToBePromoted->getParent() != Parent) { |
| 4334 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 4335 | << ToBePromoted->getParent()->getName() |
| 4336 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 4337 | return false; |
| 4338 | } |
| 4339 | |
| 4340 | if (VPH.canCombine(ToBePromoted)) { |
| 4341 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 4342 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 4343 | VPH.recordCombineInstruction(ToBePromoted); |
| 4344 | bool Changed = VPH.promote(); |
| 4345 | NumStoreExtractExposed += Changed; |
| 4346 | return Changed; |
| 4347 | } |
| 4348 | |
| 4349 | DEBUG(dbgs() << "Try promoting.\n"); |
| 4350 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 4351 | return false; |
| 4352 | |
| 4353 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 4354 | |
| 4355 | VPH.enqueueForPromotion(ToBePromoted); |
| 4356 | Inst = ToBePromoted; |
| 4357 | } |
| 4358 | return false; |
| 4359 | } |
| 4360 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 4361 | bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4362 | // Bail out if we inserted the instruction to prevent optimizations from |
| 4363 | // stepping on each other's toes. |
| 4364 | if (InsertedInsts.count(I)) |
| 4365 | return false; |
| 4366 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4367 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 4368 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 4369 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 4370 | // trivial PHI, go ahead and zap it here. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4371 | const DataLayout &DL = I->getModule()->getDataLayout(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 4372 | if (Value *V = SimplifyInstruction(P, DL, TLInfo, nullptr)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4373 | P->replaceAllUsesWith(V); |
| 4374 | P->eraseFromParent(); |
| 4375 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4376 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4377 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4378 | return false; |
| 4379 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4380 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4381 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4382 | // If the source of the cast is a constant, then this should have |
| 4383 | // already been constant folded. The only reason NOT to constant fold |
| 4384 | // it is if something (e.g. LSR) was careful to place the constant |
| 4385 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 4386 | // the address of globals out of a loop). If this is the case, we don't |
| 4387 | // want to forward-subst the cast. |
| 4388 | if (isa<Constant>(CI->getOperand(0))) |
| 4389 | return false; |
| 4390 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4391 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI)) |
| 4392 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4393 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4394 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 4395 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 4396 | /// fit in one register |
| 4397 | if (TLI && TLI->getTypeAction(CI->getContext(), |
| 4398 | TLI->getValueType(CI->getType())) == |
| 4399 | TargetLowering::TypeExpandInteger) { |
| 4400 | return SinkCast(CI); |
| 4401 | } else { |
| 4402 | bool MadeChange = MoveExtToFormExtLoad(I); |
| 4403 | return MadeChange | OptimizeExtUses(I); |
| 4404 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4405 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4406 | return false; |
| 4407 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4408 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4409 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 4410 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
| 4411 | return OptimizeCmpExpression(CI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4412 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4413 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4414 | if (TLI) { |
| 4415 | unsigned AS = LI->getPointerAddressSpace(); |
| 4416 | return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 4417 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4418 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4419 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4420 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4421 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4422 | if (TLI) { |
| 4423 | unsigned AS = SI->getPointerAddressSpace(); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4424 | return OptimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4425 | SI->getOperand(0)->getType(), AS); |
| 4426 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4427 | return false; |
| 4428 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4429 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 4430 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 4431 | |
| 4432 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 4433 | BinOp->getOpcode() == Instruction::LShr)) { |
| 4434 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 4435 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
| 4436 | return OptimizeExtractBits(BinOp, CI, *TLI); |
| 4437 | |
| 4438 | return false; |
| 4439 | } |
| 4440 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4441 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 4442 | if (GEPI->hasAllZeroIndices()) { |
| 4443 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 4444 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 4445 | GEPI->getName(), GEPI); |
| 4446 | GEPI->replaceAllUsesWith(NC); |
| 4447 | GEPI->eraseFromParent(); |
| 4448 | ++NumGEPsElim; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 4449 | OptimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4450 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 4451 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4452 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4453 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4454 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4455 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 4456 | return OptimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4457 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4458 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
| 4459 | return OptimizeSelectInst(SI); |
| 4460 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4461 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
| 4462 | return OptimizeShuffleVectorInst(SVI); |
| 4463 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4464 | if (isa<ExtractElementInst>(I)) |
| 4465 | return OptimizeExtractElementInst(I); |
| 4466 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4467 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4468 | } |
| 4469 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 4470 | // In this pass we look for GEP and cast instructions that are used |
| 4471 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 4472 | // selection. |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 4473 | bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 4474 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 4475 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4476 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4477 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 4478 | while (CurInstIterator != BB.end()) { |
| 4479 | MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT); |
| 4480 | if (ModifiedDT) |
| 4481 | return true; |
| 4482 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 4483 | MadeChange |= DupRetToEnableTailCallOpts(&BB); |
| 4484 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 4485 | return MadeChange; |
| 4486 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4487 | |
| 4488 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4489 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4490 | // find a node corresponding to the value. |
| 4491 | bool CodeGenPrepare::PlaceDbgValues(Function &F) { |
| 4492 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 4493 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4494 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 4495 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { |
Duncan P. N. Exon Smith | e90f116 | 2015-01-08 21:07:55 +0000 | [diff] [blame] | 4496 | Instruction *Insn = BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4497 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 4498 | // Leave dbg.values that refer to an alloca alone. These |
| 4499 | // instrinsics describe the address of a variable (= the alloca) |
| 4500 | // being taken. They should not be moved next to the alloca |
| 4501 | // (and to the beginning of the scope), but rather stay close to |
| 4502 | // where said address is used. |
| 4503 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4504 | PrevNonDbgInst = Insn; |
| 4505 | continue; |
| 4506 | } |
| 4507 | |
| 4508 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 4509 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
| 4510 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 4511 | DVI->removeFromParent(); |
| 4512 | if (isa<PHINode>(VI)) |
| 4513 | DVI->insertBefore(VI->getParent()->getFirstInsertionPt()); |
| 4514 | else |
| 4515 | DVI->insertAfter(VI); |
| 4516 | MadeChange = true; |
| 4517 | ++NumDbgValueMoved; |
| 4518 | } |
| 4519 | } |
| 4520 | } |
| 4521 | return MadeChange; |
| 4522 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 4523 | |
| 4524 | // If there is a sequence that branches based on comparing a single bit |
| 4525 | // against zero that can be combined into a single instruction, and the |
| 4526 | // target supports folding these into a single instruction, sink the |
| 4527 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 4528 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 4529 | // searched for. |
| 4530 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 4531 | if (!EnableAndCmpSinking) |
| 4532 | return false; |
| 4533 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 4534 | return false; |
| 4535 | bool MadeChange = false; |
| 4536 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ) { |
| 4537 | BasicBlock *BB = I++; |
| 4538 | |
| 4539 | // Does this BB end with the following? |
| 4540 | // %andVal = and %val, #single-bit-set |
| 4541 | // %icmpVal = icmp %andResult, 0 |
| 4542 | // br i1 %cmpVal label %dest1, label %dest2" |
| 4543 | BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator()); |
| 4544 | if (!Brcc || !Brcc->isConditional()) |
| 4545 | continue; |
| 4546 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
| 4547 | if (!Cmp || Cmp->getParent() != BB) |
| 4548 | continue; |
| 4549 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 4550 | if (!Zero || !Zero->isZero()) |
| 4551 | continue; |
| 4552 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
| 4553 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB) |
| 4554 | continue; |
| 4555 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 4556 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 4557 | continue; |
| 4558 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump()); |
| 4559 | |
| 4560 | // Push the "and; icmp" for any users that are conditional branches. |
| 4561 | // Since there can only be one branch use per BB, we don't need to keep |
| 4562 | // track of which BBs we insert into. |
| 4563 | for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end(); |
| 4564 | UI != E; ) { |
| 4565 | Use &TheUse = *UI; |
| 4566 | // Find brcc use. |
| 4567 | BranchInst *BrccUser = dyn_cast<BranchInst>(*UI); |
| 4568 | ++UI; |
| 4569 | if (!BrccUser || !BrccUser->isConditional()) |
| 4570 | continue; |
| 4571 | BasicBlock *UserBB = BrccUser->getParent(); |
| 4572 | if (UserBB == BB) continue; |
| 4573 | DEBUG(dbgs() << "found Brcc use\n"); |
| 4574 | |
| 4575 | // Sink the "and; icmp" to use. |
| 4576 | MadeChange = true; |
| 4577 | BinaryOperator *NewAnd = |
| 4578 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 4579 | BrccUser); |
| 4580 | CmpInst *NewCmp = |
| 4581 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 4582 | "", BrccUser); |
| 4583 | TheUse = NewCmp; |
| 4584 | ++NumAndCmpsMoved; |
| 4585 | DEBUG(BrccUser->getParent()->dump()); |
| 4586 | } |
| 4587 | } |
| 4588 | return MadeChange; |
| 4589 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4590 | |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 4591 | /// \brief Retrieve the probabilities of a conditional branch. Returns true on |
| 4592 | /// success, or returns false if no or invalid metadata was found. |
| 4593 | static bool extractBranchMetadata(BranchInst *BI, |
| 4594 | uint64_t &ProbTrue, uint64_t &ProbFalse) { |
| 4595 | assert(BI->isConditional() && |
| 4596 | "Looking for probabilities on unconditional branch?"); |
| 4597 | auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof); |
| 4598 | if (!ProfileData || ProfileData->getNumOperands() != 3) |
| 4599 | return false; |
| 4600 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 4601 | const auto *CITrue = |
| 4602 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)); |
| 4603 | const auto *CIFalse = |
| 4604 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2)); |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 4605 | if (!CITrue || !CIFalse) |
| 4606 | return false; |
| 4607 | |
| 4608 | ProbTrue = CITrue->getValue().getZExtValue(); |
| 4609 | ProbFalse = CIFalse->getValue().getZExtValue(); |
| 4610 | |
| 4611 | return true; |
| 4612 | } |
| 4613 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4614 | /// \brief Scale down both weights to fit into uint32_t. |
| 4615 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 4616 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 4617 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 4618 | NewTrue = NewTrue / Scale; |
| 4619 | NewFalse = NewFalse / Scale; |
| 4620 | } |
| 4621 | |
| 4622 | /// \brief Some targets prefer to split a conditional branch like: |
| 4623 | /// \code |
| 4624 | /// %0 = icmp ne i32 %a, 0 |
| 4625 | /// %1 = icmp ne i32 %b, 0 |
| 4626 | /// %or.cond = or i1 %0, %1 |
| 4627 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 4628 | /// \endcode |
| 4629 | /// into multiple branch instructions like: |
| 4630 | /// \code |
| 4631 | /// bb1: |
| 4632 | /// %0 = icmp ne i32 %a, 0 |
| 4633 | /// br i1 %0, label %TrueBB, label %bb2 |
| 4634 | /// bb2: |
| 4635 | /// %1 = icmp ne i32 %b, 0 |
| 4636 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 4637 | /// \endcode |
| 4638 | /// This usually allows instruction selection to do even further optimizations |
| 4639 | /// and combine the compare with the branch instruction. Currently this is |
| 4640 | /// applied for targets which have "cheap" jump instructions. |
| 4641 | /// |
| 4642 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 4643 | /// |
| 4644 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 4645 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4646 | return false; |
| 4647 | |
| 4648 | bool MadeChange = false; |
| 4649 | for (auto &BB : F) { |
| 4650 | // Does this BB end with the following? |
| 4651 | // %cond1 = icmp|fcmp|binary instruction ... |
| 4652 | // %cond2 = icmp|fcmp|binary instruction ... |
| 4653 | // %cond.or = or|and i1 %cond1, cond2 |
| 4654 | // br i1 %cond.or label %dest1, label %dest2" |
| 4655 | BinaryOperator *LogicOp; |
| 4656 | BasicBlock *TBB, *FBB; |
| 4657 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 4658 | continue; |
| 4659 | |
| 4660 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 4661 | Value *Cond1, *Cond2; |
| 4662 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 4663 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4664 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 4665 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 4666 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4667 | Opc = Instruction::Or; |
| 4668 | else |
| 4669 | continue; |
| 4670 | |
| 4671 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 4672 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 4673 | continue; |
| 4674 | |
| 4675 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 4676 | |
| 4677 | // Create a new BB. |
| 4678 | auto *InsertBefore = std::next(Function::iterator(BB)) |
| 4679 | .getNodePtrUnchecked(); |
| 4680 | auto TmpBB = BasicBlock::Create(BB.getContext(), |
| 4681 | BB.getName() + ".cond.split", |
| 4682 | BB.getParent(), InsertBefore); |
| 4683 | |
| 4684 | // Update original basic block by using the first condition directly by the |
| 4685 | // branch instruction and removing the no longer needed and/or instruction. |
| 4686 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 4687 | Br1->setCondition(Cond1); |
| 4688 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 4689 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4690 | // Depending on the conditon we have to either replace the true or the false |
| 4691 | // successor of the original branch instruction. |
| 4692 | if (Opc == Instruction::And) |
| 4693 | Br1->setSuccessor(0, TmpBB); |
| 4694 | else |
| 4695 | Br1->setSuccessor(1, TmpBB); |
| 4696 | |
| 4697 | // Fill in the new basic block. |
| 4698 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 4699 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 4700 | I->removeFromParent(); |
| 4701 | I->insertBefore(Br2); |
| 4702 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4703 | |
| 4704 | // Update PHI nodes in both successors. The original BB needs to be |
| 4705 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 4706 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 4707 | // incoming edge to the PHI nodes, because both branch instructions target |
| 4708 | // now the same successor. Depending on the original branch condition |
| 4709 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
| 4710 | // we perfrom the correct update for the PHI nodes. |
| 4711 | // This doesn't change the successor order of the just created branch |
| 4712 | // instruction (or any other instruction). |
| 4713 | if (Opc == Instruction::Or) |
| 4714 | std::swap(TBB, FBB); |
| 4715 | |
| 4716 | // Replace the old BB with the new BB. |
| 4717 | for (auto &I : *TBB) { |
| 4718 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 4719 | if (!PN) |
| 4720 | break; |
| 4721 | int i; |
| 4722 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 4723 | PN->setIncomingBlock(i, TmpBB); |
| 4724 | } |
| 4725 | |
| 4726 | // Add another incoming edge form the new BB. |
| 4727 | for (auto &I : *FBB) { |
| 4728 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 4729 | if (!PN) |
| 4730 | break; |
| 4731 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 4732 | PN->addIncoming(Val, TmpBB); |
| 4733 | } |
| 4734 | |
| 4735 | // Update the branch weights (from SelectionDAGBuilder:: |
| 4736 | // FindMergedConditions). |
| 4737 | if (Opc == Instruction::Or) { |
| 4738 | // Codegen X | Y as: |
| 4739 | // BB1: |
| 4740 | // jmp_if_X TBB |
| 4741 | // jmp TmpBB |
| 4742 | // TmpBB: |
| 4743 | // jmp_if_Y TBB |
| 4744 | // jmp FBB |
| 4745 | // |
| 4746 | |
| 4747 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 4748 | // The requirement is that |
| 4749 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 4750 | // = TrueProb for orignal BB. |
| 4751 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 4752 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 4753 | // assumes that |
| 4754 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 4755 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 4756 | // TmpBB, but the math is more complicated. |
| 4757 | uint64_t TrueWeight, FalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 4758 | if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4759 | uint64_t NewTrueWeight = TrueWeight; |
| 4760 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 4761 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 4762 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 4763 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 4764 | |
| 4765 | NewTrueWeight = TrueWeight; |
| 4766 | NewFalseWeight = 2 * FalseWeight; |
| 4767 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 4768 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 4769 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 4770 | } |
| 4771 | } else { |
| 4772 | // Codegen X & Y as: |
| 4773 | // BB1: |
| 4774 | // jmp_if_X TmpBB |
| 4775 | // jmp FBB |
| 4776 | // TmpBB: |
| 4777 | // jmp_if_Y TBB |
| 4778 | // jmp FBB |
| 4779 | // |
| 4780 | // This requires creation of TmpBB after CurBB. |
| 4781 | |
| 4782 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 4783 | // The requirement is that |
| 4784 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 4785 | // = FalseProb for orignal BB. |
| 4786 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 4787 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 4788 | // assumes that |
| 4789 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 4790 | uint64_t TrueWeight, FalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 4791 | if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4792 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 4793 | uint64_t NewFalseWeight = FalseWeight; |
| 4794 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 4795 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 4796 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 4797 | |
| 4798 | NewTrueWeight = 2 * TrueWeight; |
| 4799 | NewFalseWeight = FalseWeight; |
| 4800 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 4801 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 4802 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 4803 | } |
| 4804 | } |
| 4805 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4806 | // Note: No point in getting fancy here, since the DT info is never |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 4807 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 4808 | ModifiedDT = true; |
| 4809 | |
| 4810 | MadeChange = true; |
| 4811 | |
| 4812 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 4813 | TmpBB->dump()); |
| 4814 | } |
| 4815 | return MadeChange; |
| 4816 | } |