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" |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/TargetTransformInfo.h" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ValueTracking.h" |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/MemoryBuiltins.h" |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 26 | #include "llvm/CodeGen/Analysis.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 27 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Constants.h" |
| 29 | #include "llvm/IR/DataLayout.h" |
| 30 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 33 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 34 | #include "llvm/IR/IRBuilder.h" |
| 35 | #include "llvm/IR/InlineAsm.h" |
| 36 | #include "llvm/IR/Instructions.h" |
| 37 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 38 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 39 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 40 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 41 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 42 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 43 | #include "llvm/Pass.h" |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 44 | #include "llvm/Support/BranchProbability.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 45 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 46 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 47 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 48 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 49 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 50 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 51 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 52 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 53 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 54 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 55 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 56 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 57 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 58 | #define DEBUG_TYPE "codegenprepare" |
| 59 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 60 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 61 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 62 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 63 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 64 | "sunken Cmps"); |
| 65 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 66 | "of sunken Casts"); |
| 67 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 68 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 69 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 70 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 71 | STATISTIC(NumAndsAdded, |
| 72 | "Number of and mask instructions added to form ext loads"); |
| 73 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 74 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 75 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 76 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 77 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 78 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 79 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 80 | static cl::opt<bool> DisableBranchOpts( |
| 81 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 82 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 83 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 84 | static cl::opt<bool> |
| 85 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 86 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 87 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 88 | static cl::opt<bool> DisableSelectToBranch( |
| 89 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 90 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 91 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 92 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 93 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 94 | cl::desc("Address sinking in CGP using GEPs.")); |
| 95 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 96 | static cl::opt<bool> EnableAndCmpSinking( |
| 97 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 98 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 99 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 100 | static cl::opt<bool> DisableStoreExtract( |
| 101 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 102 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 103 | |
| 104 | static cl::opt<bool> StressStoreExtract( |
| 105 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 106 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 107 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 108 | static cl::opt<bool> DisableExtLdPromotion( |
| 109 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 110 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 111 | "CodeGenPrepare")); |
| 112 | |
| 113 | static cl::opt<bool> StressExtLdPromotion( |
| 114 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 115 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 116 | "optimization in CodeGenPrepare")); |
| 117 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 118 | static cl::opt<bool> DisablePreheaderProtect( |
| 119 | "disable-preheader-prot", cl::Hidden, cl::init(false), |
| 120 | cl::desc("Disable protection against removing loop preheaders")); |
| 121 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 122 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 123 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 124 | typedef PointerIntPair<Type *, 1, bool> TypeIsSExt; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 125 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 126 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 127 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 128 | class CodeGenPrepare : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 129 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 130 | const TargetLowering *TLI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 131 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 132 | const TargetLibraryInfo *TLInfo; |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 133 | const LoopInfo *LI; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 134 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 135 | /// As we scan instructions optimizing them, this is the next instruction |
| 136 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 137 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 138 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 139 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 140 | /// This allows us to avoid inserting duplicate code for blocks with |
| 141 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 142 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 143 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 144 | /// Keeps track of all instructions inserted for the current function. |
| 145 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 146 | /// Keeps track of the type of the related instruction before their |
| 147 | /// promotion for the current function. |
| 148 | InstrToOrigTy PromotedInsts; |
| 149 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 150 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 151 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 152 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 153 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 154 | bool OptSize; |
| 155 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 156 | /// DataLayout for the Function being processed. |
| 157 | const DataLayout *DL; |
| 158 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 159 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 160 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 161 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 162 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 163 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 164 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 165 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 166 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 167 | StringRef getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 168 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 169 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 170 | // FIXME: When we can selectively preserve passes, preserve the domtree. |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 171 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 172 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 173 | AU.addRequired<LoopInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 174 | } |
| 175 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 176 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 177 | bool eliminateFallThrough(Function &F); |
| 178 | bool eliminateMostlyEmptyBlocks(Function &F); |
| 179 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 180 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
| 181 | bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 182 | bool optimizeInst(Instruction *I, bool& ModifiedDT); |
| 183 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 184 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 185 | bool optimizeInlineAsmInst(CallInst *CS); |
| 186 | bool optimizeCallInst(CallInst *CI, bool& ModifiedDT); |
| 187 | bool moveExtToFormExtLoad(Instruction *&I); |
| 188 | bool optimizeExtUses(Instruction *I); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 189 | bool optimizeLoadExt(LoadInst *I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 190 | bool optimizeSelectInst(SelectInst *SI); |
| 191 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 192 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 193 | bool optimizeExtractElementInst(Instruction *Inst); |
| 194 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 195 | bool placeDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 196 | bool sinkAndCmp(Function &F); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 197 | bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 198 | Instruction *&Inst, |
| 199 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 200 | unsigned CreatedInstCost); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 201 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 202 | bool simplifyOffsetableRelocate(Instruction &I); |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 203 | void stripInvariantGroupMetadata(Instruction &I); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 204 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 205 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 206 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 207 | char CodeGenPrepare::ID = 0; |
Jiangning Liu | d623c52 | 2014-06-11 07:04:37 +0000 | [diff] [blame] | 208 | INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare", |
| 209 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 210 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 211 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 212 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 213 | } |
| 214 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 215 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 216 | if (skipFunction(F)) |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 217 | return false; |
| 218 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 219 | DL = &F.getParent()->getDataLayout(); |
| 220 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 221 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 222 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 223 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 224 | PromotedInsts.clear(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 225 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 226 | ModifiedDT = false; |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 227 | if (TM) |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 228 | TLI = TM->getSubtargetImpl(F)->getTargetLowering(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 229 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 230 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 231 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 232 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 233 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 234 | /// This optimization identifies DIV instructions that can be |
| 235 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 236 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 237 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 238 | TLI->getBypassSlowDivWidths(); |
Eric Christopher | 49a7d6c | 2016-01-04 23:18:58 +0000 | [diff] [blame] | 239 | BasicBlock* BB = &*F.begin(); |
| 240 | while (BB != nullptr) { |
| 241 | // bypassSlowDivision may create new BBs, but we don't want to reapply the |
| 242 | // optimization to those blocks. |
| 243 | BasicBlock* Next = BB->getNextNode(); |
| 244 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); |
| 245 | BB = Next; |
| 246 | } |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 247 | } |
| 248 | |
| 249 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 250 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 251 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 252 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 253 | // 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] | 254 | // 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] | 255 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 256 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 257 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 258 | // If there is a mask, compare against zero, and branch that can be combined |
| 259 | // into a single target instruction, push the mask and compare into branch |
| 260 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 261 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 262 | if (!DisableBranchOpts) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 263 | EverMadeChange |= sinkAndCmp(F); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 264 | EverMadeChange |= splitBranchCondition(F); |
| 265 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 266 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 267 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 268 | while (MadeChange) { |
| 269 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 270 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 271 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 272 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 273 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 274 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 275 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 276 | if (ModifiedDTOnIteration) |
| 277 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 278 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 279 | EverMadeChange |= MadeChange; |
| 280 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 281 | |
| 282 | SunkAddrs.clear(); |
| 283 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 284 | if (!DisableBranchOpts) { |
| 285 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 286 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 287 | for (BasicBlock &BB : F) { |
| 288 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 289 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 290 | if (!MadeChange) continue; |
| 291 | |
| 292 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 293 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 294 | if (pred_begin(*II) == pred_end(*II)) |
| 295 | WorkList.insert(*II); |
| 296 | } |
| 297 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 298 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 299 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 300 | while (!WorkList.empty()) { |
| 301 | BasicBlock *BB = *WorkList.begin(); |
| 302 | WorkList.erase(BB); |
| 303 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 304 | |
| 305 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 306 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 307 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 308 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 309 | if (pred_begin(*II) == pred_end(*II)) |
| 310 | WorkList.insert(*II); |
| 311 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 312 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 313 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 314 | // a single edge. |
| 315 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 316 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 317 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 318 | EverMadeChange |= MadeChange; |
| 319 | } |
| 320 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 321 | if (!DisableGCOpts) { |
| 322 | SmallVector<Instruction *, 2> Statepoints; |
| 323 | for (BasicBlock &BB : F) |
| 324 | for (Instruction &I : BB) |
| 325 | if (isStatepoint(I)) |
| 326 | Statepoints.push_back(&I); |
| 327 | for (auto &I : Statepoints) |
| 328 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 329 | } |
| 330 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 331 | return EverMadeChange; |
| 332 | } |
| 333 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 334 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 335 | /// basic blocks has a single successor pointing to the other basic block, |
| 336 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 337 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 338 | bool Changed = false; |
| 339 | // 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] | 340 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 341 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 342 | // If the destination block has a single pred, then this is a trivial |
| 343 | // edge, just collapse it. |
| 344 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 345 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 346 | // Don't merge if BB's address is taken. |
| 347 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 348 | |
| 349 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 350 | if (Term && !Term->isConditional()) { |
| 351 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 352 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 353 | // Remember if SinglePred was the entry block of the function. |
| 354 | // If so, we will need to move BB back to the entry position. |
| 355 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 356 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 357 | |
| 358 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 359 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 360 | |
| 361 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 362 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 363 | } |
| 364 | } |
| 365 | return Changed; |
| 366 | } |
| 367 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 368 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 369 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 370 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 371 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 372 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 373 | SmallPtrSet<BasicBlock *, 16> Preheaders; |
| 374 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); |
| 375 | while (!LoopList.empty()) { |
| 376 | Loop *L = LoopList.pop_back_val(); |
| 377 | LoopList.insert(LoopList.end(), L->begin(), L->end()); |
| 378 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 379 | Preheaders.insert(Preheader); |
| 380 | } |
| 381 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 382 | bool MadeChange = false; |
| 383 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 384 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 385 | BasicBlock *BB = &*I++; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 386 | |
| 387 | // If this block doesn't end with an uncond branch, ignore it. |
| 388 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 389 | if (!BI || !BI->isUnconditional()) |
| 390 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 391 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 392 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 393 | // node, then other stuff is happening here. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 394 | BasicBlock::iterator BBI = BI->getIterator(); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 395 | if (BBI != BB->begin()) { |
| 396 | --BBI; |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 397 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 398 | if (BBI == BB->begin()) |
| 399 | break; |
| 400 | --BBI; |
| 401 | } |
| 402 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 403 | continue; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 404 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 405 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 406 | // Do not break infinite loops. |
| 407 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 408 | if (DestBB == BB) |
| 409 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 410 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 411 | if (!canMergeBlocks(BB, DestBB)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 412 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 413 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 414 | // Do not delete loop preheaders if doing so would create a critical edge. |
| 415 | // Loop preheaders can be good locations to spill registers. If the |
| 416 | // preheader is deleted and we create a critical edge, registers may be |
| 417 | // spilled in the loop body instead. |
| 418 | if (!DisablePreheaderProtect && Preheaders.count(BB) && |
| 419 | !(BB->getSinglePredecessor() && BB->getSinglePredecessor()->getSingleSuccessor())) |
| 420 | continue; |
| 421 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 422 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 423 | MadeChange = true; |
| 424 | } |
| 425 | return MadeChange; |
| 426 | } |
| 427 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 428 | /// Return true if we can merge BB into DestBB if there is a single |
| 429 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 430 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 431 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 432 | const BasicBlock *DestBB) const { |
| 433 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 434 | // the successor. If there are more complex condition (e.g. preheaders), |
| 435 | // don't mess around with them. |
| 436 | BasicBlock::const_iterator BBI = BB->begin(); |
| 437 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 438 | for (const User *U : PN->users()) { |
| 439 | const Instruction *UI = cast<Instruction>(U); |
| 440 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 441 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 442 | // If User is inside DestBB block and it is a PHINode then check |
| 443 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 444 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 445 | if (UI->getParent() == DestBB) { |
| 446 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 447 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 448 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 449 | if (Insn && Insn->getParent() == BB && |
| 450 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 451 | return false; |
| 452 | } |
| 453 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 454 | } |
| 455 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 456 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 457 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 458 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 459 | // can't merge the block. |
| 460 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 461 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 462 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 463 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 464 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 465 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 466 | // It is faster to get preds from a PHI than with pred_iterator. |
| 467 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 468 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 469 | } else { |
| 470 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 471 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 472 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 473 | // Walk the preds of DestBB. |
| 474 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 475 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 476 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 477 | BBI = DestBB->begin(); |
| 478 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 479 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 480 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 481 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 482 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 483 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 484 | if (V2PN->getParent() == BB) |
| 485 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 486 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 487 | // If there is a conflict, bail out. |
| 488 | if (V1 != V2) return false; |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | return true; |
| 494 | } |
| 495 | |
| 496 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 497 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 498 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 499 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 500 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 501 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 502 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 503 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 504 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 505 | // If the destination block has a single pred, then this is a trivial edge, |
| 506 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 507 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 508 | if (SinglePred != DestBB) { |
| 509 | // Remember if SinglePred was the entry block of the function. If so, we |
| 510 | // will need to move BB back to the entry position. |
| 511 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 512 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 513 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 514 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 515 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 516 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 517 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 518 | return; |
| 519 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 520 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 521 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 522 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 523 | // to handle the new incoming edges it is about to have. |
| 524 | PHINode *PN; |
| 525 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 526 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 527 | // Remove the incoming value for BB, and remember it. |
| 528 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 529 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 530 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 531 | // value that dominates BB. |
| 532 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 533 | if (InValPhi && InValPhi->getParent() == BB) { |
| 534 | // Add all of the input values of the input PHI as inputs of this phi. |
| 535 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 536 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 537 | InValPhi->getIncomingBlock(i)); |
| 538 | } else { |
| 539 | // Otherwise, add one instance of the dominating value for each edge that |
| 540 | // we will be adding. |
| 541 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 542 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 543 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 544 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 545 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 546 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 547 | } |
| 548 | } |
| 549 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 550 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 551 | // The PHIs are now updated, change everything that refers to BB to use |
| 552 | // DestBB and remove BB. |
| 553 | BB->replaceAllUsesWith(DestBB); |
| 554 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 555 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 556 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 557 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 558 | } |
| 559 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 560 | // Computes a map of base pointer relocation instructions to corresponding |
| 561 | // derived pointer relocation instructions given a vector of all relocate calls |
| 562 | static void computeBaseDerivedRelocateMap( |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 563 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, |
| 564 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> |
| 565 | &RelocateInstMap) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 566 | // Collect information in two maps: one primarily for locating the base object |
| 567 | // while filling the second map; the second map is the final structure holding |
| 568 | // a mapping between Base and corresponding Derived relocate calls |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 569 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; |
| 570 | for (auto *ThisRelocate : AllRelocateCalls) { |
| 571 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), |
| 572 | ThisRelocate->getDerivedPtrIndex()); |
| 573 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 574 | } |
| 575 | for (auto &Item : RelocateIdxMap) { |
| 576 | std::pair<unsigned, unsigned> Key = Item.first; |
| 577 | if (Key.first == Key.second) |
| 578 | // Base relocation: nothing to insert |
| 579 | continue; |
| 580 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 581 | GCRelocateInst *I = Item.second; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 582 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 583 | |
| 584 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 585 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 586 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 587 | // TODO: We might want to insert a new base object relocate and gep off |
| 588 | // that, if there are enough derived object relocates. |
| 589 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 590 | |
| 591 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 592 | } |
| 593 | } |
| 594 | |
| 595 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 596 | // small integer constants |
| 597 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 598 | SmallVectorImpl<Value *> &OffsetV) { |
| 599 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 600 | // Only accept small constant integer operands |
| 601 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 602 | if (!Op || Op->getZExtValue() > 20) |
| 603 | return false; |
| 604 | } |
| 605 | |
| 606 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 607 | OffsetV.push_back(GEP->getOperand(i)); |
| 608 | return true; |
| 609 | } |
| 610 | |
| 611 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 612 | // replace, computes a replacement, and affects it. |
| 613 | static bool |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 614 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, |
| 615 | const SmallVectorImpl<GCRelocateInst *> &Targets) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 616 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 617 | for (GCRelocateInst *ToReplace : Targets) { |
| 618 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 619 | "Not relocating a derived object of the original base object"); |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 620 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 621 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 622 | continue; |
| 623 | } |
| 624 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 625 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 626 | // Base and derived relocates are in different basic blocks. |
| 627 | // In this case transform is only valid when base dominates derived |
| 628 | // relocate. However it would be too expensive to check dominance |
| 629 | // for each such relocate, so we skip the whole transformation. |
| 630 | continue; |
| 631 | } |
| 632 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 633 | Value *Base = ToReplace->getBasePtr(); |
| 634 | auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 635 | if (!Derived || Derived->getPointerOperand() != Base) |
| 636 | continue; |
| 637 | |
| 638 | SmallVector<Value *, 2> OffsetV; |
| 639 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 640 | continue; |
| 641 | |
| 642 | // Create a Builder and replace the target callsite with a gep |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 643 | assert(RelocatedBase->getNextNode() && |
| 644 | "Should always have one since it's not a terminator"); |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 645 | |
| 646 | // Insert after RelocatedBase |
| 647 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 648 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 649 | |
| 650 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 651 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 652 | // match, and we should reuse it to get the derived pointer. But it could be |
| 653 | // cases like this: |
| 654 | // bb1: |
| 655 | // ... |
| 656 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 657 | // br label %merge |
| 658 | // |
| 659 | // bb2: |
| 660 | // ... |
| 661 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 662 | // br label %merge |
| 663 | // |
| 664 | // merge: |
| 665 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 666 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 667 | // |
| 668 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 669 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 670 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 671 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 672 | if (RelocatedBase->getType() != Base->getType()) { |
| 673 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 674 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 675 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 676 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 677 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 678 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 679 | // If the newly generated derived pointer's type does not match the original derived |
| 680 | // pointer's type, cast the new derived pointer to match it. Same reasoning as above. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 681 | Value *ActualReplacement = Replacement; |
| 682 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 683 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 684 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 685 | } |
| 686 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 687 | ToReplace->eraseFromParent(); |
| 688 | |
| 689 | MadeChange = true; |
| 690 | } |
| 691 | return MadeChange; |
| 692 | } |
| 693 | |
| 694 | // Turns this: |
| 695 | // |
| 696 | // %base = ... |
| 697 | // %ptr = gep %base + 15 |
| 698 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 699 | // %base' = relocate(%tok, i32 4, i32 4) |
| 700 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 701 | // %val = load %ptr' |
| 702 | // |
| 703 | // into this: |
| 704 | // |
| 705 | // %base = ... |
| 706 | // %ptr = gep %base + 15 |
| 707 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 708 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 709 | // %ptr' = gep %base' + 15 |
| 710 | // %val = load %ptr' |
| 711 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 712 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 713 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 714 | |
| 715 | for (auto *U : I.users()) |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 716 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 717 | // Collect all the relocate calls associated with a statepoint |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 718 | AllRelocateCalls.push_back(Relocate); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 719 | |
| 720 | // We need atleast one base pointer relocation + one derived pointer |
| 721 | // relocation to mangle |
| 722 | if (AllRelocateCalls.size() < 2) |
| 723 | return false; |
| 724 | |
| 725 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 726 | // corresponding derived relocate instructions |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 727 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 728 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 729 | if (RelocateInstMap.empty()) |
| 730 | return false; |
| 731 | |
| 732 | for (auto &Item : RelocateInstMap) |
| 733 | // Item.first is the RelocatedBase to offset against |
| 734 | // Item.second is the vector of Targets to replace |
| 735 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 736 | return MadeChange; |
| 737 | } |
| 738 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 739 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 740 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 741 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 742 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 743 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 744 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
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 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 747 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 748 | UI != E; ) { |
| 749 | Use &TheUse = UI.getUse(); |
| 750 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 751 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 752 | // Figure out which BB this cast is used in. For PHI's this is the |
| 753 | // appropriate predecessor block. |
| 754 | BasicBlock *UserBB = User->getParent(); |
| 755 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 756 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 757 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 758 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 759 | // Preincrement use iterator so we don't invalidate it. |
| 760 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 761 | |
David Majnemer | 0c80e2e | 2016-04-27 19:36:38 +0000 | [diff] [blame] | 762 | // The first insertion point of a block containing an EH pad is after the |
| 763 | // pad. If the pad is the user, we cannot sink the cast past the pad. |
| 764 | if (User->isEHPad()) |
| 765 | continue; |
| 766 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 767 | // If the block selected to receive the cast is an EH pad that does not |
| 768 | // allow non-PHI instructions before the terminator, we can't sink the |
| 769 | // cast. |
| 770 | if (UserBB->getTerminator()->isEHPad()) |
| 771 | continue; |
| 772 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 773 | // If this user is in the same block as the cast, don't change the cast. |
| 774 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 775 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 776 | // If we have already inserted a cast into this block, use it. |
| 777 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 778 | |
| 779 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 780 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 781 | assert(InsertPt != UserBB->end()); |
| 782 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 783 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 784 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 785 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 786 | // 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] | 787 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 788 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 789 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 790 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 791 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 792 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 793 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 794 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 795 | MadeChange = true; |
| 796 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 797 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 798 | return MadeChange; |
| 799 | } |
| 800 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 801 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 802 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 803 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 804 | /// |
| 805 | /// Return true if any changes are made. |
| 806 | /// |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 807 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 808 | const DataLayout &DL) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 809 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 810 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 811 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 812 | |
| 813 | // This is an fp<->int conversion? |
| 814 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 815 | return false; |
| 816 | |
| 817 | // If this is an extension, it will be a zero or sign extension, which |
| 818 | // isn't a noop. |
| 819 | if (SrcVT.bitsLT(DstVT)) return false; |
| 820 | |
| 821 | // If these values will be promoted, find out what they will be promoted |
| 822 | // to. This helps us consider truncates on PPC as noop copies when they |
| 823 | // are. |
| 824 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 825 | TargetLowering::TypePromoteInteger) |
| 826 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 827 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 828 | TargetLowering::TypePromoteInteger) |
| 829 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 830 | |
| 831 | // If, after promotion, these are the same types, this is a noop copy. |
| 832 | if (SrcVT != DstVT) |
| 833 | return false; |
| 834 | |
| 835 | return SinkCast(CI); |
| 836 | } |
| 837 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 838 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 839 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 840 | /// |
| 841 | /// Return true if any changes were made. |
| 842 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 843 | Value *A, *B; |
| 844 | Instruction *AddI; |
| 845 | if (!match(CI, |
| 846 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 847 | return false; |
| 848 | |
| 849 | Type *Ty = AddI->getType(); |
| 850 | if (!isa<IntegerType>(Ty)) |
| 851 | return false; |
| 852 | |
| 853 | // We don't want to move around uses of condition values this late, so we we |
| 854 | // check if it is legal to create the call to the intrinsic in the basic |
| 855 | // block containing the icmp: |
| 856 | |
| 857 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 858 | return false; |
| 859 | |
| 860 | #ifndef NDEBUG |
| 861 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 862 | // for now: |
| 863 | if (AddI->hasOneUse()) |
| 864 | assert(*AddI->user_begin() == CI && "expected!"); |
| 865 | #endif |
| 866 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 867 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 868 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 869 | |
| 870 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 871 | |
| 872 | auto *UAddWithOverflow = |
| 873 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 874 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 875 | auto *Overflow = |
| 876 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 877 | |
| 878 | CI->replaceAllUsesWith(Overflow); |
| 879 | AddI->replaceAllUsesWith(UAdd); |
| 880 | CI->eraseFromParent(); |
| 881 | AddI->eraseFromParent(); |
| 882 | return true; |
| 883 | } |
| 884 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 885 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 886 | /// registers that must be created and coalesced. This is a clear win except on |
| 887 | /// targets with multiple condition code registers (PowerPC), where it might |
| 888 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 889 | /// |
| 890 | /// Return true if any changes are made. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 891 | static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 892 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 893 | |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 894 | // Avoid sinking soft-FP comparisons, since this can move them into a loop. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 895 | if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI)) |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 896 | return false; |
| 897 | |
| 898 | // Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 899 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 900 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 901 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 902 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 903 | UI != E; ) { |
| 904 | Use &TheUse = UI.getUse(); |
| 905 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 906 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 907 | // Preincrement use iterator so we don't invalidate it. |
| 908 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 909 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 910 | // Don't bother for PHI nodes. |
| 911 | if (isa<PHINode>(User)) |
| 912 | continue; |
| 913 | |
| 914 | // Figure out which BB this cmp is used in. |
| 915 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 916 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 917 | // If this user is in the same block as the cmp, don't change the cmp. |
| 918 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 919 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 920 | // If we have already inserted a cmp into this block, use it. |
| 921 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 922 | |
| 923 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 924 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 925 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 926 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 927 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 928 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Wolfgang Pieb | e51bede | 2016-10-06 21:43:45 +0000 | [diff] [blame^] | 929 | // Propagate the debug info. |
| 930 | InsertedCmp->setDebugLoc(CI->getDebugLoc()); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 931 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 932 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 933 | // Replace a use of the cmp with a use of the new cmp. |
| 934 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 935 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 936 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 937 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 938 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 939 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 940 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 941 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 942 | MadeChange = true; |
| 943 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 944 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 945 | return MadeChange; |
| 946 | } |
| 947 | |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 948 | static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 949 | if (SinkCmpExpression(CI, TLI)) |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 950 | return true; |
| 951 | |
| 952 | if (CombineUAddWithOverflow(CI)) |
| 953 | return true; |
| 954 | |
| 955 | return false; |
| 956 | } |
| 957 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 958 | /// Check if the candidates could be combined with a shift instruction, which |
| 959 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 960 | /// 1. Truncate instruction |
| 961 | /// 2. And instruction and the imm is a mask of the low bits: |
| 962 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 963 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 964 | if (!isa<TruncInst>(User)) { |
| 965 | if (User->getOpcode() != Instruction::And || |
| 966 | !isa<ConstantInt>(User->getOperand(1))) |
| 967 | return false; |
| 968 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 969 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 970 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 971 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 972 | return false; |
| 973 | } |
| 974 | return true; |
| 975 | } |
| 976 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 977 | /// Sink both shift and truncate instruction to the use of truncate's BB. |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 978 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 979 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 980 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 981 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 982 | BasicBlock *UserBB = User->getParent(); |
| 983 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 984 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 985 | bool MadeChange = false; |
| 986 | |
| 987 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 988 | TruncE = TruncI->user_end(); |
| 989 | TruncUI != TruncE;) { |
| 990 | |
| 991 | Use &TruncTheUse = TruncUI.getUse(); |
| 992 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 993 | // Preincrement use iterator so we don't invalidate it. |
| 994 | |
| 995 | ++TruncUI; |
| 996 | |
| 997 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 998 | if (!ISDOpcode) |
| 999 | continue; |
| 1000 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 1001 | // If the use is actually a legal node, there will not be an |
| 1002 | // implicit truncate. |
| 1003 | // FIXME: always querying the result type is just an |
| 1004 | // approximation; some nodes' legality is determined by the |
| 1005 | // 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] | 1006 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1007 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1008 | continue; |
| 1009 | |
| 1010 | // Don't bother for PHI nodes. |
| 1011 | if (isa<PHINode>(TruncUser)) |
| 1012 | continue; |
| 1013 | |
| 1014 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 1015 | |
| 1016 | if (UserBB == TruncUserBB) |
| 1017 | continue; |
| 1018 | |
| 1019 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 1020 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 1021 | |
| 1022 | if (!InsertedShift && !InsertedTrunc) { |
| 1023 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1024 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1025 | // Sink the shift |
| 1026 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1027 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1028 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1029 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1030 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1031 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1032 | |
| 1033 | // Sink the trunc |
| 1034 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 1035 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1036 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1037 | |
| 1038 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1039 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1040 | |
| 1041 | MadeChange = true; |
| 1042 | |
| 1043 | TruncTheUse = InsertedTrunc; |
| 1044 | } |
| 1045 | } |
| 1046 | return MadeChange; |
| 1047 | } |
| 1048 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1049 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1050 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1051 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1052 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1053 | /// BB1: |
| 1054 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1055 | /// BB2: |
| 1056 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1057 | /// ==> |
| 1058 | /// |
| 1059 | /// BB2: |
| 1060 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1061 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1062 | /// |
| 1063 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1064 | /// instruction. |
| 1065 | /// Return true if any changes are made. |
| 1066 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1067 | const TargetLowering &TLI, |
| 1068 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1069 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1070 | |
| 1071 | /// Only insert instructions in each block once. |
| 1072 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1073 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1074 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1075 | |
| 1076 | bool MadeChange = false; |
| 1077 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1078 | UI != E;) { |
| 1079 | Use &TheUse = UI.getUse(); |
| 1080 | Instruction *User = cast<Instruction>(*UI); |
| 1081 | // Preincrement use iterator so we don't invalidate it. |
| 1082 | ++UI; |
| 1083 | |
| 1084 | // Don't bother for PHI nodes. |
| 1085 | if (isa<PHINode>(User)) |
| 1086 | continue; |
| 1087 | |
| 1088 | if (!isExtractBitsCandidateUse(User)) |
| 1089 | continue; |
| 1090 | |
| 1091 | BasicBlock *UserBB = User->getParent(); |
| 1092 | |
| 1093 | if (UserBB == DefBB) { |
| 1094 | // If the shift and truncate instruction are in the same BB. The use of |
| 1095 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1096 | // legal. In this case, we would like to sink both shift and truncate |
| 1097 | // instruction to the BB of TruncUse. |
| 1098 | // for example: |
| 1099 | // BB1: |
| 1100 | // i64 shift.result = lshr i64 opnd, imm |
| 1101 | // trunc.result = trunc shift.result to i16 |
| 1102 | // |
| 1103 | // BB2: |
| 1104 | // ----> We will have an implicit truncate here if the architecture does |
| 1105 | // not have i16 compare. |
| 1106 | // cmp i16 trunc.result, opnd2 |
| 1107 | // |
| 1108 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1109 | // If the type of the truncate is legal, no trucate will be |
| 1110 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1111 | && |
| 1112 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1113 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1114 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1115 | |
| 1116 | continue; |
| 1117 | } |
| 1118 | // If we have already inserted a shift into this block, use it. |
| 1119 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1120 | |
| 1121 | if (!InsertedShift) { |
| 1122 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1123 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1124 | |
| 1125 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1126 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1127 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1128 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1129 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1130 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1131 | |
| 1132 | MadeChange = true; |
| 1133 | } |
| 1134 | |
| 1135 | // Replace a use of the shift with a use of the new shift. |
| 1136 | TheUse = InsertedShift; |
| 1137 | } |
| 1138 | |
| 1139 | // If we removed all uses, nuke the shift. |
| 1140 | if (ShiftI->use_empty()) |
| 1141 | ShiftI->eraseFromParent(); |
| 1142 | |
| 1143 | return MadeChange; |
| 1144 | } |
| 1145 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1146 | // Translate a masked load intrinsic like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1147 | // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, |
| 1148 | // <16 x i1> %mask, <16 x i32> %passthru) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1149 | // to a chain of basic blocks, with loading element one-by-one if |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1150 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1151 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1152 | // %1 = bitcast i8* %addr to i32* |
| 1153 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1154 | // %3 = icmp eq i1 %2, true |
| 1155 | // br i1 %3, label %cond.load, label %else |
| 1156 | // |
| 1157 | //cond.load: ; preds = %0 |
| 1158 | // %4 = getelementptr i32* %1, i32 0 |
| 1159 | // %5 = load i32* %4 |
| 1160 | // %6 = insertelement <16 x i32> undef, i32 %5, i32 0 |
| 1161 | // br label %else |
| 1162 | // |
| 1163 | //else: ; preds = %0, %cond.load |
| 1164 | // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] |
| 1165 | // %7 = extractelement <16 x i1> %mask, i32 1 |
| 1166 | // %8 = icmp eq i1 %7, true |
| 1167 | // br i1 %8, label %cond.load1, label %else2 |
| 1168 | // |
| 1169 | //cond.load1: ; preds = %else |
| 1170 | // %9 = getelementptr i32* %1, i32 1 |
| 1171 | // %10 = load i32* %9 |
| 1172 | // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 |
| 1173 | // br label %else2 |
| 1174 | // |
| 1175 | //else2: ; preds = %else, %cond.load1 |
| 1176 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1177 | // %12 = extractelement <16 x i1> %mask, i32 2 |
| 1178 | // %13 = icmp eq i1 %12, true |
| 1179 | // br i1 %13, label %cond.load4, label %else5 |
| 1180 | // |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1181 | static void scalarizeMaskedLoad(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1182 | Value *Ptr = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1183 | Value *Alignment = CI->getArgOperand(1); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1184 | Value *Mask = CI->getArgOperand(2); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1185 | Value *Src0 = CI->getArgOperand(3); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1186 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1187 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1188 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1189 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1190 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1191 | Type *EltTy = CI->getType()->getVectorElementType(); |
| 1192 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1193 | IRBuilder<> Builder(CI->getContext()); |
| 1194 | Instruction *InsertPt = CI; |
| 1195 | BasicBlock *IfBlock = CI->getParent(); |
| 1196 | BasicBlock *CondBlock = nullptr; |
| 1197 | BasicBlock *PrevIfBlock = CI->getParent(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1198 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1199 | Builder.SetInsertPoint(InsertPt); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1200 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1201 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1202 | // Short-cut if the mask is all-true. |
| 1203 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1204 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1205 | |
| 1206 | if (IsAllOnesMask) { |
| 1207 | Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); |
| 1208 | CI->replaceAllUsesWith(NewI); |
| 1209 | CI->eraseFromParent(); |
| 1210 | return; |
| 1211 | } |
| 1212 | |
| 1213 | // Adjust alignment for the scalar instruction. |
| 1214 | AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1215 | // Bitcast %addr fron i8* to EltTy* |
| 1216 | Type *NewPtrType = |
| 1217 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1218 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1219 | unsigned VectorWidth = VecType->getNumElements(); |
| 1220 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1221 | Value *UndefVal = UndefValue::get(VecType); |
| 1222 | |
| 1223 | // The result vector |
| 1224 | Value *VResult = UndefVal; |
| 1225 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1226 | if (isa<ConstantVector>(Mask)) { |
| 1227 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1228 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1229 | continue; |
| 1230 | Value *Gep = |
| 1231 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1232 | LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
| 1233 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1234 | Builder.getInt32(Idx)); |
| 1235 | } |
| 1236 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1237 | CI->replaceAllUsesWith(NewI); |
| 1238 | CI->eraseFromParent(); |
| 1239 | return; |
| 1240 | } |
| 1241 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1242 | PHINode *Phi = nullptr; |
| 1243 | Value *PrevPhi = UndefVal; |
| 1244 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1245 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1246 | |
| 1247 | // Fill the "else" block, created in the previous iteration |
| 1248 | // |
| 1249 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1250 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1251 | // %to_load = icmp eq i1 %mask_1, true |
| 1252 | // br i1 %to_load, label %cond.load, label %else |
| 1253 | // |
| 1254 | if (Idx > 0) { |
| 1255 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1256 | Phi->addIncoming(VResult, CondBlock); |
| 1257 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1258 | PrevPhi = Phi; |
| 1259 | VResult = Phi; |
| 1260 | } |
| 1261 | |
| 1262 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1263 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1264 | ConstantInt::get(Predicate->getType(), 1)); |
| 1265 | |
| 1266 | // Create "cond" block |
| 1267 | // |
| 1268 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1269 | // %Elt = load i32* %EltAddr |
| 1270 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1271 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1272 | CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1273 | Builder.SetInsertPoint(InsertPt); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1274 | |
| 1275 | Value *Gep = |
| 1276 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1277 | LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1278 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); |
| 1279 | |
| 1280 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1281 | BasicBlock *NewIfBlock = |
| 1282 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1283 | Builder.SetInsertPoint(InsertPt); |
| 1284 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1285 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1286 | OldBr->eraseFromParent(); |
| 1287 | PrevIfBlock = IfBlock; |
| 1288 | IfBlock = NewIfBlock; |
| 1289 | } |
| 1290 | |
| 1291 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1292 | Phi->addIncoming(VResult, CondBlock); |
| 1293 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1294 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1295 | CI->replaceAllUsesWith(NewI); |
| 1296 | CI->eraseFromParent(); |
| 1297 | } |
| 1298 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1299 | // Translate a masked store intrinsic, like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1300 | // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, |
| 1301 | // <16 x i1> %mask) |
| 1302 | // to a chain of basic blocks, that stores element one-by-one if |
| 1303 | // the appropriate mask bit is set |
| 1304 | // |
| 1305 | // %1 = bitcast i8* %addr to i32* |
| 1306 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1307 | // %3 = icmp eq i1 %2, true |
| 1308 | // br i1 %3, label %cond.store, label %else |
| 1309 | // |
| 1310 | // cond.store: ; preds = %0 |
| 1311 | // %4 = extractelement <16 x i32> %val, i32 0 |
| 1312 | // %5 = getelementptr i32* %1, i32 0 |
| 1313 | // store i32 %4, i32* %5 |
| 1314 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1315 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1316 | // else: ; preds = %0, %cond.store |
| 1317 | // %6 = extractelement <16 x i1> %mask, i32 1 |
| 1318 | // %7 = icmp eq i1 %6, true |
| 1319 | // br i1 %7, label %cond.store1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1320 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1321 | // cond.store1: ; preds = %else |
| 1322 | // %8 = extractelement <16 x i32> %val, i32 1 |
| 1323 | // %9 = getelementptr i32* %1, i32 1 |
| 1324 | // store i32 %8, i32* %9 |
| 1325 | // br label %else2 |
| 1326 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1327 | static void scalarizeMaskedStore(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1328 | Value *Src = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1329 | Value *Ptr = CI->getArgOperand(1); |
| 1330 | Value *Alignment = CI->getArgOperand(2); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1331 | Value *Mask = CI->getArgOperand(3); |
| 1332 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1333 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1334 | VectorType *VecType = dyn_cast<VectorType>(Src->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1335 | assert(VecType && "Unexpected data type in masked store intrinsic"); |
| 1336 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1337 | Type *EltTy = VecType->getElementType(); |
| 1338 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1339 | IRBuilder<> Builder(CI->getContext()); |
| 1340 | Instruction *InsertPt = CI; |
| 1341 | BasicBlock *IfBlock = CI->getParent(); |
| 1342 | Builder.SetInsertPoint(InsertPt); |
| 1343 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1344 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1345 | // Short-cut if the mask is all-true. |
| 1346 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1347 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1348 | |
| 1349 | if (IsAllOnesMask) { |
| 1350 | Builder.CreateAlignedStore(Src, Ptr, AlignVal); |
| 1351 | CI->eraseFromParent(); |
| 1352 | return; |
| 1353 | } |
| 1354 | |
| 1355 | // Adjust alignment for the scalar instruction. |
| 1356 | AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1357 | // Bitcast %addr fron i8* to EltTy* |
| 1358 | Type *NewPtrType = |
| 1359 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1360 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1361 | unsigned VectorWidth = VecType->getNumElements(); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1362 | |
| 1363 | if (isa<ConstantVector>(Mask)) { |
| 1364 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1365 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1366 | continue; |
| 1367 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
| 1368 | Value *Gep = |
| 1369 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1370 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
| 1371 | } |
| 1372 | CI->eraseFromParent(); |
| 1373 | return; |
| 1374 | } |
| 1375 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1376 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1377 | |
| 1378 | // Fill the "else" block, created in the previous iteration |
| 1379 | // |
| 1380 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1381 | // %to_store = icmp eq i1 %mask_1, true |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1382 | // br i1 %to_store, label %cond.store, label %else |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1383 | // |
| 1384 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1385 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1386 | ConstantInt::get(Predicate->getType(), 1)); |
| 1387 | |
| 1388 | // Create "cond" block |
| 1389 | // |
| 1390 | // %OneElt = extractelement <16 x i32> %Src, i32 Idx |
| 1391 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1392 | // %store i32 %OneElt, i32* %EltAddr |
| 1393 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1394 | BasicBlock *CondBlock = |
| 1395 | IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1396 | Builder.SetInsertPoint(InsertPt); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1397 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1398 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1399 | Value *Gep = |
| 1400 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1401 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1402 | |
| 1403 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1404 | BasicBlock *NewIfBlock = |
| 1405 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1406 | Builder.SetInsertPoint(InsertPt); |
| 1407 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1408 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1409 | OldBr->eraseFromParent(); |
| 1410 | IfBlock = NewIfBlock; |
| 1411 | } |
| 1412 | CI->eraseFromParent(); |
| 1413 | } |
| 1414 | |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1415 | // Translate a masked gather intrinsic like |
| 1416 | // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, |
| 1417 | // <16 x i1> %Mask, <16 x i32> %Src) |
| 1418 | // to a chain of basic blocks, with loading element one-by-one if |
| 1419 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1420 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1421 | // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind |
| 1422 | // % Mask0 = extractelement <16 x i1> %Mask, i32 0 |
| 1423 | // % ToLoad0 = icmp eq i1 % Mask0, true |
| 1424 | // br i1 % ToLoad0, label %cond.load, label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1425 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1426 | // cond.load: |
| 1427 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1428 | // % Load0 = load i32, i32* % Ptr0, align 4 |
| 1429 | // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 |
| 1430 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1431 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1432 | // else: |
| 1433 | // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] |
| 1434 | // % Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1435 | // % ToLoad1 = icmp eq i1 % Mask1, true |
| 1436 | // br i1 % ToLoad1, label %cond.load1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1437 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1438 | // cond.load1: |
| 1439 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1440 | // % Load1 = load i32, i32* % Ptr1, align 4 |
| 1441 | // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 |
| 1442 | // br label %else2 |
| 1443 | // . . . |
| 1444 | // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src |
| 1445 | // ret <16 x i32> %Result |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1446 | static void scalarizeMaskedGather(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1447 | Value *Ptrs = CI->getArgOperand(0); |
| 1448 | Value *Alignment = CI->getArgOperand(1); |
| 1449 | Value *Mask = CI->getArgOperand(2); |
| 1450 | Value *Src0 = CI->getArgOperand(3); |
| 1451 | |
| 1452 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
| 1453 | |
| 1454 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1455 | |
| 1456 | IRBuilder<> Builder(CI->getContext()); |
| 1457 | Instruction *InsertPt = CI; |
| 1458 | BasicBlock *IfBlock = CI->getParent(); |
| 1459 | BasicBlock *CondBlock = nullptr; |
| 1460 | BasicBlock *PrevIfBlock = CI->getParent(); |
| 1461 | Builder.SetInsertPoint(InsertPt); |
| 1462 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1463 | |
| 1464 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1465 | |
| 1466 | Value *UndefVal = UndefValue::get(VecType); |
| 1467 | |
| 1468 | // The result vector |
| 1469 | Value *VResult = UndefVal; |
| 1470 | unsigned VectorWidth = VecType->getNumElements(); |
| 1471 | |
| 1472 | // Shorten the way if the mask is a vector of constants. |
| 1473 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1474 | |
| 1475 | if (IsConstMask) { |
| 1476 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1477 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1478 | continue; |
| 1479 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1480 | "Ptr" + Twine(Idx)); |
| 1481 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1482 | "Load" + Twine(Idx)); |
| 1483 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1484 | Builder.getInt32(Idx), |
| 1485 | "Res" + Twine(Idx)); |
| 1486 | } |
| 1487 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1488 | CI->replaceAllUsesWith(NewI); |
| 1489 | CI->eraseFromParent(); |
| 1490 | return; |
| 1491 | } |
| 1492 | |
| 1493 | PHINode *Phi = nullptr; |
| 1494 | Value *PrevPhi = UndefVal; |
| 1495 | |
| 1496 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1497 | |
| 1498 | // Fill the "else" block, created in the previous iteration |
| 1499 | // |
| 1500 | // %Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1501 | // %ToLoad1 = icmp eq i1 %Mask1, true |
| 1502 | // br i1 %ToLoad1, label %cond.load, label %else |
| 1503 | // |
| 1504 | if (Idx > 0) { |
| 1505 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1506 | Phi->addIncoming(VResult, CondBlock); |
| 1507 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1508 | PrevPhi = Phi; |
| 1509 | VResult = Phi; |
| 1510 | } |
| 1511 | |
| 1512 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1513 | Builder.getInt32(Idx), |
| 1514 | "Mask" + Twine(Idx)); |
| 1515 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1516 | ConstantInt::get(Predicate->getType(), 1), |
| 1517 | "ToLoad" + Twine(Idx)); |
| 1518 | |
| 1519 | // Create "cond" block |
| 1520 | // |
| 1521 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1522 | // %Elt = load i32* %EltAddr |
| 1523 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1524 | // |
| 1525 | CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); |
| 1526 | Builder.SetInsertPoint(InsertPt); |
| 1527 | |
| 1528 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1529 | "Ptr" + Twine(Idx)); |
| 1530 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1531 | "Load" + Twine(Idx)); |
| 1532 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), |
| 1533 | "Res" + Twine(Idx)); |
| 1534 | |
| 1535 | // Create "else" block, fill it in the next iteration |
| 1536 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1537 | Builder.SetInsertPoint(InsertPt); |
| 1538 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1539 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1540 | OldBr->eraseFromParent(); |
| 1541 | PrevIfBlock = IfBlock; |
| 1542 | IfBlock = NewIfBlock; |
| 1543 | } |
| 1544 | |
| 1545 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1546 | Phi->addIncoming(VResult, CondBlock); |
| 1547 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1548 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1549 | CI->replaceAllUsesWith(NewI); |
| 1550 | CI->eraseFromParent(); |
| 1551 | } |
| 1552 | |
| 1553 | // Translate a masked scatter intrinsic, like |
| 1554 | // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, |
| 1555 | // <16 x i1> %Mask) |
| 1556 | // to a chain of basic blocks, that stores element one-by-one if |
| 1557 | // the appropriate mask bit is set. |
| 1558 | // |
| 1559 | // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind |
| 1560 | // % Mask0 = extractelement <16 x i1> % Mask, i32 0 |
| 1561 | // % ToStore0 = icmp eq i1 % Mask0, true |
| 1562 | // br i1 %ToStore0, label %cond.store, label %else |
| 1563 | // |
| 1564 | // cond.store: |
| 1565 | // % Elt0 = extractelement <16 x i32> %Src, i32 0 |
| 1566 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1567 | // store i32 %Elt0, i32* % Ptr0, align 4 |
| 1568 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1569 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1570 | // else: |
| 1571 | // % Mask1 = extractelement <16 x i1> % Mask, i32 1 |
| 1572 | // % ToStore1 = icmp eq i1 % Mask1, true |
| 1573 | // br i1 % ToStore1, label %cond.store1, label %else2 |
| 1574 | // |
| 1575 | // cond.store1: |
| 1576 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1577 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1578 | // store i32 % Elt1, i32* % Ptr1, align 4 |
| 1579 | // br label %else2 |
| 1580 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1581 | static void scalarizeMaskedScatter(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1582 | Value *Src = CI->getArgOperand(0); |
| 1583 | Value *Ptrs = CI->getArgOperand(1); |
| 1584 | Value *Alignment = CI->getArgOperand(2); |
| 1585 | Value *Mask = CI->getArgOperand(3); |
| 1586 | |
| 1587 | assert(isa<VectorType>(Src->getType()) && |
| 1588 | "Unexpected data type in masked scatter intrinsic"); |
| 1589 | assert(isa<VectorType>(Ptrs->getType()) && |
| 1590 | isa<PointerType>(Ptrs->getType()->getVectorElementType()) && |
| 1591 | "Vector of pointers is expected in masked scatter intrinsic"); |
| 1592 | |
| 1593 | IRBuilder<> Builder(CI->getContext()); |
| 1594 | Instruction *InsertPt = CI; |
| 1595 | BasicBlock *IfBlock = CI->getParent(); |
| 1596 | Builder.SetInsertPoint(InsertPt); |
| 1597 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1598 | |
| 1599 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1600 | unsigned VectorWidth = Src->getType()->getVectorNumElements(); |
| 1601 | |
| 1602 | // Shorten the way if the mask is a vector of constants. |
| 1603 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1604 | |
| 1605 | if (IsConstMask) { |
| 1606 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1607 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1608 | continue; |
| 1609 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1610 | "Elt" + Twine(Idx)); |
| 1611 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1612 | "Ptr" + Twine(Idx)); |
| 1613 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1614 | } |
| 1615 | CI->eraseFromParent(); |
| 1616 | return; |
| 1617 | } |
| 1618 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1619 | // Fill the "else" block, created in the previous iteration |
| 1620 | // |
| 1621 | // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx |
| 1622 | // % ToStore = icmp eq i1 % Mask1, true |
| 1623 | // br i1 % ToStore, label %cond.store, label %else |
| 1624 | // |
| 1625 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1626 | Builder.getInt32(Idx), |
| 1627 | "Mask" + Twine(Idx)); |
| 1628 | Value *Cmp = |
| 1629 | Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1630 | ConstantInt::get(Predicate->getType(), 1), |
| 1631 | "ToStore" + Twine(Idx)); |
| 1632 | |
| 1633 | // Create "cond" block |
| 1634 | // |
| 1635 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1636 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1637 | // %store i32 % Elt1, i32* % Ptr1 |
| 1638 | // |
| 1639 | BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); |
| 1640 | Builder.SetInsertPoint(InsertPt); |
| 1641 | |
| 1642 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1643 | "Elt" + Twine(Idx)); |
| 1644 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1645 | "Ptr" + Twine(Idx)); |
| 1646 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1647 | |
| 1648 | // Create "else" block, fill it in the next iteration |
| 1649 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1650 | Builder.SetInsertPoint(InsertPt); |
| 1651 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1652 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1653 | OldBr->eraseFromParent(); |
| 1654 | IfBlock = NewIfBlock; |
| 1655 | } |
| 1656 | CI->eraseFromParent(); |
| 1657 | } |
| 1658 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1659 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 1660 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 1661 | /// |
| 1662 | /// We want to transform: |
| 1663 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 1664 | /// |
| 1665 | /// into: |
| 1666 | /// entry: |
| 1667 | /// %cmpz = icmp eq i64 %A, 0 |
| 1668 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 1669 | /// cond.false: |
| 1670 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 1671 | /// br label %cond.end |
| 1672 | /// cond.end: |
| 1673 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 1674 | /// |
| 1675 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 1676 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 1677 | const TargetLowering *TLI, |
| 1678 | const DataLayout *DL, |
| 1679 | bool &ModifiedDT) { |
| 1680 | if (!TLI || !DL) |
| 1681 | return false; |
| 1682 | |
| 1683 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 1684 | if (match(CountZeros->getOperand(1), m_One())) |
| 1685 | return false; |
| 1686 | |
| 1687 | // If it's cheap to speculate, there's nothing to do. |
| 1688 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 1689 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 1690 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 1691 | return false; |
| 1692 | |
| 1693 | // Only handle legal scalar cases. Anything else requires too much work. |
| 1694 | Type *Ty = CountZeros->getType(); |
| 1695 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 1696 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1697 | return false; |
| 1698 | |
| 1699 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 1700 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 1701 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 1702 | |
| 1703 | // Create another block after the count zero intrinsic. A PHI will be added |
| 1704 | // in this block to select the result of the intrinsic or the bit-width |
| 1705 | // constant if the input to the intrinsic is zero. |
| 1706 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 1707 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 1708 | |
| 1709 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 1710 | IRBuilder<> Builder(CountZeros->getContext()); |
| 1711 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 1712 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 1713 | |
| 1714 | // Replace the unconditional branch that was created by the first split with |
| 1715 | // a compare against zero and a conditional branch. |
| 1716 | Value *Zero = Constant::getNullValue(Ty); |
| 1717 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 1718 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 1719 | StartBlock->getTerminator()->eraseFromParent(); |
| 1720 | |
| 1721 | // Create a PHI in the end block to select either the output of the intrinsic |
| 1722 | // or the bit width of the operand. |
| 1723 | Builder.SetInsertPoint(&EndBlock->front()); |
| 1724 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 1725 | CountZeros->replaceAllUsesWith(PN); |
| 1726 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 1727 | PN->addIncoming(BitWidth, StartBlock); |
| 1728 | PN->addIncoming(CountZeros, CallBlock); |
| 1729 | |
| 1730 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 1731 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 1732 | // intrinsic; we only despeculate when a zero input is defined. |
| 1733 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 1734 | ModifiedDT = true; |
| 1735 | return true; |
| 1736 | } |
| 1737 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1738 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1739 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1740 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1741 | // Lower inline assembly if we can. |
| 1742 | // If we found an inline asm expession, and if the target knows how to |
| 1743 | // lower it to normal LLVM code, do so now. |
| 1744 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 1745 | if (TLI->ExpandInlineAsm(CI)) { |
| 1746 | // Avoid invalidating the iterator. |
| 1747 | CurInstIterator = BB->begin(); |
| 1748 | // Avoid processing instructions out of order, which could cause |
| 1749 | // reuse before a value is defined. |
| 1750 | SunkAddrs.clear(); |
| 1751 | return true; |
| 1752 | } |
| 1753 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1754 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1755 | return true; |
| 1756 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1757 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1758 | // Align the pointer arguments to this call if the target thinks it's a good |
| 1759 | // idea |
| 1760 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1761 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1762 | for (auto &Arg : CI->arg_operands()) { |
| 1763 | // We want to align both objects whose address is used directly and |
| 1764 | // objects whose address is used in casts and GEPs, though it only makes |
| 1765 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 1766 | // if size - offset meets the size threshold. |
| 1767 | if (!Arg->getType()->isPointerTy()) |
| 1768 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1769 | APInt Offset(DL->getPointerSizeInBits( |
| 1770 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 1771 | 0); |
| 1772 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1773 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1774 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 1775 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1776 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1777 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 1778 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1779 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1780 | // Global variables can only be aligned if they are defined in this |
| 1781 | // object (i.e. they are uniquely initialized in this object), and |
| 1782 | // over-aligning global variables that have an explicit section is |
| 1783 | // forbidden. |
| 1784 | GlobalVariable *GV; |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 1785 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && |
Tim Northover | 918f050 | 2016-07-18 18:28:52 +0000 | [diff] [blame] | 1786 | GV->getPointerAlignment(*DL) < PrefAlign && |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 1787 | DL->getTypeAllocSize(GV->getValueType()) >= |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1788 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1789 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1790 | } |
| 1791 | // If this is a memcpy (or similar) then we may be able to improve the |
| 1792 | // alignment |
| 1793 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1794 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1795 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1796 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1797 | if (Align > MI->getAlignment()) |
| 1798 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1799 | } |
| 1800 | } |
| 1801 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 1802 | // If we have a cold call site, try to sink addressing computation into the |
| 1803 | // cold block. This interacts with our handling for loads and stores to |
| 1804 | // ensure that we can fold all uses of a potential addressing computation |
| 1805 | // into their uses. TODO: generalize this to work over profiling data |
| 1806 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 1807 | for (auto &Arg : CI->arg_operands()) { |
| 1808 | if (!Arg->getType()->isPointerTy()) |
| 1809 | continue; |
| 1810 | unsigned AS = Arg->getType()->getPointerAddressSpace(); |
| 1811 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); |
| 1812 | } |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 1813 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1814 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1815 | if (II) { |
| 1816 | switch (II->getIntrinsicID()) { |
| 1817 | default: break; |
| 1818 | case Intrinsic::objectsize: { |
| 1819 | // Lower all uses of llvm.objectsize.* |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 1820 | uint64_t Size; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1821 | Type *ReturnTy = CI->getType(); |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 1822 | Constant *RetVal = nullptr; |
| 1823 | ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1)); |
| 1824 | ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min; |
| 1825 | if (getObjectSize(II->getArgOperand(0), |
| 1826 | Size, *DL, TLInfo, false, Mode)) { |
| 1827 | RetVal = ConstantInt::get(ReturnTy, Size); |
| 1828 | } else { |
| 1829 | RetVal = ConstantInt::get(ReturnTy, |
| 1830 | Mode == ObjSizeMode::Min ? 0 : -1ULL); |
| 1831 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1832 | // Substituting this can cause recursive simplifications, which can |
| 1833 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 1834 | // happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1835 | Value *CurValue = &*CurInstIterator; |
| 1836 | WeakVH IterHandle(CurValue); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1837 | |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 1838 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1839 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1840 | // If the iterator instruction was recursively deleted, start over at the |
| 1841 | // start of the block. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1842 | if (IterHandle != CurValue) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1843 | CurInstIterator = BB->begin(); |
| 1844 | SunkAddrs.clear(); |
| 1845 | } |
| 1846 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 1847 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1848 | case Intrinsic::masked_load: { |
| 1849 | // Scalarize unsupported vector masked load |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1850 | if (!TTI->isLegalMaskedLoad(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1851 | scalarizeMaskedLoad(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1852 | ModifiedDT = true; |
| 1853 | return true; |
| 1854 | } |
| 1855 | return false; |
| 1856 | } |
| 1857 | case Intrinsic::masked_store: { |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1858 | if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1859 | scalarizeMaskedStore(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1860 | ModifiedDT = true; |
| 1861 | return true; |
| 1862 | } |
| 1863 | return false; |
| 1864 | } |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1865 | case Intrinsic::masked_gather: { |
| 1866 | if (!TTI->isLegalMaskedGather(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1867 | scalarizeMaskedGather(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1868 | ModifiedDT = true; |
| 1869 | return true; |
| 1870 | } |
| 1871 | return false; |
| 1872 | } |
| 1873 | case Intrinsic::masked_scatter: { |
| 1874 | if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1875 | scalarizeMaskedScatter(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1876 | ModifiedDT = true; |
| 1877 | return true; |
| 1878 | } |
| 1879 | return false; |
| 1880 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1881 | case Intrinsic::aarch64_stlxr: |
| 1882 | case Intrinsic::aarch64_stxr: { |
| 1883 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 1884 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 1885 | ExtVal->getParent() == CI->getParent()) |
| 1886 | return false; |
| 1887 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 1888 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 1889 | // Mark this instruction as "inserted by CGP", so that other |
| 1890 | // optimizations don't touch it. |
| 1891 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1892 | return true; |
| 1893 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 1894 | case Intrinsic::invariant_group_barrier: |
| 1895 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 1896 | II->eraseFromParent(); |
| 1897 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1898 | |
| 1899 | case Intrinsic::cttz: |
| 1900 | case Intrinsic::ctlz: |
| 1901 | // If counting zeros is expensive, try to avoid it. |
| 1902 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1903 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1904 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1905 | if (TLI) { |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1906 | // Unknown address space. |
| 1907 | // TODO: Target hook to pick which address space the intrinsic cares |
| 1908 | // about? |
| 1909 | unsigned AddrSpace = ~0u; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1910 | SmallVector<Value*, 2> PtrOps; |
| 1911 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1912 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1913 | while (!PtrOps.empty()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1914 | if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1915 | return true; |
| 1916 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 1917 | } |
| 1918 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1919 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1920 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 1921 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 1922 | // Lower all default uses of _chk calls. This is very similar |
| 1923 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1924 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 1925 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1926 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1927 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 1928 | CI->replaceAllUsesWith(V); |
| 1929 | CI->eraseFromParent(); |
| 1930 | return true; |
| 1931 | } |
| 1932 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1933 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1934 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1935 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 1936 | /// to enable tail call optimizations. The case it is currently looking for is: |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1937 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1938 | /// bb0: |
| 1939 | /// %tmp0 = tail call i32 @f0() |
| 1940 | /// br label %return |
| 1941 | /// bb1: |
| 1942 | /// %tmp1 = tail call i32 @f1() |
| 1943 | /// br label %return |
| 1944 | /// bb2: |
| 1945 | /// %tmp2 = tail call i32 @f2() |
| 1946 | /// br label %return |
| 1947 | /// return: |
| 1948 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 1949 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1950 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1951 | /// |
| 1952 | /// => |
| 1953 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1954 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1955 | /// bb0: |
| 1956 | /// %tmp0 = tail call i32 @f0() |
| 1957 | /// ret i32 %tmp0 |
| 1958 | /// bb1: |
| 1959 | /// %tmp1 = tail call i32 @f1() |
| 1960 | /// ret i32 %tmp1 |
| 1961 | /// bb2: |
| 1962 | /// %tmp2 = tail call i32 @f2() |
| 1963 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1964 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1965 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 1966 | if (!TLI) |
| 1967 | return false; |
| 1968 | |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1969 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 1970 | if (!RetI) |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 1971 | return false; |
| 1972 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1973 | PHINode *PN = nullptr; |
| 1974 | BitCastInst *BCI = nullptr; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1975 | Value *V = RetI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1976 | if (V) { |
| 1977 | BCI = dyn_cast<BitCastInst>(V); |
| 1978 | if (BCI) |
| 1979 | V = BCI->getOperand(0); |
| 1980 | |
| 1981 | PN = dyn_cast<PHINode>(V); |
| 1982 | if (!PN) |
| 1983 | return false; |
| 1984 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1985 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1986 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1987 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1988 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1989 | // Make sure there are no instructions between the PHI and return, or that the |
| 1990 | // return is the first instruction in the block. |
| 1991 | if (PN) { |
| 1992 | BasicBlock::iterator BI = BB->begin(); |
| 1993 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1994 | if (&*BI == BCI) |
| 1995 | // Also skip over the bitcast. |
| 1996 | ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1997 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1998 | return false; |
| 1999 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2000 | BasicBlock::iterator BI = BB->begin(); |
| 2001 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2002 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2003 | return false; |
| 2004 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2005 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2006 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 2007 | /// call. |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2008 | const Function *F = BB->getParent(); |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2009 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2010 | if (PN) { |
| 2011 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 2012 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 2013 | // Make sure the phi value is indeed produced by the tail call. |
| 2014 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2015 | TLI->mayBeEmittedAsTailCall(CI) && |
| 2016 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2017 | TailCalls.push_back(CI); |
| 2018 | } |
| 2019 | } else { |
| 2020 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2021 | 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] | 2022 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2023 | continue; |
| 2024 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2025 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2026 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 2027 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2028 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 2029 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2030 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2031 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2032 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2033 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && |
| 2034 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2035 | TailCalls.push_back(CI); |
| 2036 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2037 | } |
| 2038 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2039 | bool Changed = false; |
| 2040 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 2041 | CallInst *CI = TailCalls[i]; |
| 2042 | CallSite CS(CI); |
| 2043 | |
| 2044 | // Conservatively require the attributes of the call to match those of the |
| 2045 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 2046 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 2047 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 2048 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 2049 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 2050 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2051 | continue; |
| 2052 | |
| 2053 | // Make sure the call instruction is followed by an unconditional branch to |
| 2054 | // the return block. |
| 2055 | BasicBlock *CallBB = CI->getParent(); |
| 2056 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 2057 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 2058 | continue; |
| 2059 | |
| 2060 | // Duplicate the return into CallBB. |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2061 | (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 2062 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2063 | ++NumRetsDup; |
| 2064 | } |
| 2065 | |
| 2066 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 2067 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2068 | BB->eraseFromParent(); |
| 2069 | |
| 2070 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2071 | } |
| 2072 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2073 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2074 | // Memory Optimization |
| 2075 | //===----------------------------------------------------------------------===// |
| 2076 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2077 | namespace { |
| 2078 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2079 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2080 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 2081 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2082 | Value *BaseReg; |
| 2083 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2084 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2085 | void print(raw_ostream &OS) const; |
| 2086 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2087 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2088 | bool operator==(const ExtAddrMode& O) const { |
| 2089 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 2090 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 2091 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 2092 | } |
| 2093 | }; |
| 2094 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2095 | #ifndef NDEBUG |
| 2096 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2097 | AM.print(OS); |
| 2098 | return OS; |
| 2099 | } |
| 2100 | #endif |
| 2101 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2102 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2103 | bool NeedPlus = false; |
| 2104 | OS << "["; |
| 2105 | if (BaseGV) { |
| 2106 | OS << (NeedPlus ? " + " : "") |
| 2107 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2108 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2109 | NeedPlus = true; |
| 2110 | } |
| 2111 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2112 | if (BaseOffs) { |
| 2113 | OS << (NeedPlus ? " + " : "") |
| 2114 | << BaseOffs; |
| 2115 | NeedPlus = true; |
| 2116 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2117 | |
| 2118 | if (BaseReg) { |
| 2119 | OS << (NeedPlus ? " + " : "") |
| 2120 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2121 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2122 | NeedPlus = true; |
| 2123 | } |
| 2124 | if (Scale) { |
| 2125 | OS << (NeedPlus ? " + " : "") |
| 2126 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2127 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2128 | } |
| 2129 | |
| 2130 | OS << ']'; |
| 2131 | } |
| 2132 | |
| 2133 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Yaron Keren | eb2a254 | 2016-01-29 20:50:44 +0000 | [diff] [blame] | 2134 | LLVM_DUMP_METHOD void ExtAddrMode::dump() const { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2135 | print(dbgs()); |
| 2136 | dbgs() << '\n'; |
| 2137 | } |
| 2138 | #endif |
| 2139 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2140 | /// \brief This class provides transaction based operation on the IR. |
| 2141 | /// Every change made through this class is recorded in the internal state and |
| 2142 | /// can be undone (rollback) until commit is called. |
| 2143 | class TypePromotionTransaction { |
| 2144 | |
| 2145 | /// \brief This represents the common interface of the individual transaction. |
| 2146 | /// Each class implements the logic for doing one specific modification on |
| 2147 | /// the IR via the TypePromotionTransaction. |
| 2148 | class TypePromotionAction { |
| 2149 | protected: |
| 2150 | /// The Instruction modified. |
| 2151 | Instruction *Inst; |
| 2152 | |
| 2153 | public: |
| 2154 | /// \brief Constructor of the action. |
| 2155 | /// The constructor performs the related action on the IR. |
| 2156 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2157 | |
| 2158 | virtual ~TypePromotionAction() {} |
| 2159 | |
| 2160 | /// \brief Undo the modification done by this action. |
| 2161 | /// When this method is called, the IR must be in the same state as it was |
| 2162 | /// before this action was applied. |
| 2163 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2164 | /// state as it was directly after this action was applied. |
| 2165 | virtual void undo() = 0; |
| 2166 | |
| 2167 | /// \brief Advocate every change made by this action. |
| 2168 | /// When the results on the IR of the action are to be kept, it is important |
| 2169 | /// to call this function, otherwise hidden information may be kept forever. |
| 2170 | virtual void commit() { |
| 2171 | // Nothing to be done, this action is not doing anything. |
| 2172 | } |
| 2173 | }; |
| 2174 | |
| 2175 | /// \brief Utility to remember the position of an instruction. |
| 2176 | class InsertionHandler { |
| 2177 | /// Position of an instruction. |
| 2178 | /// Either an instruction: |
| 2179 | /// - Is the first in a basic block: BB is used. |
| 2180 | /// - Has a previous instructon: PrevInst is used. |
| 2181 | union { |
| 2182 | Instruction *PrevInst; |
| 2183 | BasicBlock *BB; |
| 2184 | } Point; |
| 2185 | /// Remember whether or not the instruction had a previous instruction. |
| 2186 | bool HasPrevInstruction; |
| 2187 | |
| 2188 | public: |
| 2189 | /// \brief Record the position of \p Inst. |
| 2190 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2191 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2192 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2193 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2194 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2195 | else |
| 2196 | Point.BB = Inst->getParent(); |
| 2197 | } |
| 2198 | |
| 2199 | /// \brief Insert \p Inst at the recorded position. |
| 2200 | void insert(Instruction *Inst) { |
| 2201 | if (HasPrevInstruction) { |
| 2202 | if (Inst->getParent()) |
| 2203 | Inst->removeFromParent(); |
| 2204 | Inst->insertAfter(Point.PrevInst); |
| 2205 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2206 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2207 | if (Inst->getParent()) |
| 2208 | Inst->moveBefore(Position); |
| 2209 | else |
| 2210 | Inst->insertBefore(Position); |
| 2211 | } |
| 2212 | } |
| 2213 | }; |
| 2214 | |
| 2215 | /// \brief Move an instruction before another. |
| 2216 | class InstructionMoveBefore : public TypePromotionAction { |
| 2217 | /// Original position of the instruction. |
| 2218 | InsertionHandler Position; |
| 2219 | |
| 2220 | public: |
| 2221 | /// \brief Move \p Inst before \p Before. |
| 2222 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2223 | : TypePromotionAction(Inst), Position(Inst) { |
| 2224 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2225 | Inst->moveBefore(Before); |
| 2226 | } |
| 2227 | |
| 2228 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2229 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2230 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2231 | Position.insert(Inst); |
| 2232 | } |
| 2233 | }; |
| 2234 | |
| 2235 | /// \brief Set the operand of an instruction with a new value. |
| 2236 | class OperandSetter : public TypePromotionAction { |
| 2237 | /// Original operand of the instruction. |
| 2238 | Value *Origin; |
| 2239 | /// Index of the modified instruction. |
| 2240 | unsigned Idx; |
| 2241 | |
| 2242 | public: |
| 2243 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2244 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2245 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2246 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2247 | << "for:" << *Inst << "\n" |
| 2248 | << "with:" << *NewVal << "\n"); |
| 2249 | Origin = Inst->getOperand(Idx); |
| 2250 | Inst->setOperand(Idx, NewVal); |
| 2251 | } |
| 2252 | |
| 2253 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2254 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2255 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2256 | << "for: " << *Inst << "\n" |
| 2257 | << "with: " << *Origin << "\n"); |
| 2258 | Inst->setOperand(Idx, Origin); |
| 2259 | } |
| 2260 | }; |
| 2261 | |
| 2262 | /// \brief Hide the operands of an instruction. |
| 2263 | /// Do as if this instruction was not using any of its operands. |
| 2264 | class OperandsHider : public TypePromotionAction { |
| 2265 | /// The list of original operands. |
| 2266 | SmallVector<Value *, 4> OriginalValues; |
| 2267 | |
| 2268 | public: |
| 2269 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2270 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2271 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2272 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2273 | OriginalValues.reserve(NumOpnds); |
| 2274 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2275 | // Save the current operand. |
| 2276 | Value *Val = Inst->getOperand(It); |
| 2277 | OriginalValues.push_back(Val); |
| 2278 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2279 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2280 | // that we are not willing to pay. |
| 2281 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2282 | } |
| 2283 | } |
| 2284 | |
| 2285 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2286 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2287 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2288 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2289 | Inst->setOperand(It, OriginalValues[It]); |
| 2290 | } |
| 2291 | }; |
| 2292 | |
| 2293 | /// \brief Build a truncate instruction. |
| 2294 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2295 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2296 | public: |
| 2297 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2298 | /// result. |
| 2299 | /// trunc Opnd to Ty. |
| 2300 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2301 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2302 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2303 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2304 | } |
| 2305 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2306 | /// \brief Get the built value. |
| 2307 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2308 | |
| 2309 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2310 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2311 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2312 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2313 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2314 | } |
| 2315 | }; |
| 2316 | |
| 2317 | /// \brief Build a sign extension instruction. |
| 2318 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2319 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2320 | public: |
| 2321 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2322 | /// result. |
| 2323 | /// sext Opnd to Ty. |
| 2324 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2325 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2326 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2327 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2328 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2329 | } |
| 2330 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2331 | /// \brief Get the built value. |
| 2332 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2333 | |
| 2334 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2335 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2336 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2337 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2338 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2339 | } |
| 2340 | }; |
| 2341 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2342 | /// \brief Build a zero extension instruction. |
| 2343 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2344 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2345 | public: |
| 2346 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2347 | /// result. |
| 2348 | /// zext Opnd to Ty. |
| 2349 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2350 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2351 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2352 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2353 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2354 | } |
| 2355 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2356 | /// \brief Get the built value. |
| 2357 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2358 | |
| 2359 | /// \brief Remove the built instruction. |
| 2360 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2361 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2362 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2363 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2364 | } |
| 2365 | }; |
| 2366 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2367 | /// \brief Mutate an instruction to another type. |
| 2368 | class TypeMutator : public TypePromotionAction { |
| 2369 | /// Record the original type. |
| 2370 | Type *OrigTy; |
| 2371 | |
| 2372 | public: |
| 2373 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2374 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2375 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2376 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2377 | << "\n"); |
| 2378 | Inst->mutateType(NewTy); |
| 2379 | } |
| 2380 | |
| 2381 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2382 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2383 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2384 | << "\n"); |
| 2385 | Inst->mutateType(OrigTy); |
| 2386 | } |
| 2387 | }; |
| 2388 | |
| 2389 | /// \brief Replace the uses of an instruction by another instruction. |
| 2390 | class UsesReplacer : public TypePromotionAction { |
| 2391 | /// Helper structure to keep track of the replaced uses. |
| 2392 | struct InstructionAndIdx { |
| 2393 | /// The instruction using the instruction. |
| 2394 | Instruction *Inst; |
| 2395 | /// The index where this instruction is used for Inst. |
| 2396 | unsigned Idx; |
| 2397 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2398 | : Inst(Inst), Idx(Idx) {} |
| 2399 | }; |
| 2400 | |
| 2401 | /// Keep track of the original uses (pair Instruction, Index). |
| 2402 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 2403 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 2404 | |
| 2405 | public: |
| 2406 | /// \brief Replace all the use of \p Inst by \p New. |
| 2407 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2408 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2409 | << "\n"); |
| 2410 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2411 | for (Use &U : Inst->uses()) { |
| 2412 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2413 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2414 | } |
| 2415 | // Now, we can replace the uses. |
| 2416 | Inst->replaceAllUsesWith(New); |
| 2417 | } |
| 2418 | |
| 2419 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2420 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2421 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2422 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2423 | EndIt = OriginalUses.end(); |
| 2424 | UseIt != EndIt; ++UseIt) { |
| 2425 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2426 | } |
| 2427 | } |
| 2428 | }; |
| 2429 | |
| 2430 | /// \brief Remove an instruction from the IR. |
| 2431 | class InstructionRemover : public TypePromotionAction { |
| 2432 | /// Original position of the instruction. |
| 2433 | InsertionHandler Inserter; |
| 2434 | /// Helper structure to hide all the link to the instruction. In other |
| 2435 | /// words, this helps to do as if the instruction was removed. |
| 2436 | OperandsHider Hider; |
| 2437 | /// Keep track of the uses replaced, if any. |
| 2438 | UsesReplacer *Replacer; |
| 2439 | |
| 2440 | public: |
| 2441 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2442 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2443 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 2444 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2445 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2446 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2447 | if (New) |
| 2448 | Replacer = new UsesReplacer(Inst, New); |
| 2449 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 2450 | Inst->removeFromParent(); |
| 2451 | } |
| 2452 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2453 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2454 | |
| 2455 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2456 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2457 | |
| 2458 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2459 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2460 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2461 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2462 | Inserter.insert(Inst); |
| 2463 | if (Replacer) |
| 2464 | Replacer->undo(); |
| 2465 | Hider.undo(); |
| 2466 | } |
| 2467 | }; |
| 2468 | |
| 2469 | public: |
| 2470 | /// Restoration point. |
| 2471 | /// The restoration point is a pointer to an action instead of an iterator |
| 2472 | /// because the iterator may be invalidated but not the pointer. |
| 2473 | typedef const TypePromotionAction *ConstRestorationPt; |
| 2474 | /// Advocate every changes made in that transaction. |
| 2475 | void commit(); |
| 2476 | /// Undo all the changes made after the given point. |
| 2477 | void rollback(ConstRestorationPt Point); |
| 2478 | /// Get the current restoration point. |
| 2479 | ConstRestorationPt getRestorationPoint() const; |
| 2480 | |
| 2481 | /// \name API for IR modification with state keeping to support rollback. |
| 2482 | /// @{ |
| 2483 | /// Same as Instruction::setOperand. |
| 2484 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2485 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2486 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2487 | /// Same as Value::replaceAllUsesWith. |
| 2488 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2489 | /// Same as Value::mutateType. |
| 2490 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2491 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2492 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2493 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2494 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2495 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2496 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2497 | /// Same as Instruction::moveBefore. |
| 2498 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2499 | /// @} |
| 2500 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2501 | private: |
| 2502 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2503 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2504 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2505 | }; |
| 2506 | |
| 2507 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2508 | Value *NewVal) { |
| 2509 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2510 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2511 | } |
| 2512 | |
| 2513 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2514 | Value *NewVal) { |
| 2515 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2516 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2517 | } |
| 2518 | |
| 2519 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2520 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2521 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2522 | } |
| 2523 | |
| 2524 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2525 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2526 | } |
| 2527 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2528 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2529 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2530 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2531 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2532 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2533 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2534 | } |
| 2535 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2536 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2537 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2538 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2539 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2540 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2541 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2542 | } |
| 2543 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2544 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2545 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2546 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2547 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2548 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2549 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2550 | } |
| 2551 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2552 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2553 | Instruction *Before) { |
| 2554 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2555 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2556 | } |
| 2557 | |
| 2558 | TypePromotionTransaction::ConstRestorationPt |
| 2559 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2560 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2561 | } |
| 2562 | |
| 2563 | void TypePromotionTransaction::commit() { |
| 2564 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2565 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2566 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2567 | Actions.clear(); |
| 2568 | } |
| 2569 | |
| 2570 | void TypePromotionTransaction::rollback( |
| 2571 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2572 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2573 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2574 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2575 | } |
| 2576 | } |
| 2577 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2578 | /// \brief A helper class for matching addressing modes. |
| 2579 | /// |
| 2580 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2581 | class AddressingModeMatcher { |
| 2582 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2583 | const TargetMachine &TM; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2584 | const TargetLowering &TLI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2585 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2586 | |
| 2587 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2588 | /// the memory instruction that we're computing this address for. |
| 2589 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2590 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2591 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2592 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2593 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2594 | /// part of the return value of this addressing mode matching stuff. |
| 2595 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2596 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2597 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2598 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2599 | /// A map from the instructions to their type before promotion. |
| 2600 | InstrToOrigTy &PromotedInsts; |
| 2601 | /// The ongoing transaction where every action should be registered. |
| 2602 | TypePromotionTransaction &TPT; |
| 2603 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2604 | /// This is set to true when we should not do profitability checks. |
| 2605 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2606 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2607 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2608 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2609 | const TargetMachine &TM, Type *AT, unsigned AS, |
| 2610 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2611 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2612 | InstrToOrigTy &PromotedInsts, |
| 2613 | TypePromotionTransaction &TPT) |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2614 | : AddrModeInsts(AMI), TM(TM), |
| 2615 | TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent()) |
| 2616 | ->getTargetLowering()), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2617 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 2618 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 2619 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2620 | IgnoreProfitability = false; |
| 2621 | } |
| 2622 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2623 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2624 | /// Find the maximal addressing mode that a load/store of V can fold, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2625 | /// give an access type of AccessTy. This returns a list of involved |
| 2626 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2627 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2628 | /// optimizations. |
| 2629 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2630 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2631 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2632 | Instruction *MemoryInst, |
| 2633 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2634 | const TargetMachine &TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2635 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2636 | InstrToOrigTy &PromotedInsts, |
| 2637 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2638 | ExtAddrMode Result; |
| 2639 | |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2640 | bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2641 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2642 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2643 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2644 | return Result; |
| 2645 | } |
| 2646 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2647 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 2648 | bool matchAddr(Value *V, unsigned Depth); |
| 2649 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2650 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2651 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2652 | ExtAddrMode &AMBefore, |
| 2653 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2654 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 2655 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2656 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2657 | }; |
| 2658 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2659 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2660 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 2661 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2662 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2663 | unsigned Depth) { |
| 2664 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 2665 | // mode. Just process that directly. |
| 2666 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2667 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2668 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2669 | // If the scale is 0, it takes nothing to add this. |
| 2670 | if (Scale == 0) |
| 2671 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2672 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2673 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 2674 | // need an available scale field. |
| 2675 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 2676 | return false; |
| 2677 | |
| 2678 | ExtAddrMode TestAddrMode = AddrMode; |
| 2679 | |
| 2680 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 2681 | // [A+B + A*7] -> [B+A*8]. |
| 2682 | TestAddrMode.Scale += Scale; |
| 2683 | TestAddrMode.ScaledReg = ScaleReg; |
| 2684 | |
| 2685 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2686 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2687 | return false; |
| 2688 | |
| 2689 | // It was legal, so commit it. |
| 2690 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2691 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2692 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 2693 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 2694 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2695 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2696 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 2697 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 2698 | TestAddrMode.ScaledReg = AddLHS; |
| 2699 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2700 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2701 | // If this addressing mode is legal, commit it and remember that we folded |
| 2702 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2703 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2704 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 2705 | AddrMode = TestAddrMode; |
| 2706 | return true; |
| 2707 | } |
| 2708 | } |
| 2709 | |
| 2710 | // Otherwise, not (x+c)*scale, just return what we have. |
| 2711 | return true; |
| 2712 | } |
| 2713 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2714 | /// This is a little filter, which returns true if an addressing computation |
| 2715 | /// involving I might be folded into a load/store accessing it. |
| 2716 | /// This doesn't need to be perfect, but needs to accept at least |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2717 | /// the set of instructions that MatchOperationAddr can. |
| 2718 | static bool MightBeFoldableInst(Instruction *I) { |
| 2719 | switch (I->getOpcode()) { |
| 2720 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 2721 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2722 | // Don't touch identity bitcasts. |
| 2723 | if (I->getType() == I->getOperand(0)->getType()) |
| 2724 | return false; |
| 2725 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 2726 | case Instruction::PtrToInt: |
| 2727 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2728 | return true; |
| 2729 | case Instruction::IntToPtr: |
| 2730 | // We know the input is intptr_t, so this is foldable. |
| 2731 | return true; |
| 2732 | case Instruction::Add: |
| 2733 | return true; |
| 2734 | case Instruction::Mul: |
| 2735 | case Instruction::Shl: |
| 2736 | // Can only handle X*C and X << C. |
| 2737 | return isa<ConstantInt>(I->getOperand(1)); |
| 2738 | case Instruction::GetElementPtr: |
| 2739 | return true; |
| 2740 | default: |
| 2741 | return false; |
| 2742 | } |
| 2743 | } |
| 2744 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2745 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 2746 | /// \note \p Val is assumed to be the product of some type promotion. |
| 2747 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 2748 | /// to be legal, as the non-promoted value would have had the same state. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2749 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 2750 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2751 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 2752 | if (!PromotedInst) |
| 2753 | return false; |
| 2754 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 2755 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 2756 | if (!ISDOpcode) |
| 2757 | return true; |
| 2758 | // Otherwise, check if the promoted instruction is legal or not. |
| 2759 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2760 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2761 | } |
| 2762 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2763 | /// \brief Hepler class to perform type promotion. |
| 2764 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2765 | /// \brief Utility function to check whether or not a sign or zero extension |
| 2766 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 2767 | /// either using the operands of \p Inst or promoting \p Inst. |
| 2768 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2769 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2770 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2771 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2772 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2773 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2774 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2775 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2776 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 2777 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2778 | |
| 2779 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 2780 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2781 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 2782 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2783 | } |
| 2784 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2785 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2786 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2787 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2788 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2789 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2790 | /// Newly added extensions are inserted in \p Exts. |
| 2791 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2792 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2793 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2794 | static Value *promoteOperandForTruncAndAnyExt( |
| 2795 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2796 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2797 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2798 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2799 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2800 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2801 | /// operand is promotable and is not a supported trunc or sext. |
| 2802 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2803 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2804 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2805 | /// Newly added extensions are inserted in \p Exts. |
| 2806 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2807 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2808 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2809 | static Value *promoteOperandForOther(Instruction *Ext, |
| 2810 | TypePromotionTransaction &TPT, |
| 2811 | InstrToOrigTy &PromotedInsts, |
| 2812 | unsigned &CreatedInstsCost, |
| 2813 | SmallVectorImpl<Instruction *> *Exts, |
| 2814 | SmallVectorImpl<Instruction *> *Truncs, |
| 2815 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2816 | |
| 2817 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2818 | static Value *signExtendOperandForOther( |
| 2819 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2820 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2821 | SmallVectorImpl<Instruction *> *Exts, |
| 2822 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2823 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2824 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2825 | } |
| 2826 | |
| 2827 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2828 | static Value *zeroExtendOperandForOther( |
| 2829 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2830 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2831 | SmallVectorImpl<Instruction *> *Exts, |
| 2832 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2833 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2834 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2835 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2836 | |
| 2837 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2838 | /// Type for the utility function that promotes the operand of Ext. |
| 2839 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2840 | InstrToOrigTy &PromotedInsts, |
| 2841 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2842 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2843 | SmallVectorImpl<Instruction *> *Truncs, |
| 2844 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2845 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 2846 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2847 | /// \return NULL if no promotable action is possible with the current |
| 2848 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2849 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 2850 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2851 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 2852 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 2853 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2854 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2855 | const TargetLowering &TLI, |
| 2856 | const InstrToOrigTy &PromotedInsts); |
| 2857 | }; |
| 2858 | |
| 2859 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2860 | Type *ConsideredExtType, |
| 2861 | const InstrToOrigTy &PromotedInsts, |
| 2862 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2863 | // The promotion helper does not know how to deal with vector types yet. |
| 2864 | // To be able to fix that, we would need to fix the places where we |
| 2865 | // statically extend, e.g., constants and such. |
| 2866 | if (Inst->getType()->isVectorTy()) |
| 2867 | return false; |
| 2868 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2869 | // We can always get through zext. |
| 2870 | if (isa<ZExtInst>(Inst)) |
| 2871 | return true; |
| 2872 | |
| 2873 | // sext(sext) is ok too. |
| 2874 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2875 | return true; |
| 2876 | |
| 2877 | // We can get through binary operator, if it is legal. In other words, the |
| 2878 | // binary operator must have a nuw or nsw flag. |
| 2879 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 2880 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2881 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 2882 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2883 | return true; |
| 2884 | |
| 2885 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2886 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2887 | if (!isa<TruncInst>(Inst)) |
| 2888 | return false; |
| 2889 | |
| 2890 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2891 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2892 | // If the type is larger than the result type of the extension, we cannot. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2893 | if (!OpndVal->getType()->isIntegerTy() || |
| 2894 | OpndVal->getType()->getIntegerBitWidth() > |
| 2895 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2896 | return false; |
| 2897 | |
| 2898 | // If the operand of the truncate is not an instruction, we will not have |
| 2899 | // any information on the dropped bits. |
| 2900 | // (Actually we could for constant but it is not worth the extra logic). |
| 2901 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 2902 | if (!Opnd) |
| 2903 | return false; |
| 2904 | |
| 2905 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2906 | // I.e., check that trunc just drops extended bits of the same kind of |
| 2907 | // the extension. |
| 2908 | // #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] | 2909 | const Type *OpndType; |
| 2910 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 2911 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 2912 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2913 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 2914 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2915 | else |
| 2916 | return false; |
| 2917 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2918 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 2919 | return Inst->getType()->getIntegerBitWidth() >= |
| 2920 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2921 | } |
| 2922 | |
| 2923 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2924 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2925 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2926 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 2927 | "Unexpected instruction type"); |
| 2928 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 2929 | Type *ExtTy = Ext->getType(); |
| 2930 | bool IsSExt = isa<SExtInst>(Ext); |
| 2931 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2932 | // get through. |
| 2933 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2934 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2935 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2936 | |
| 2937 | // Do not promote if the operand has been added by codegenprepare. |
| 2938 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 2939 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2940 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2941 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2942 | |
| 2943 | // SExt or Trunc instructions. |
| 2944 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2945 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 2946 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2947 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2948 | |
| 2949 | // Regular instruction. |
| 2950 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2951 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2952 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2953 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2954 | } |
| 2955 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2956 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2957 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2958 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2959 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2960 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2961 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 2962 | // get through it and this method should not be called. |
| 2963 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2964 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2965 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2966 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2967 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2968 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2969 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2970 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2971 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 2972 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 2973 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2974 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2975 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2976 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 2977 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2978 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 2979 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2980 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2981 | |
| 2982 | // Remove dead code. |
| 2983 | if (SExtOpnd->use_empty()) |
| 2984 | TPT.eraseInstruction(SExtOpnd); |
| 2985 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2986 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2987 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2988 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2989 | if (ExtInst) { |
| 2990 | if (Exts) |
| 2991 | Exts->push_back(ExtInst); |
| 2992 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 2993 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2994 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2995 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2996 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2997 | // At this point we have: ext ty opnd to ty. |
| 2998 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 2999 | Value *NextVal = ExtInst->getOperand(0); |
| 3000 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3001 | return NextVal; |
| 3002 | } |
| 3003 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3004 | Value *TypePromotionHelper::promoteOperandForOther( |
| 3005 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3006 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3007 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3008 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 3009 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3010 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3011 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3012 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3013 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3014 | if (!ExtOpnd->hasOneUse()) { |
| 3015 | // ExtOpnd will be promoted. |
| 3016 | // 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] | 3017 | // promoted version. |
| 3018 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3019 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3020 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 3021 | ITrunc->removeFromParent(); |
| 3022 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3023 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3024 | if (Truncs) |
| 3025 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3026 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3027 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3028 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3029 | // Restore the operand of Ext (which has been replaced by the previous call |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3030 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3031 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3032 | } |
| 3033 | |
| 3034 | // Get through the Instruction: |
| 3035 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3036 | // 2. Replace the uses of Ext by Inst. |
| 3037 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3038 | |
| 3039 | // Remember the original type of the instruction before promotion. |
| 3040 | // 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] | 3041 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 3042 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3043 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3044 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3045 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3046 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3047 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3048 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3049 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3050 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 3051 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3052 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3053 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 3054 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 3055 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3056 | DEBUG(dbgs() << "No need to propagate\n"); |
| 3057 | continue; |
| 3058 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3059 | // Check if we can statically extend the operand. |
| 3060 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3061 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3062 | DEBUG(dbgs() << "Statically extend\n"); |
| 3063 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3064 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3065 | : Cst->getValue().zext(BitWidth); |
| 3066 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3067 | continue; |
| 3068 | } |
| 3069 | // UndefValue are typed, so we have to statically sign extend them. |
| 3070 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3071 | DEBUG(dbgs() << "Statically extend\n"); |
| 3072 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3073 | continue; |
| 3074 | } |
| 3075 | |
| 3076 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3077 | // Check if Ext was reused to extend an operand. |
| 3078 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3079 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3080 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3081 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3082 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3083 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3084 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3085 | continue; |
| 3086 | } |
| 3087 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3088 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3089 | if (Exts) |
| 3090 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3091 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3092 | |
| 3093 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3094 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3095 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3096 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3097 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3098 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3099 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3100 | if (ExtForOpnd == Ext) { |
| 3101 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 3102 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3103 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3104 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3105 | } |
| 3106 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3107 | /// Check whether or not promoting an instruction to a wider type is profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3108 | /// \p NewCost gives the cost of extension instructions created by the |
| 3109 | /// promotion. |
| 3110 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3111 | /// plus the number of instructions that have been |
| 3112 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3113 | /// \p PromotedOperand is the value that has been promoted. |
| 3114 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3115 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3116 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 3117 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 3118 | // The cost of the new extensions is greater than the cost of the |
| 3119 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3120 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3121 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3122 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3123 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3124 | return true; |
| 3125 | // The promotion is neutral but it may help folding the sign extension in |
| 3126 | // loads for instance. |
| 3127 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3128 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3129 | } |
| 3130 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3131 | /// Given an instruction or constant expr, see if we can fold the operation |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3132 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3133 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3134 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3135 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3136 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3137 | /// because it has been moved away. |
| 3138 | /// Thus AddrInst must not be added in the matched instructions. |
| 3139 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3140 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3141 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3142 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3143 | unsigned Depth, |
| 3144 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3145 | // Avoid exponential behavior on extremely deep expression trees. |
| 3146 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3147 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3148 | // By default, all matched instructions stay in place. |
| 3149 | if (MovedAway) |
| 3150 | *MovedAway = false; |
| 3151 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3152 | switch (Opcode) { |
| 3153 | case Instruction::PtrToInt: |
| 3154 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3155 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3156 | case Instruction::IntToPtr: { |
| 3157 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3158 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3159 | // This inttoptr is a no-op if the integer type is pointer sized. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3160 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3161 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3162 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3163 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3164 | case Instruction::BitCast: |
| 3165 | // BitCast is always a noop, and we can handle it as long as it is |
| 3166 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3167 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3168 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3169 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3170 | // and we don't want to mess around with them. Assume it knows what it |
| 3171 | // is doing. |
| 3172 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3173 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3174 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3175 | case Instruction::AddrSpaceCast: { |
| 3176 | unsigned SrcAS |
| 3177 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3178 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3179 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3180 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3181 | return false; |
| 3182 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3183 | case Instruction::Add: { |
| 3184 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3185 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3186 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3187 | // Start a transaction at this point. |
| 3188 | // The LHS may match but not the RHS. |
| 3189 | // Therefore, we need a higher level restoration point to undo partially |
| 3190 | // matched operation. |
| 3191 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3192 | TPT.getRestorationPoint(); |
| 3193 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3194 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3195 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3196 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3197 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3198 | // Restore the old addr mode info. |
| 3199 | AddrMode = BackupAddrMode; |
| 3200 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3201 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3202 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3203 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3204 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3205 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3206 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3207 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3208 | // Otherwise we definitely can't merge the ADD in. |
| 3209 | AddrMode = BackupAddrMode; |
| 3210 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3211 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3212 | break; |
| 3213 | } |
| 3214 | //case Instruction::Or: |
| 3215 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3216 | //break; |
| 3217 | case Instruction::Mul: |
| 3218 | case Instruction::Shl: { |
| 3219 | // Can only handle X*C and X << C. |
| 3220 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3221 | if (!RHS) |
| 3222 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3223 | int64_t Scale = RHS->getSExtValue(); |
| 3224 | if (Opcode == Instruction::Shl) |
| 3225 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3226 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3227 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3228 | } |
| 3229 | case Instruction::GetElementPtr: { |
| 3230 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3231 | // one variable offset. |
| 3232 | int VariableOperand = -1; |
| 3233 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3234 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3235 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3236 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3237 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
| 3238 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3239 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3240 | unsigned Idx = |
| 3241 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3242 | ConstantOffset += SL->getElementOffset(Idx); |
| 3243 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3244 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3245 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3246 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3247 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3248 | // We only allow one variable index at the moment. |
| 3249 | if (VariableOperand != -1) |
| 3250 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3251 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3252 | // Remember the variable index. |
| 3253 | VariableOperand = i; |
| 3254 | VariableScale = TypeSize; |
| 3255 | } |
| 3256 | } |
| 3257 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3258 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3259 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3260 | // just add it to the disp field and check validity. |
| 3261 | if (VariableOperand == -1) { |
| 3262 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3263 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3264 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3265 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3266 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3267 | return true; |
| 3268 | } |
| 3269 | AddrMode.BaseOffs -= ConstantOffset; |
| 3270 | return false; |
| 3271 | } |
| 3272 | |
| 3273 | // Save the valid addressing mode in case we can't match. |
| 3274 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3275 | unsigned OldSize = AddrModeInsts.size(); |
| 3276 | |
| 3277 | // See if the scale and offset amount is valid for this target. |
| 3278 | AddrMode.BaseOffs += ConstantOffset; |
| 3279 | |
| 3280 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3281 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3282 | // If it couldn't be matched, just stuff the value in a register. |
| 3283 | if (AddrMode.HasBaseReg) { |
| 3284 | AddrMode = BackupAddrMode; |
| 3285 | AddrModeInsts.resize(OldSize); |
| 3286 | return false; |
| 3287 | } |
| 3288 | AddrMode.HasBaseReg = true; |
| 3289 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3290 | } |
| 3291 | |
| 3292 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3293 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3294 | Depth)) { |
| 3295 | // If it couldn't be matched, try stuffing the base into a register |
| 3296 | // instead of matching it, and retrying the match of the scale. |
| 3297 | AddrMode = BackupAddrMode; |
| 3298 | AddrModeInsts.resize(OldSize); |
| 3299 | if (AddrMode.HasBaseReg) |
| 3300 | return false; |
| 3301 | AddrMode.HasBaseReg = true; |
| 3302 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3303 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3304 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3305 | VariableScale, Depth)) { |
| 3306 | // If even that didn't work, bail. |
| 3307 | AddrMode = BackupAddrMode; |
| 3308 | AddrModeInsts.resize(OldSize); |
| 3309 | return false; |
| 3310 | } |
| 3311 | } |
| 3312 | |
| 3313 | return true; |
| 3314 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3315 | case Instruction::SExt: |
| 3316 | case Instruction::ZExt: { |
| 3317 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3318 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3319 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3320 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3321 | // 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] | 3322 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3323 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3324 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3325 | if (!TPH) |
| 3326 | return false; |
| 3327 | |
| 3328 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3329 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3330 | unsigned CreatedInstsCost = 0; |
| 3331 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3332 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3333 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3334 | // SExt has been moved away. |
| 3335 | // Thus either it will be rematched later in the recursive calls or it is |
| 3336 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3337 | // E.g., |
| 3338 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3339 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3340 | // addr = gep base, idx |
| 3341 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3342 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3343 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3344 | // addr = gep base, op <- match |
| 3345 | if (MovedAway) |
| 3346 | *MovedAway = true; |
| 3347 | |
| 3348 | assert(PromotedOperand && |
| 3349 | "TypePromotionHelper should have filtered out those cases"); |
| 3350 | |
| 3351 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3352 | unsigned OldSize = AddrModeInsts.size(); |
| 3353 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3354 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3355 | // The total of the new cost is equal to the cost of the created |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3356 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3357 | // The total of the old cost is equal to the cost of the extension plus |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3358 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3359 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3360 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3361 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3362 | AddrMode = BackupAddrMode; |
| 3363 | AddrModeInsts.resize(OldSize); |
| 3364 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3365 | TPT.rollback(LastKnownGood); |
| 3366 | return false; |
| 3367 | } |
| 3368 | return true; |
| 3369 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3370 | } |
| 3371 | return false; |
| 3372 | } |
| 3373 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3374 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3375 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3376 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3377 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3378 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3379 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3380 | // Start a transaction at this point that we will rollback if the matching |
| 3381 | // fails. |
| 3382 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3383 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3384 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 3385 | // Fold in immediates if legal for the target. |
| 3386 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3387 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3388 | return true; |
| 3389 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 3390 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 3391 | // 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] | 3392 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3393 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3394 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3395 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3396 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3397 | } |
| 3398 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 3399 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3400 | unsigned OldSize = AddrModeInsts.size(); |
| 3401 | |
| 3402 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3403 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3404 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3405 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3406 | // to check here. |
| 3407 | if (MovedAway) |
| 3408 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3409 | // Okay, it's possible to fold this. Check to see if it is actually |
| 3410 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 3411 | // register pressure too much. |
| 3412 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3413 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3414 | AddrModeInsts.push_back(I); |
| 3415 | return true; |
| 3416 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3417 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3418 | // It isn't profitable to do this, roll back. |
| 3419 | //cerr << "NOT FOLDING: " << *I; |
| 3420 | AddrMode = BackupAddrMode; |
| 3421 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3422 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3423 | } |
| 3424 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3425 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3426 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3427 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3428 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 3429 | // Null pointer gets folded without affecting the addressing mode. |
| 3430 | return true; |
| 3431 | } |
| 3432 | |
| 3433 | // Worse case, the target should support [reg] addressing modes. :) |
| 3434 | if (!AddrMode.HasBaseReg) { |
| 3435 | AddrMode.HasBaseReg = true; |
| 3436 | AddrMode.BaseReg = Addr; |
| 3437 | // Still check for legality in case the target supports [imm] but not [i+r]. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3438 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3439 | return true; |
| 3440 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3441 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3442 | } |
| 3443 | |
| 3444 | // If the base register is already taken, see if we can do [r+r]. |
| 3445 | if (AddrMode.Scale == 0) { |
| 3446 | AddrMode.Scale = 1; |
| 3447 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3448 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3449 | return true; |
| 3450 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3451 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3452 | } |
| 3453 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3454 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3455 | return false; |
| 3456 | } |
| 3457 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3458 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 3459 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3460 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3461 | const TargetMachine &TM) { |
| 3462 | const Function *F = CI->getParent()->getParent(); |
| 3463 | const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering(); |
| 3464 | const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3465 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3466 | TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI, |
| 3467 | ImmutableCallSite(CI)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3468 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3469 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3470 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3471 | // Compute the constraint code and ConstraintType to use. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3472 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3473 | |
| 3474 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 3475 | // operand, we can't fold it! |
| 3476 | if (OpInfo.CallOperandVal == OpVal && |
| 3477 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 3478 | !OpInfo.isIndirect)) |
| 3479 | return false; |
| 3480 | } |
| 3481 | |
| 3482 | return true; |
| 3483 | } |
| 3484 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3485 | /// Recursively walk all the uses of I until we find a memory use. |
| 3486 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3487 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3488 | static bool FindAllMemoryUses( |
| 3489 | Instruction *I, |
| 3490 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
| 3491 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3492 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3493 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3494 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3495 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3496 | // If this is an obviously unfoldable instruction, bail out. |
| 3497 | if (!MightBeFoldableInst(I)) |
| 3498 | return true; |
| 3499 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3500 | const bool OptSize = I->getFunction()->optForSize(); |
| 3501 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3502 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3503 | for (Use &U : I->uses()) { |
| 3504 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3505 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3506 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3507 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3508 | continue; |
| 3509 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3510 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3511 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3512 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3513 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 3514 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3515 | continue; |
| 3516 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3517 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3518 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3519 | // If this is a cold call, we can sink the addressing calculation into |
| 3520 | // the cold path. See optimizeCallInst |
| 3521 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 3522 | continue; |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 3523 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3524 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 3525 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3526 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3527 | // If this is a memory operand, we're cool, otherwise bail out. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3528 | if (!IsOperandAMemoryOperand(CI, IA, I, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3529 | return true; |
| 3530 | continue; |
| 3531 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3532 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3533 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3534 | return true; |
| 3535 | } |
| 3536 | |
| 3537 | return false; |
| 3538 | } |
| 3539 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3540 | /// Return true if Val is already known to be live at the use site that we're |
| 3541 | /// folding it into. If so, there is no cost to include it in the addressing |
| 3542 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 3543 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3544 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3545 | Value *KnownLive2) { |
| 3546 | // 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] | 3547 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3548 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3549 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3550 | // All values other than instructions and arguments (e.g. constants) are live. |
| 3551 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3552 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3553 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 3554 | // true because it is just a reference to the stack/frame pointer, which is |
| 3555 | // live for the whole function. |
| 3556 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 3557 | if (AI->isStaticAlloca()) |
| 3558 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3559 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3560 | // Check to see if this value is already used in the memory instruction's |
| 3561 | // block. If so, it's already live into the block at the very least, so we |
| 3562 | // can reasonably fold it. |
| 3563 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 3564 | } |
| 3565 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3566 | /// It is possible for the addressing mode of the machine to fold the specified |
| 3567 | /// instruction into a load or store that ultimately uses it. |
| 3568 | /// However, the specified instruction has multiple uses. |
| 3569 | /// Given this, it may actually increase register pressure to fold it |
| 3570 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3571 | /// |
| 3572 | /// X = ... |
| 3573 | /// Y = X+1 |
| 3574 | /// use(Y) -> nonload/store |
| 3575 | /// Z = Y+1 |
| 3576 | /// load Z |
| 3577 | /// |
| 3578 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 3579 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 3580 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 3581 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 3582 | /// number of computations either. |
| 3583 | /// |
| 3584 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 3585 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 3586 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 3587 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3588 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3589 | ExtAddrMode &AMAfter) { |
| 3590 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3591 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3592 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 3593 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 3594 | // the set of registers referenced by AMAfter and subtract out those |
| 3595 | // referenced by AMBefore: this is the set of values which folding in this |
| 3596 | // address extends the lifetime of. |
| 3597 | // |
| 3598 | // Note that there are only two potential values being referenced here, |
| 3599 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 3600 | // folded immediates). |
| 3601 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3602 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3603 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 3604 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3605 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3606 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3607 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3608 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3609 | |
| 3610 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 3611 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3612 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3613 | return true; |
| 3614 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3615 | // If all uses of this instruction can have the address mode sunk into them, |
| 3616 | // we can remove the addressing mode and effectively trade one live register |
| 3617 | // for another (at worst.) In this context, folding an addressing mode into |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 3618 | // the use is just a particularly nice way of sinking it. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3619 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 3620 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3621 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3622 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3623 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3624 | // Now that we know that all uses of this instruction are part of a chain of |
| 3625 | // computation involving only operations that could theoretically be folded |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3626 | // into a memory use, loop over each of these memory operation uses and see |
| 3627 | // if they could *actually* fold the instruction. The assumption is that |
| 3628 | // addressing modes are cheap and that duplicating the computation involved |
| 3629 | // many times is worthwhile, even on a fastpath. For sinking candidates |
| 3630 | // (i.e. cold call sites), this serves as a way to prevent excessive code |
| 3631 | // growth since most architectures have some reasonable small and fast way to |
| 3632 | // compute an effective address. (i.e LEA on x86) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3633 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 3634 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 3635 | Instruction *User = MemoryUses[i].first; |
| 3636 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3637 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3638 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 3639 | // know what it accesses. |
| 3640 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3641 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 3642 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3643 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3644 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 3645 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3646 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3647 | // Do a match against the root of this address, ignoring profitability. This |
| 3648 | // will tell us if the addressing mode for the memory operation will |
| 3649 | // *actually* cover the shared instruction. |
| 3650 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3651 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3652 | TPT.getRestorationPoint(); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3653 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3654 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3655 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3656 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3657 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3658 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3659 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3660 | // The match was to check the profitability, the changes made are not |
| 3661 | // part of the original matcher. Therefore, they should be dropped |
| 3662 | // otherwise the original matcher will not present the right state. |
| 3663 | TPT.rollback(LastKnownGood); |
| 3664 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3665 | // If the match didn't cover I, then it won't be shared by it. |
David Majnemer | 0d955d0 | 2016-08-11 22:21:41 +0000 | [diff] [blame] | 3666 | if (!is_contained(MatchedAddrModeInsts, I)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3667 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3668 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3669 | MatchedAddrModeInsts.clear(); |
| 3670 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3671 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3672 | return true; |
| 3673 | } |
| 3674 | |
| 3675 | } // end anonymous namespace |
| 3676 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3677 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3678 | /// different basic block than BB. |
| 3679 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 3680 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 3681 | return I->getParent() != BB; |
| 3682 | return false; |
| 3683 | } |
| 3684 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3685 | /// Sink addressing mode computation immediate before MemoryInst if doing so |
| 3686 | /// can be done without increasing register pressure. The need for the |
| 3687 | /// register pressure constraint means this can end up being an all or nothing |
| 3688 | /// decision for all uses of the same addressing computation. |
| 3689 | /// |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3690 | /// Load and Store Instructions often have addressing modes that can do |
| 3691 | /// significant amounts of computation. As such, instruction selection will try |
| 3692 | /// to get the load or store to do as much computation as possible for the |
| 3693 | /// program. The problem is that isel can only see within a single block. As |
| 3694 | /// such, we sink as much legal addressing mode work into the block as possible. |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 3695 | /// |
| 3696 | /// This method is used to optimize both load/store and inline asms with memory |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3697 | /// operands. It's also used to sink addressing computations feeding into cold |
| 3698 | /// call sites into their (cold) basic block. |
| 3699 | /// |
| 3700 | /// The motivation for handling sinking into cold blocks is that doing so can |
| 3701 | /// both enable other address mode sinking (by satisfying the register pressure |
| 3702 | /// constraint above), and reduce register pressure globally (by removing the |
| 3703 | /// addressing mode computation from the fast path entirely.). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3704 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3705 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3706 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3707 | |
| 3708 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3709 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 3710 | SmallVector<Value*, 8> worklist; |
| 3711 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3712 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3713 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3714 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 3715 | // the addressing mode obtained from the non-PHI roots of the graph |
| 3716 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3717 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3718 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3719 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3720 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 3721 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3722 | TypePromotionTransaction TPT; |
| 3723 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3724 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3725 | while (!worklist.empty()) { |
| 3726 | Value *V = worklist.back(); |
| 3727 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3728 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3729 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3730 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3731 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3732 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3733 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3734 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3735 | // For a PHI node, push all of its incoming values. |
| 3736 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 3737 | for (Value *IncValue : P->incoming_values()) |
| 3738 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3739 | continue; |
| 3740 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3741 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3742 | // For non-PHIs, determine the addressing mode being computed. Note that |
| 3743 | // the result may differ depending on what other uses our candidate |
| 3744 | // addressing instructions might have. |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3745 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3746 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3747 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3748 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3749 | |
| 3750 | // This check is broken into two cases with very similar code to avoid using |
| 3751 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 3752 | // calling getNumUses() unconditionally caused a significant compile-time |
| 3753 | // regression. |
| 3754 | if (!Consensus) { |
| 3755 | Consensus = V; |
| 3756 | AddrMode = NewAddrMode; |
| 3757 | AddrModeInsts = NewAddrModeInsts; |
| 3758 | continue; |
| 3759 | } else if (NewAddrMode == AddrMode) { |
| 3760 | if (!IsNumUsesConsensusValid) { |
| 3761 | NumUsesConsensus = Consensus->getNumUses(); |
| 3762 | IsNumUsesConsensusValid = true; |
| 3763 | } |
| 3764 | |
| 3765 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 3766 | // for all other roots of the PHI traversal. Also, when choosing one |
| 3767 | // such root as representative, select the one with the most uses in order |
| 3768 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 3769 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3770 | unsigned NumUses = V->getNumUses(); |
| 3771 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3772 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3773 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3774 | AddrModeInsts = NewAddrModeInsts; |
| 3775 | } |
| 3776 | continue; |
| 3777 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3778 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3779 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3780 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3781 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3782 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3783 | // If the addressing mode couldn't be determined, or if multiple different |
| 3784 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3785 | if (!Consensus) { |
| 3786 | TPT.rollback(LastKnownGood); |
| 3787 | return false; |
| 3788 | } |
| 3789 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3790 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3791 | // Check to see if any of the instructions supersumed by this addr mode are |
| 3792 | // non-local to I's BB. |
| 3793 | bool AnyNonLocal = false; |
| 3794 | for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) { |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 3795 | if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) { |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3796 | AnyNonLocal = true; |
| 3797 | break; |
| 3798 | } |
| 3799 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3800 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3801 | // If all the instructions matched are already in this BB, don't do anything. |
| 3802 | if (!AnyNonLocal) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3803 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3804 | return false; |
| 3805 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3806 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3807 | // Insert this computation right after this user. Since our caller is |
| 3808 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 3809 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3810 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3811 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3812 | // Now that we determined the addressing expression we want to use and know |
| 3813 | // that we have to sink it into this block. Check to see if we have already |
| 3814 | // done this for some other load/store instr in this block. If so, reuse the |
| 3815 | // computation. |
| 3816 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 3817 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3818 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3819 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3820 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 3821 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 3822 | } else if (AddrSinkUsingGEPs || |
| 3823 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Eric Christopher | 2c63549 | 2015-01-27 07:54:39 +0000 | [diff] [blame] | 3824 | TM->getSubtargetImpl(*MemoryInst->getParent()->getParent()) |
| 3825 | ->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3826 | // By default, we use the GEP-based method when AA is used later. This |
| 3827 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 3828 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3829 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3830 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3831 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3832 | |
| 3833 | // First, find the pointer. |
| 3834 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 3835 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3836 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3837 | } |
| 3838 | |
| 3839 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 3840 | // We can't add more than one pointer together, nor can we scale a |
| 3841 | // pointer (both of which seem meaningless). |
| 3842 | if (ResultPtr || AddrMode.Scale != 1) |
| 3843 | return false; |
| 3844 | |
| 3845 | ResultPtr = AddrMode.ScaledReg; |
| 3846 | AddrMode.Scale = 0; |
| 3847 | } |
| 3848 | |
| 3849 | if (AddrMode.BaseGV) { |
| 3850 | if (ResultPtr) |
| 3851 | return false; |
| 3852 | |
| 3853 | ResultPtr = AddrMode.BaseGV; |
| 3854 | } |
| 3855 | |
| 3856 | // If the real base value actually came from an inttoptr, then the matcher |
| 3857 | // will look through it and provide only the integer value. In that case, |
| 3858 | // use it here. |
| 3859 | if (!ResultPtr && AddrMode.BaseReg) { |
| 3860 | ResultPtr = |
| 3861 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3862 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3863 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 3864 | ResultPtr = |
| 3865 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 3866 | AddrMode.Scale = 0; |
| 3867 | } |
| 3868 | |
| 3869 | if (!ResultPtr && |
| 3870 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 3871 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 3872 | } else if (!ResultPtr) { |
| 3873 | return false; |
| 3874 | } else { |
| 3875 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3876 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 3877 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3878 | |
| 3879 | // Start with the base register. Do this first so that subsequent address |
| 3880 | // matching finds it last, which will prevent it from trying to match it |
| 3881 | // as the scaled value in case it happens to be a mul. That would be |
| 3882 | // problematic if we've sunk a different mul for the scale, because then |
| 3883 | // we'd end up sinking both muls. |
| 3884 | if (AddrMode.BaseReg) { |
| 3885 | Value *V = AddrMode.BaseReg; |
| 3886 | if (V->getType() != IntPtrTy) |
| 3887 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 3888 | |
| 3889 | ResultIndex = V; |
| 3890 | } |
| 3891 | |
| 3892 | // Add the scale value. |
| 3893 | if (AddrMode.Scale) { |
| 3894 | Value *V = AddrMode.ScaledReg; |
| 3895 | if (V->getType() == IntPtrTy) { |
| 3896 | // done. |
| 3897 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3898 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 3899 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 3900 | } else { |
| 3901 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3902 | // required to create it did not overflow before we extend it. Since |
| 3903 | // the original IR value was tossed in favor of a constant back when |
| 3904 | // the AddrMode was created we need to bail out gracefully if widths |
| 3905 | // do not match instead of extending it. |
| 3906 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 3907 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 3908 | I->eraseFromParent(); |
| 3909 | return false; |
| 3910 | } |
| 3911 | |
| 3912 | if (AddrMode.Scale != 1) |
| 3913 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3914 | "sunkaddr"); |
| 3915 | if (ResultIndex) |
| 3916 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 3917 | else |
| 3918 | ResultIndex = V; |
| 3919 | } |
| 3920 | |
| 3921 | // Add in the Base Offset if present. |
| 3922 | if (AddrMode.BaseOffs) { |
| 3923 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 3924 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 3925 | // We need to add this separately from the scale above to help with |
| 3926 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3927 | if (ResultPtr->getType() != I8PtrTy) |
| 3928 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3929 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3930 | } |
| 3931 | |
| 3932 | ResultIndex = V; |
| 3933 | } |
| 3934 | |
| 3935 | if (!ResultIndex) { |
| 3936 | SunkAddr = ResultPtr; |
| 3937 | } else { |
| 3938 | if (ResultPtr->getType() != I8PtrTy) |
| 3939 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3940 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3941 | } |
| 3942 | |
| 3943 | if (SunkAddr->getType() != Addr->getType()) |
| 3944 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 3945 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3946 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3947 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3948 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3949 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3950 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3951 | |
| 3952 | // Start with the base register. Do this first so that subsequent address |
| 3953 | // matching finds it last, which will prevent it from trying to match it |
| 3954 | // as the scaled value in case it happens to be a mul. That would be |
| 3955 | // problematic if we've sunk a different mul for the scale, because then |
| 3956 | // we'd end up sinking both muls. |
| 3957 | if (AddrMode.BaseReg) { |
| 3958 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3959 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3960 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3961 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3962 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3963 | Result = V; |
| 3964 | } |
| 3965 | |
| 3966 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3967 | if (AddrMode.Scale) { |
| 3968 | Value *V = AddrMode.ScaledReg; |
| 3969 | if (V->getType() == IntPtrTy) { |
| 3970 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3971 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3972 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3973 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3974 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3975 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3976 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3977 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3978 | // required to create it did not overflow before we extend it. Since |
| 3979 | // the original IR value was tossed in favor of a constant back when |
| 3980 | // the AddrMode was created we need to bail out gracefully if widths |
| 3981 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 3982 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 3983 | if (I && (Result != AddrMode.BaseReg)) |
| 3984 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3985 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3986 | } |
| 3987 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3988 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3989 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3990 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3991 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3992 | else |
| 3993 | Result = V; |
| 3994 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3995 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3996 | // Add in the BaseGV if present. |
| 3997 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3998 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3999 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4000 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4001 | else |
| 4002 | Result = V; |
| 4003 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4004 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4005 | // Add in the Base Offset if present. |
| 4006 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4007 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4008 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4009 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4010 | else |
| 4011 | Result = V; |
| 4012 | } |
| 4013 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4014 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 4015 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4016 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4017 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4018 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4019 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4020 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4021 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4022 | // If we have no uses, recursively delete the value and all dead instructions |
| 4023 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4024 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4025 | // This can cause recursive deletion, which can invalidate our iterator. |
| 4026 | // Use a WeakVH to hold onto it in case this happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4027 | Value *CurValue = &*CurInstIterator; |
| 4028 | WeakVH IterHandle(CurValue); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4029 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4030 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 4031 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4032 | |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4033 | if (IterHandle != CurValue) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4034 | // If the iterator instruction was recursively deleted, start over at the |
| 4035 | // start of the block. |
| 4036 | CurInstIterator = BB->begin(); |
| 4037 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4038 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 4039 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4040 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4041 | return true; |
| 4042 | } |
| 4043 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4044 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 4045 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4046 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4047 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4048 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4049 | const TargetRegisterInfo *TRI = |
| 4050 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4051 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 4052 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4053 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 4054 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4055 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4056 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4057 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 4058 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4059 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 4060 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 4061 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4062 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4063 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4064 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 4065 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4066 | } |
| 4067 | |
| 4068 | return MadeChange; |
| 4069 | } |
| 4070 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4071 | /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or |
| 4072 | /// sign extensions. |
| 4073 | static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) { |
| 4074 | assert(!Inst->use_empty() && "Input must have at least one use"); |
| 4075 | const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin()); |
| 4076 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 4077 | Type *ExtTy = FirstUser->getType(); |
| 4078 | for (const User *U : Inst->users()) { |
| 4079 | const Instruction *UI = cast<Instruction>(U); |
| 4080 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4081 | return false; |
| 4082 | Type *CurTy = UI->getType(); |
| 4083 | // Same input and output types: Same instruction after CSE. |
| 4084 | if (CurTy == ExtTy) |
| 4085 | continue; |
| 4086 | |
| 4087 | // If IsSExt is true, we are in this situation: |
| 4088 | // a = Inst |
| 4089 | // b = sext ty1 a to ty2 |
| 4090 | // c = sext ty1 a to ty3 |
| 4091 | // Assuming ty2 is shorter than ty3, this could be turned into: |
| 4092 | // a = Inst |
| 4093 | // b = sext ty1 a to ty2 |
| 4094 | // c = sext ty2 b to ty3 |
| 4095 | // However, the last sext is not free. |
| 4096 | if (IsSExt) |
| 4097 | return false; |
| 4098 | |
| 4099 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4100 | // In that case, we would not account for a different use. |
| 4101 | Type *NarrowTy; |
| 4102 | Type *LargeTy; |
| 4103 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4104 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4105 | NarrowTy = CurTy; |
| 4106 | LargeTy = ExtTy; |
| 4107 | } else { |
| 4108 | NarrowTy = ExtTy; |
| 4109 | LargeTy = CurTy; |
| 4110 | } |
| 4111 | |
| 4112 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4113 | return false; |
| 4114 | } |
| 4115 | // All uses are the same or can be derived from one another for free. |
| 4116 | return true; |
| 4117 | } |
| 4118 | |
| 4119 | /// \brief Try to form ExtLd by promoting \p Exts until they reach a |
| 4120 | /// load instruction. |
| 4121 | /// If an ext(load) can be formed, it is returned via \p LI for the load |
| 4122 | /// and \p Inst for the extension. |
| 4123 | /// Otherwise LI == nullptr and Inst == nullptr. |
| 4124 | /// When some promotion happened, \p TPT contains the proper state to |
| 4125 | /// revert them. |
| 4126 | /// |
| 4127 | /// \return true when promoting was necessary to expose the ext(load) |
| 4128 | /// opportunity, false otherwise. |
| 4129 | /// |
| 4130 | /// Example: |
| 4131 | /// \code |
| 4132 | /// %ld = load i32* %addr |
| 4133 | /// %add = add nuw i32 %ld, 4 |
| 4134 | /// %zext = zext i32 %add to i64 |
| 4135 | /// \endcode |
| 4136 | /// => |
| 4137 | /// \code |
| 4138 | /// %ld = load i32* %addr |
| 4139 | /// %zext = zext i32 %ld to i64 |
| 4140 | /// %add = add nuw i64 %zext, 4 |
| 4141 | /// \encode |
| 4142 | /// Thanks to the promotion, we can match zext(load i32*) to i64. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4143 | bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4144 | LoadInst *&LI, Instruction *&Inst, |
| 4145 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4146 | unsigned CreatedInstsCost = 0) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4147 | // Iterate over all the extensions to see if one form an ext(load). |
| 4148 | for (auto I : Exts) { |
| 4149 | // Check if we directly have ext(load). |
| 4150 | if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) { |
| 4151 | Inst = I; |
| 4152 | // No promotion happened here. |
| 4153 | return false; |
| 4154 | } |
| 4155 | // Check whether or not we want to do any promotion. |
| 4156 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
| 4157 | continue; |
| 4158 | // Get the action to perform the promotion. |
| 4159 | TypePromotionHelper::Action TPH = TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4160 | I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4161 | // Check if we can promote. |
| 4162 | if (!TPH) |
| 4163 | continue; |
| 4164 | // Save the current state. |
| 4165 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4166 | TPT.getRestorationPoint(); |
| 4167 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4168 | unsigned NewCreatedInstsCost = 0; |
| 4169 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4170 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4171 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4172 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4173 | assert(PromotedVal && |
| 4174 | "TypePromotionHelper should have filtered out those cases"); |
| 4175 | |
| 4176 | // We would be able to merge only one extension in a load. |
| 4177 | // Therefore, if we have more than 1 new extension we heuristically |
| 4178 | // cut this search path, because it means we degrade the code quality. |
| 4179 | // With exactly 2, the transformation is neutral, because we will merge |
| 4180 | // one extension but leave one. However, we optimistically keep going, |
| 4181 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4182 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
| 4183 | TotalCreatedInstsCost -= ExtCost; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4184 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4185 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4186 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4187 | // The promotion is not profitable, rollback to the previous state. |
| 4188 | TPT.rollback(LastKnownGood); |
| 4189 | continue; |
| 4190 | } |
| 4191 | // The promotion is profitable. |
| 4192 | // Check if it exposes an ext(load). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4193 | (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4194 | if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4195 | // If we have created a new extension, i.e., now we have two |
| 4196 | // extensions. We must make sure one of them is merged with |
| 4197 | // the load, otherwise we may degrade the code quality. |
| 4198 | (LI->hasOneUse() || hasSameExtUse(LI, *TLI)))) |
| 4199 | // Promotion happened. |
| 4200 | return true; |
| 4201 | // If this does not help to expose an ext(load) then, rollback. |
| 4202 | TPT.rollback(LastKnownGood); |
| 4203 | } |
| 4204 | // None of the extension can form an ext(load). |
| 4205 | LI = nullptr; |
| 4206 | Inst = nullptr; |
| 4207 | return false; |
| 4208 | } |
| 4209 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4210 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4211 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4212 | /// extend into the load. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4213 | /// \p I[in/out] the extension may be modified during the process if some |
| 4214 | /// promotions apply. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4215 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4216 | bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4217 | // Try to promote a chain of computation if it allows to form |
| 4218 | // an extended load. |
| 4219 | TypePromotionTransaction TPT; |
| 4220 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4221 | TPT.getRestorationPoint(); |
| 4222 | SmallVector<Instruction *, 1> Exts; |
| 4223 | Exts.push_back(I); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4224 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4225 | LoadInst *LI = nullptr; |
| 4226 | Instruction *OldExt = I; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4227 | bool HasPromoted = extLdPromotion(TPT, LI, I, Exts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4228 | if (!LI || !I) { |
| 4229 | assert(!HasPromoted && !LI && "If we did not match any load instruction " |
| 4230 | "the code must remain the same"); |
| 4231 | I = OldExt; |
| 4232 | return false; |
| 4233 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4234 | |
| 4235 | // 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] | 4236 | // Make the cheap checks first if we did not promote. |
| 4237 | // If we promoted, we need to check if it is indeed profitable. |
| 4238 | if (!HasPromoted && LI->getParent() == I->getParent()) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4239 | return false; |
| 4240 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4241 | EVT VT = TLI->getValueType(*DL, I->getType()); |
| 4242 | EVT LoadVT = TLI->getValueType(*DL, LI->getType()); |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4243 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4244 | // If the load has other users and the truncate is not free, this probably |
| 4245 | // isn't worthwhile. |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4246 | if (!LI->hasOneUse() && TLI && |
| 4247 | (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4248 | !TLI->isTruncateFree(I->getType(), LI->getType())) { |
| 4249 | I = OldExt; |
| 4250 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4251 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4252 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4253 | |
| 4254 | // Check whether the target supports casts folded into loads. |
| 4255 | unsigned LType; |
| 4256 | if (isa<ZExtInst>(I)) |
| 4257 | LType = ISD::ZEXTLOAD; |
| 4258 | else { |
| 4259 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 4260 | LType = ISD::SEXTLOAD; |
| 4261 | } |
Ahmed Bougacha | 2b6917b | 2015-01-08 00:51:32 +0000 | [diff] [blame] | 4262 | if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4263 | I = OldExt; |
| 4264 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4265 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4266 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4267 | |
| 4268 | // Move the extend into the same block as the load, so that SelectionDAG |
| 4269 | // can fold it. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4270 | TPT.commit(); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4271 | I->removeFromParent(); |
| 4272 | I->insertAfter(LI); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4273 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4274 | return true; |
| 4275 | } |
| 4276 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4277 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4278 | BasicBlock *DefBB = I->getParent(); |
| 4279 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 4280 | // 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] | 4281 | // other uses of the source with result of extension. |
| 4282 | Value *Src = I->getOperand(0); |
| 4283 | if (Src->hasOneUse()) |
| 4284 | return false; |
| 4285 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 4286 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 4287 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4288 | return false; |
| 4289 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4290 | // 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] | 4291 | // this block. |
| 4292 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4293 | return false; |
| 4294 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4295 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4296 | for (User *U : I->users()) { |
| 4297 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4298 | |
| 4299 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4300 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4301 | if (UserBB == DefBB) continue; |
| 4302 | DefIsLiveOut = true; |
| 4303 | break; |
| 4304 | } |
| 4305 | if (!DefIsLiveOut) |
| 4306 | return false; |
| 4307 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 4308 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4309 | for (User *U : Src->users()) { |
| 4310 | Instruction *UI = cast<Instruction>(U); |
| 4311 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4312 | if (UserBB == DefBB) continue; |
| 4313 | // Be conservative. We don't want this xform to end up introducing |
| 4314 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4315 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4316 | return false; |
| 4317 | } |
| 4318 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4319 | // InsertedTruncs - Only insert one trunc in each block once. |
| 4320 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 4321 | |
| 4322 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4323 | for (Use &U : Src->uses()) { |
| 4324 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4325 | |
| 4326 | // Figure out which BB this ext is used in. |
| 4327 | BasicBlock *UserBB = User->getParent(); |
| 4328 | if (UserBB == DefBB) continue; |
| 4329 | |
| 4330 | // Both src and def are live in this block. Rewrite the use. |
| 4331 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 4332 | |
| 4333 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 4334 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4335 | assert(InsertPt != UserBB->end()); |
| 4336 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4337 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4338 | } |
| 4339 | |
| 4340 | // 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] | 4341 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4342 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4343 | MadeChange = true; |
| 4344 | } |
| 4345 | |
| 4346 | return MadeChange; |
| 4347 | } |
| 4348 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 4349 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 4350 | // just after the load if the target can fold this into one extload instruction, |
| 4351 | // with the hope of eliminating some of the other later "and" instructions using |
| 4352 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 4353 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 4354 | // path from the load goes through a phi) are left for isel to potentially |
| 4355 | // remove. |
| 4356 | // |
| 4357 | // For example: |
| 4358 | // |
| 4359 | // b0: |
| 4360 | // x = load i32 |
| 4361 | // ... |
| 4362 | // b1: |
| 4363 | // y = and x, 0xff |
| 4364 | // z = use y |
| 4365 | // |
| 4366 | // becomes: |
| 4367 | // |
| 4368 | // b0: |
| 4369 | // x = load i32 |
| 4370 | // x' = and x, 0xff |
| 4371 | // ... |
| 4372 | // b1: |
| 4373 | // z = use x' |
| 4374 | // |
| 4375 | // whereas: |
| 4376 | // |
| 4377 | // b0: |
| 4378 | // x1 = load i32 |
| 4379 | // ... |
| 4380 | // b1: |
| 4381 | // x2 = load i32 |
| 4382 | // ... |
| 4383 | // b2: |
| 4384 | // x = phi x1, x2 |
| 4385 | // y = and x, 0xff |
| 4386 | // |
| 4387 | // becomes (after a call to optimizeLoadExt for each load): |
| 4388 | // |
| 4389 | // b0: |
| 4390 | // x1 = load i32 |
| 4391 | // x1' = and x1, 0xff |
| 4392 | // ... |
| 4393 | // b1: |
| 4394 | // x2 = load i32 |
| 4395 | // x2' = and x2, 0xff |
| 4396 | // ... |
| 4397 | // b2: |
| 4398 | // x = phi x1', x2' |
| 4399 | // y = and x, 0xff |
| 4400 | // |
| 4401 | |
| 4402 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
| 4403 | |
| 4404 | if (!Load->isSimple() || |
| 4405 | !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy())) |
| 4406 | return false; |
| 4407 | |
| 4408 | // Skip loads we've already transformed or have no reason to transform. |
| 4409 | if (Load->hasOneUse()) { |
| 4410 | User *LoadUser = *Load->user_begin(); |
| 4411 | if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() && |
| 4412 | !dyn_cast<PHINode>(LoadUser)) |
| 4413 | return false; |
| 4414 | } |
| 4415 | |
| 4416 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 4417 | // of the loaded value are needed. |
| 4418 | SmallVector<Instruction *, 8> WorkList; |
| 4419 | SmallPtrSet<Instruction *, 16> Visited; |
| 4420 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 4421 | for (auto *U : Load->users()) |
| 4422 | WorkList.push_back(cast<Instruction>(U)); |
| 4423 | |
| 4424 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 4425 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 4426 | APInt DemandBits(BitWidth, 0); |
| 4427 | APInt WidestAndBits(BitWidth, 0); |
| 4428 | |
| 4429 | while (!WorkList.empty()) { |
| 4430 | Instruction *I = WorkList.back(); |
| 4431 | WorkList.pop_back(); |
| 4432 | |
| 4433 | // Break use-def graph loops. |
| 4434 | if (!Visited.insert(I).second) |
| 4435 | continue; |
| 4436 | |
| 4437 | // For a PHI node, push all of its users. |
| 4438 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 4439 | for (auto *U : Phi->users()) |
| 4440 | WorkList.push_back(cast<Instruction>(U)); |
| 4441 | continue; |
| 4442 | } |
| 4443 | |
| 4444 | switch (I->getOpcode()) { |
| 4445 | case llvm::Instruction::And: { |
| 4446 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4447 | if (!AndC) |
| 4448 | return false; |
| 4449 | APInt AndBits = AndC->getValue(); |
| 4450 | DemandBits |= AndBits; |
| 4451 | // Keep track of the widest and mask we see. |
| 4452 | if (AndBits.ugt(WidestAndBits)) |
| 4453 | WidestAndBits = AndBits; |
| 4454 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 4455 | AndsToMaybeRemove.push_back(I); |
| 4456 | break; |
| 4457 | } |
| 4458 | |
| 4459 | case llvm::Instruction::Shl: { |
| 4460 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4461 | if (!ShlC) |
| 4462 | return false; |
| 4463 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
| 4464 | auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt); |
| 4465 | DemandBits |= ShlDemandBits; |
| 4466 | break; |
| 4467 | } |
| 4468 | |
| 4469 | case llvm::Instruction::Trunc: { |
| 4470 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 4471 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
| 4472 | auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth); |
| 4473 | DemandBits |= TruncBits; |
| 4474 | break; |
| 4475 | } |
| 4476 | |
| 4477 | default: |
| 4478 | return false; |
| 4479 | } |
| 4480 | } |
| 4481 | |
| 4482 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 4483 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 4484 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 4485 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 4486 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 4487 | // followed by an AND. |
| 4488 | // TODO: Look into removing this restriction by fixing backends to either |
| 4489 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 4490 | // a single instruction. |
| 4491 | // |
| 4492 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 4493 | // mask, since these are the only ands that will be removed by isel. |
| 4494 | if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) || |
| 4495 | WidestAndBits != DemandBits) |
| 4496 | return false; |
| 4497 | |
| 4498 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 4499 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 4500 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 4501 | |
| 4502 | // Reject cases that won't be matched as extloads. |
| 4503 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 4504 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 4505 | return false; |
| 4506 | |
| 4507 | IRBuilder<> Builder(Load->getNextNode()); |
| 4508 | auto *NewAnd = dyn_cast<Instruction>( |
| 4509 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
| 4510 | |
| 4511 | // Replace all uses of load with new and (except for the use of load in the |
| 4512 | // new and itself). |
| 4513 | Load->replaceAllUsesWith(NewAnd); |
| 4514 | NewAnd->setOperand(0, Load); |
| 4515 | |
| 4516 | // Remove any and instructions that are now redundant. |
| 4517 | for (auto *And : AndsToMaybeRemove) |
| 4518 | // Check that the and mask is the same as the one we decided to put on the |
| 4519 | // new and. |
| 4520 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 4521 | And->replaceAllUsesWith(NewAnd); |
| 4522 | if (&*CurInstIterator == And) |
| 4523 | CurInstIterator = std::next(And->getIterator()); |
| 4524 | And->eraseFromParent(); |
| 4525 | ++NumAndUses; |
| 4526 | } |
| 4527 | |
| 4528 | ++NumAndsAdded; |
| 4529 | return true; |
| 4530 | } |
| 4531 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4532 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 4533 | /// that is only used once. |
| 4534 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 4535 | auto *I = dyn_cast<Instruction>(V); |
| 4536 | // If it's safe to speculatively execute, then it should not have side |
| 4537 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 4538 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 4539 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4540 | } |
| 4541 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4542 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4543 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4544 | const TargetLowering *TLI, |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4545 | SelectInst *SI) { |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4546 | // If even a predictable select is cheap, then a branch can't be cheaper. |
| 4547 | if (!TLI->isPredictableSelectExpensive()) |
| 4548 | return false; |
| 4549 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4550 | // FIXME: This should use the same heuristics as IfConversion to determine |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4551 | // whether a select is better represented as a branch. |
| 4552 | |
| 4553 | // If metadata tells us that the select condition is obviously predictable, |
| 4554 | // then we want to replace the select with a branch. |
| 4555 | uint64_t TrueWeight, FalseWeight; |
| 4556 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { |
| 4557 | uint64_t Max = std::max(TrueWeight, FalseWeight); |
| 4558 | uint64_t Sum = TrueWeight + FalseWeight; |
Sanjay Patel | c7b91e6 | 2016-05-09 17:31:55 +0000 | [diff] [blame] | 4559 | if (Sum != 0) { |
| 4560 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); |
| 4561 | if (Probability > TLI->getPredictableBranchThreshold()) |
| 4562 | return true; |
| 4563 | } |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4564 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4565 | |
| 4566 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 4567 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 4568 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 4569 | // comparison condition. If the compare has more than one use, there's |
| 4570 | // probably another cmov or setcc around, so it's not worth emitting a branch. |
Sanjay Patel | 5e5f0e9 | 2015-09-28 21:44:46 +0000 | [diff] [blame] | 4571 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4572 | return false; |
| 4573 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4574 | // If either operand of the select is expensive and only needed on one side |
| 4575 | // of the select, we should form a branch. |
| 4576 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 4577 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 4578 | return true; |
| 4579 | |
| 4580 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4581 | } |
| 4582 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4583 | /// If \p isTrue is true, return the true value of \p SI, otherwise return |
| 4584 | /// false value of \p SI. If the true/false value of \p SI is defined by any |
| 4585 | /// select instructions in \p Selects, look through the defining select |
| 4586 | /// instruction until the true/false value is not defined in \p Selects. |
| 4587 | static Value *getTrueOrFalseValue( |
| 4588 | SelectInst *SI, bool isTrue, |
| 4589 | const SmallPtrSet<const Instruction *, 2> &Selects) { |
| 4590 | Value *V; |
| 4591 | |
| 4592 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); |
| 4593 | DefSI = dyn_cast<SelectInst>(V)) { |
Dehao Chen | c32d712 | 2016-09-12 20:29:54 +0000 | [diff] [blame] | 4594 | assert(DefSI->getCondition() == SI->getCondition() && |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4595 | "The condition of DefSI does not match with SI"); |
| 4596 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); |
| 4597 | } |
| 4598 | return V; |
| 4599 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4600 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4601 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 4602 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4603 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4604 | // Find all consecutive select instructions that share the same condition. |
| 4605 | SmallVector<SelectInst *, 2> ASI; |
| 4606 | ASI.push_back(SI); |
| 4607 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); |
| 4608 | It != SI->getParent()->end(); ++It) { |
| 4609 | SelectInst *I = dyn_cast<SelectInst>(&*It); |
| 4610 | if (I && SI->getCondition() == I->getCondition()) { |
| 4611 | ASI.push_back(I); |
| 4612 | } else { |
| 4613 | break; |
| 4614 | } |
| 4615 | } |
| 4616 | |
| 4617 | SelectInst *LastSI = ASI.back(); |
| 4618 | // Increment the current iterator to skip all the rest of select instructions |
| 4619 | // because they will be either "not lowered" or "all lowered" to branch. |
| 4620 | CurInstIterator = std::next(LastSI->getIterator()); |
| 4621 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4622 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 4623 | |
| 4624 | // Can we convert the 'select' to CF ? |
Sanjay Patel | a31b0c0 | 2016-04-26 00:47:39 +0000 | [diff] [blame] | 4625 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond || |
| 4626 | SI->getMetadata(LLVMContext::MD_unpredictable)) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4627 | return false; |
| 4628 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4629 | TargetLowering::SelectSupportKind SelectKind; |
| 4630 | if (VectorCond) |
| 4631 | SelectKind = TargetLowering::VectorMaskSelect; |
| 4632 | else if (SI->getType()->isVectorTy()) |
| 4633 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 4634 | else |
| 4635 | SelectKind = TargetLowering::ScalarValSelect; |
| 4636 | |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4637 | if (TLI->isSelectSupported(SelectKind) && |
| 4638 | !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) |
| 4639 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4640 | |
| 4641 | ModifiedDT = true; |
| 4642 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4643 | // Transform a sequence like this: |
| 4644 | // start: |
| 4645 | // %cmp = cmp uge i32 %a, %b |
| 4646 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 4647 | // |
| 4648 | // Into: |
| 4649 | // start: |
| 4650 | // %cmp = cmp uge i32 %a, %b |
| 4651 | // br i1 %cmp, label %select.true, label %select.false |
| 4652 | // select.true: |
| 4653 | // br label %select.end |
| 4654 | // select.false: |
| 4655 | // br label %select.end |
| 4656 | // select.end: |
| 4657 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 4658 | // |
| 4659 | // In addition, we may sink instructions that produce %c or %d from |
| 4660 | // the entry block into the destination(s) of the new branch. |
| 4661 | // If the true or false blocks do not contain a sunken instruction, that |
| 4662 | // block and its branch may be optimized away. In that case, one side of the |
| 4663 | // first branch will point directly to select.end, and the corresponding PHI |
| 4664 | // predecessor block will be the start block. |
| 4665 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4666 | // First, we split the block containing the select into 2 blocks. |
| 4667 | BasicBlock *StartBlock = SI->getParent(); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4668 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4669 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4670 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4671 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4672 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4673 | |
| 4674 | // These are the new basic blocks for the conditional branch. |
| 4675 | // At least one will become an actual new basic block. |
| 4676 | BasicBlock *TrueBlock = nullptr; |
| 4677 | BasicBlock *FalseBlock = nullptr; |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4678 | BranchInst *TrueBranch = nullptr; |
| 4679 | BranchInst *FalseBranch = nullptr; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4680 | |
| 4681 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 4682 | // them speculatively. |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4683 | for (SelectInst *SI : ASI) { |
| 4684 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 4685 | if (TrueBlock == nullptr) { |
| 4686 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 4687 | EndBlock->getParent(), EndBlock); |
| 4688 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 4689 | } |
| 4690 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 4691 | TrueInst->moveBefore(TrueBranch); |
| 4692 | } |
| 4693 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 4694 | if (FalseBlock == nullptr) { |
| 4695 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 4696 | EndBlock->getParent(), EndBlock); |
| 4697 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 4698 | } |
| 4699 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 4700 | FalseInst->moveBefore(FalseBranch); |
| 4701 | } |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4702 | } |
| 4703 | |
| 4704 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 4705 | // for a new input value to the PHI. |
| 4706 | if (TrueBlock == FalseBlock) { |
| 4707 | assert(TrueBlock == nullptr && |
| 4708 | "Unexpected basic block transform while optimizing select"); |
| 4709 | |
| 4710 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 4711 | EndBlock->getParent(), EndBlock); |
| 4712 | BranchInst::Create(EndBlock, FalseBlock); |
| 4713 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4714 | |
| 4715 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4716 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 4717 | // of the condition, it means that side of the branch goes to the end block |
| 4718 | // directly and the path originates from the start block from the point of |
| 4719 | // view of the new PHI. |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4720 | BasicBlock *TT, *FT; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4721 | if (TrueBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4722 | TT = EndBlock; |
| 4723 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4724 | TrueBlock = StartBlock; |
| 4725 | } else if (FalseBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4726 | TT = TrueBlock; |
| 4727 | FT = EndBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4728 | FalseBlock = StartBlock; |
| 4729 | } else { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4730 | TT = TrueBlock; |
| 4731 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4732 | } |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4733 | IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4734 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4735 | SmallPtrSet<const Instruction *, 2> INS; |
| 4736 | INS.insert(ASI.begin(), ASI.end()); |
| 4737 | // Use reverse iterator because later select may use the value of the |
| 4738 | // earlier select, and we need to propagate value through earlier select |
| 4739 | // to get the PHI operand. |
| 4740 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { |
| 4741 | SelectInst *SI = *It; |
| 4742 | // The select itself is replaced with a PHI Node. |
| 4743 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
| 4744 | PN->takeName(SI); |
| 4745 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); |
| 4746 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4747 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4748 | SI->replaceAllUsesWith(PN); |
| 4749 | SI->eraseFromParent(); |
| 4750 | INS.erase(SI); |
| 4751 | ++NumSelectsExpanded; |
| 4752 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4753 | |
| 4754 | // Instruct OptimizeBlock to skip to the next block. |
| 4755 | CurInstIterator = StartBlock->end(); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4756 | return true; |
| 4757 | } |
| 4758 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 4759 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4760 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 4761 | int SplatElem = -1; |
| 4762 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 4763 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 4764 | return false; |
| 4765 | SplatElem = Mask[i]; |
| 4766 | } |
| 4767 | |
| 4768 | return true; |
| 4769 | } |
| 4770 | |
| 4771 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 4772 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 4773 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 4774 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4775 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4776 | BasicBlock *DefBB = SVI->getParent(); |
| 4777 | |
| 4778 | // Only do this xform if variable vector shifts are particularly expensive. |
| 4779 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 4780 | return false; |
| 4781 | |
| 4782 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 4783 | // constant splat. |
| 4784 | if (!isBroadcastShuffle(SVI)) |
| 4785 | return false; |
| 4786 | |
| 4787 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 4788 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 4789 | |
| 4790 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4791 | for (User *U : SVI->users()) { |
| 4792 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4793 | |
| 4794 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4795 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4796 | if (UserBB == DefBB) continue; |
| 4797 | |
| 4798 | // 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] | 4799 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4800 | |
| 4801 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 4802 | // already have a copy. |
| 4803 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 4804 | |
| 4805 | if (!InsertedShuffle) { |
| 4806 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4807 | assert(InsertPt != UserBB->end()); |
| 4808 | InsertedShuffle = |
| 4809 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 4810 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4811 | } |
| 4812 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4813 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4814 | MadeChange = true; |
| 4815 | } |
| 4816 | |
| 4817 | // If we removed all uses, nuke the shuffle. |
| 4818 | if (SVI->use_empty()) { |
| 4819 | SVI->eraseFromParent(); |
| 4820 | MadeChange = true; |
| 4821 | } |
| 4822 | |
| 4823 | return MadeChange; |
| 4824 | } |
| 4825 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 4826 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 4827 | if (!TLI || !DL) |
| 4828 | return false; |
| 4829 | |
| 4830 | Value *Cond = SI->getCondition(); |
| 4831 | Type *OldType = Cond->getType(); |
| 4832 | LLVMContext &Context = Cond->getContext(); |
| 4833 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 4834 | unsigned RegWidth = RegType.getSizeInBits(); |
| 4835 | |
| 4836 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 4837 | return false; |
| 4838 | |
| 4839 | // If the register width is greater than the type width, expand the condition |
| 4840 | // of the switch instruction and each case constant to the width of the |
| 4841 | // register. By widening the type of the switch condition, subsequent |
| 4842 | // comparisons (for case comparisons) will not need to be extended to the |
| 4843 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 4844 | // where N is the number of cases in the switch. |
| 4845 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 4846 | |
| 4847 | // Zero-extend the switch condition and case constants unless the switch |
| 4848 | // condition is a function argument that is already being sign-extended. |
| 4849 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 4850 | // everything instead. |
| 4851 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 4852 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 4853 | if (Arg->hasSExtAttr()) |
| 4854 | ExtType = Instruction::SExt; |
| 4855 | |
| 4856 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 4857 | ExtInst->insertBefore(SI); |
| 4858 | SI->setCondition(ExtInst); |
| 4859 | for (SwitchInst::CaseIt Case : SI->cases()) { |
| 4860 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 4861 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 4862 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 4863 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 4864 | } |
| 4865 | |
| 4866 | return true; |
| 4867 | } |
| 4868 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4869 | namespace { |
| 4870 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 4871 | /// This class is used to move downward extractelement transition. |
| 4872 | /// E.g., |
| 4873 | /// a = vector_op <2 x i32> |
| 4874 | /// b = extractelement <2 x i32> a, i32 0 |
| 4875 | /// c = scalar_op b |
| 4876 | /// store c |
| 4877 | /// |
| 4878 | /// => |
| 4879 | /// a = vector_op <2 x i32> |
| 4880 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 4881 | /// * d = extractelement <2 x i32> c, i32 0 |
| 4882 | /// * store d |
| 4883 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 4884 | /// transition. |
| 4885 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4886 | /// DataLayout associated with the current module. |
| 4887 | const DataLayout &DL; |
| 4888 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4889 | /// Used to perform some checks on the legality of vector operations. |
| 4890 | const TargetLowering &TLI; |
| 4891 | |
| 4892 | /// Used to estimated the cost of the promoted chain. |
| 4893 | const TargetTransformInfo &TTI; |
| 4894 | |
| 4895 | /// The transition being moved downwards. |
| 4896 | Instruction *Transition; |
| 4897 | /// The sequence of instructions to be promoted. |
| 4898 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 4899 | /// Cost of combining a store and an extract. |
| 4900 | unsigned StoreExtractCombineCost; |
| 4901 | /// Instruction that will be combined with the transition. |
| 4902 | Instruction *CombineInst; |
| 4903 | |
| 4904 | /// \brief The instruction that represents the current end of the transition. |
| 4905 | /// Since we are faking the promotion until we reach the end of the chain |
| 4906 | /// of computation, we need a way to get the current end of the transition. |
| 4907 | Instruction *getEndOfTransition() const { |
| 4908 | if (InstsToBePromoted.empty()) |
| 4909 | return Transition; |
| 4910 | return InstsToBePromoted.back(); |
| 4911 | } |
| 4912 | |
| 4913 | /// \brief Return the index of the original value in the transition. |
| 4914 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 4915 | /// c, is at index 0. |
| 4916 | unsigned getTransitionOriginalValueIdx() const { |
| 4917 | assert(isa<ExtractElementInst>(Transition) && |
| 4918 | "Other kind of transitions are not supported yet"); |
| 4919 | return 0; |
| 4920 | } |
| 4921 | |
| 4922 | /// \brief Return the index of the index in the transition. |
| 4923 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 4924 | /// is at index 1. |
| 4925 | unsigned getTransitionIdx() const { |
| 4926 | assert(isa<ExtractElementInst>(Transition) && |
| 4927 | "Other kind of transitions are not supported yet"); |
| 4928 | return 1; |
| 4929 | } |
| 4930 | |
| 4931 | /// \brief Get the type of the transition. |
| 4932 | /// This is the type of the original value. |
| 4933 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 4934 | /// transition is <2 x i32>. |
| 4935 | Type *getTransitionType() const { |
| 4936 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 4937 | } |
| 4938 | |
| 4939 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 4940 | /// I.e., we have the following sequence: |
| 4941 | /// Def = Transition <ty1> a to <ty2> |
| 4942 | /// b = ToBePromoted <ty2> Def, ... |
| 4943 | /// => |
| 4944 | /// b = ToBePromoted <ty1> a, ... |
| 4945 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 4946 | void promoteImpl(Instruction *ToBePromoted); |
| 4947 | |
| 4948 | /// \brief Check whether or not it is profitable to promote all the |
| 4949 | /// instructions enqueued to be promoted. |
| 4950 | bool isProfitableToPromote() { |
| 4951 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 4952 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 4953 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 4954 | : -1; |
| 4955 | Type *PromotedType = getTransitionType(); |
| 4956 | |
| 4957 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 4958 | unsigned AS = ST->getPointerAddressSpace(); |
| 4959 | unsigned Align = ST->getAlignment(); |
| 4960 | // Check if this store is supported. |
| 4961 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4962 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 4963 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4964 | // If this is not supported, there is no way we can combine |
| 4965 | // the extract with the store. |
| 4966 | return false; |
| 4967 | } |
| 4968 | |
| 4969 | // The scalar chain of computation has to pay for the transition |
| 4970 | // scalar to vector. |
| 4971 | // The vector chain has to account for the combining cost. |
| 4972 | uint64_t ScalarCost = |
| 4973 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 4974 | uint64_t VectorCost = StoreExtractCombineCost; |
| 4975 | for (const auto &Inst : InstsToBePromoted) { |
| 4976 | // Compute the cost. |
| 4977 | // By construction, all instructions being promoted are arithmetic ones. |
| 4978 | // Moreover, one argument is a constant that can be viewed as a splat |
| 4979 | // constant. |
| 4980 | Value *Arg0 = Inst->getOperand(0); |
| 4981 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 4982 | isa<ConstantFP>(Arg0); |
| 4983 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 4984 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4985 | : TargetTransformInfo::OK_AnyValue; |
| 4986 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 4987 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4988 | : TargetTransformInfo::OK_AnyValue; |
| 4989 | ScalarCost += TTI.getArithmeticInstrCost( |
| 4990 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 4991 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 4992 | Arg0OVK, Arg1OVK); |
| 4993 | } |
| 4994 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 4995 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 4996 | return ScalarCost > VectorCost; |
| 4997 | } |
| 4998 | |
| 4999 | /// \brief Generate a constant vector with \p Val with the same |
| 5000 | /// number of elements as the transition. |
| 5001 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 5002 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5003 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 5004 | /// otherwise we generate a vector with as many undef as possible: |
| 5005 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 5006 | /// used at the index of the extract. |
| 5007 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 5008 | unsigned ExtractIdx = UINT_MAX; |
| 5009 | if (!UseSplat) { |
| 5010 | // If we cannot determine where the constant must be, we have to |
| 5011 | // use a splat constant. |
| 5012 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 5013 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 5014 | ExtractIdx = CstVal->getSExtValue(); |
| 5015 | else |
| 5016 | UseSplat = true; |
| 5017 | } |
| 5018 | |
| 5019 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 5020 | if (UseSplat) |
| 5021 | return ConstantVector::getSplat(End, Val); |
| 5022 | |
| 5023 | SmallVector<Constant *, 4> ConstVec; |
| 5024 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 5025 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 5026 | if (Idx == ExtractIdx) |
| 5027 | ConstVec.push_back(Val); |
| 5028 | else |
| 5029 | ConstVec.push_back(UndefVal); |
| 5030 | } |
| 5031 | return ConstantVector::get(ConstVec); |
| 5032 | } |
| 5033 | |
| 5034 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 5035 | /// in \p Use can trigger undefined behavior. |
| 5036 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 5037 | unsigned OperandIdx) { |
| 5038 | // This is not safe to introduce undef when the operand is on |
| 5039 | // the right hand side of a division-like instruction. |
| 5040 | if (OperandIdx != 1) |
| 5041 | return false; |
| 5042 | switch (Use->getOpcode()) { |
| 5043 | default: |
| 5044 | return false; |
| 5045 | case Instruction::SDiv: |
| 5046 | case Instruction::UDiv: |
| 5047 | case Instruction::SRem: |
| 5048 | case Instruction::URem: |
| 5049 | return true; |
| 5050 | case Instruction::FDiv: |
| 5051 | case Instruction::FRem: |
| 5052 | return !Use->hasNoNaNs(); |
| 5053 | } |
| 5054 | llvm_unreachable(nullptr); |
| 5055 | } |
| 5056 | |
| 5057 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5058 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 5059 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 5060 | unsigned CombineCost) |
| 5061 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5062 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 5063 | assert(Transition && "Do not know how to promote null"); |
| 5064 | } |
| 5065 | |
| 5066 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 5067 | bool canPromote(const Instruction *ToBePromoted) const { |
| 5068 | // We could support CastInst too. |
| 5069 | return isa<BinaryOperator>(ToBePromoted); |
| 5070 | } |
| 5071 | |
| 5072 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 5073 | /// by moving downward the transition through. |
| 5074 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 5075 | // Promote only if all the operands can be statically expanded. |
| 5076 | // Indeed, we do not want to introduce any new kind of transitions. |
| 5077 | for (const Use &U : ToBePromoted->operands()) { |
| 5078 | const Value *Val = U.get(); |
| 5079 | if (Val == getEndOfTransition()) { |
| 5080 | // If the use is a division and the transition is on the rhs, |
| 5081 | // we cannot promote the operation, otherwise we may create a |
| 5082 | // division by zero. |
| 5083 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 5084 | return false; |
| 5085 | continue; |
| 5086 | } |
| 5087 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 5088 | !isa<ConstantFP>(Val)) |
| 5089 | return false; |
| 5090 | } |
| 5091 | // Check that the resulting operation is legal. |
| 5092 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 5093 | if (!ISDOpcode) |
| 5094 | return false; |
| 5095 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 5096 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5097 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5098 | } |
| 5099 | |
| 5100 | /// \brief Check whether or not \p Use can be combined |
| 5101 | /// with the transition. |
| 5102 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 5103 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 5104 | |
| 5105 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 5106 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 5107 | InstsToBePromoted.push_back(ToBePromoted); |
| 5108 | } |
| 5109 | |
| 5110 | /// \brief Set the instruction that will be combined with the transition. |
| 5111 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 5112 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 5113 | CombineInst = ToBeCombined; |
| 5114 | } |
| 5115 | |
| 5116 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 5117 | /// is profitable. |
| 5118 | /// \return True if the promotion happened, false otherwise. |
| 5119 | bool promote() { |
| 5120 | // Check if there is something to promote. |
| 5121 | // Right now, if we do not have anything to combine with, |
| 5122 | // we assume the promotion is not profitable. |
| 5123 | if (InstsToBePromoted.empty() || !CombineInst) |
| 5124 | return false; |
| 5125 | |
| 5126 | // Check cost. |
| 5127 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 5128 | return false; |
| 5129 | |
| 5130 | // Promote. |
| 5131 | for (auto &ToBePromoted : InstsToBePromoted) |
| 5132 | promoteImpl(ToBePromoted); |
| 5133 | InstsToBePromoted.clear(); |
| 5134 | return true; |
| 5135 | } |
| 5136 | }; |
| 5137 | } // End of anonymous namespace. |
| 5138 | |
| 5139 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 5140 | // At this point, we know that all the operands of ToBePromoted but Def |
| 5141 | // can be statically promoted. |
| 5142 | // For Def, we need to use its parameter in ToBePromoted: |
| 5143 | // b = ToBePromoted ty1 a |
| 5144 | // Def = Transition ty1 b to ty2 |
| 5145 | // Move the transition down. |
| 5146 | // 1. Replace all uses of the promoted operation by the transition. |
| 5147 | // = ... b => = ... Def. |
| 5148 | assert(ToBePromoted->getType() == Transition->getType() && |
| 5149 | "The type of the result of the transition does not match " |
| 5150 | "the final type"); |
| 5151 | ToBePromoted->replaceAllUsesWith(Transition); |
| 5152 | // 2. Update the type of the uses. |
| 5153 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 5154 | Type *TransitionTy = getTransitionType(); |
| 5155 | ToBePromoted->mutateType(TransitionTy); |
| 5156 | // 3. Update all the operands of the promoted operation with promoted |
| 5157 | // operands. |
| 5158 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 5159 | for (Use &U : ToBePromoted->operands()) { |
| 5160 | Value *Val = U.get(); |
| 5161 | Value *NewVal = nullptr; |
| 5162 | if (Val == Transition) |
| 5163 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5164 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 5165 | isa<ConstantFP>(Val)) { |
| 5166 | // Use a splat constant if it is not safe to use undef. |
| 5167 | NewVal = getConstantVector( |
| 5168 | cast<Constant>(Val), |
| 5169 | isa<UndefValue>(Val) || |
| 5170 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 5171 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 5172 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 5173 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5174 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 5175 | } |
| 5176 | Transition->removeFromParent(); |
| 5177 | Transition->insertAfter(ToBePromoted); |
| 5178 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 5179 | } |
| 5180 | |
| 5181 | /// Some targets can do store(extractelement) with one instruction. |
| 5182 | /// Try to push the extractelement towards the stores when the target |
| 5183 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5184 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5185 | unsigned CombineCost = UINT_MAX; |
| 5186 | if (DisableStoreExtract || !TLI || |
| 5187 | (!StressStoreExtract && |
| 5188 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 5189 | Inst->getOperand(1), CombineCost))) |
| 5190 | return false; |
| 5191 | |
| 5192 | // At this point we know that Inst is a vector to scalar transition. |
| 5193 | // Try to move it down the def-use chain, until: |
| 5194 | // - We can combine the transition with its single use |
| 5195 | // => we got rid of the transition. |
| 5196 | // - We escape the current basic block |
| 5197 | // => we would need to check that we are moving it at a cheaper place and |
| 5198 | // we do not do that for now. |
| 5199 | BasicBlock *Parent = Inst->getParent(); |
| 5200 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5201 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5202 | // If the transition has more than one use, assume this is not going to be |
| 5203 | // beneficial. |
| 5204 | while (Inst->hasOneUse()) { |
| 5205 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 5206 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 5207 | |
| 5208 | if (ToBePromoted->getParent() != Parent) { |
| 5209 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 5210 | << ToBePromoted->getParent()->getName() |
| 5211 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 5212 | return false; |
| 5213 | } |
| 5214 | |
| 5215 | if (VPH.canCombine(ToBePromoted)) { |
| 5216 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 5217 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 5218 | VPH.recordCombineInstruction(ToBePromoted); |
| 5219 | bool Changed = VPH.promote(); |
| 5220 | NumStoreExtractExposed += Changed; |
| 5221 | return Changed; |
| 5222 | } |
| 5223 | |
| 5224 | DEBUG(dbgs() << "Try promoting.\n"); |
| 5225 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 5226 | return false; |
| 5227 | |
| 5228 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 5229 | |
| 5230 | VPH.enqueueForPromotion(ToBePromoted); |
| 5231 | Inst = ToBePromoted; |
| 5232 | } |
| 5233 | return false; |
| 5234 | } |
| 5235 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5236 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5237 | // Bail out if we inserted the instruction to prevent optimizations from |
| 5238 | // stepping on each other's toes. |
| 5239 | if (InsertedInsts.count(I)) |
| 5240 | return false; |
| 5241 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5242 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 5243 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 5244 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 5245 | // trivial PHI, go ahead and zap it here. |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 5246 | if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5247 | P->replaceAllUsesWith(V); |
| 5248 | P->eraseFromParent(); |
| 5249 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5250 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5251 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5252 | return false; |
| 5253 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5254 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5255 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5256 | // If the source of the cast is a constant, then this should have |
| 5257 | // already been constant folded. The only reason NOT to constant fold |
| 5258 | // it is if something (e.g. LSR) was careful to place the constant |
| 5259 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 5260 | // the address of globals out of a loop). If this is the case, we don't |
| 5261 | // want to forward-subst the cast. |
| 5262 | if (isa<Constant>(CI->getOperand(0))) |
| 5263 | return false; |
| 5264 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5265 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5266 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5267 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5268 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5269 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 5270 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5271 | if (TLI && |
| 5272 | TLI->getTypeAction(CI->getContext(), |
| 5273 | TLI->getValueType(*DL, CI->getType())) == |
| 5274 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5275 | return SinkCast(CI); |
| 5276 | } else { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5277 | bool MadeChange = moveExtToFormExtLoad(I); |
| 5278 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5279 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5280 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5281 | return false; |
| 5282 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5283 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5284 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 5285 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 5286 | return OptimizeCmpExpression(CI, TLI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5287 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5288 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5289 | stripInvariantGroupMetadata(*LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5290 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5291 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5292 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5293 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 5294 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5295 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 5296 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5297 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5298 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5299 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5300 | stripInvariantGroupMetadata(*SI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5301 | if (TLI) { |
| 5302 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5303 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5304 | SI->getOperand(0)->getType(), AS); |
| 5305 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5306 | return false; |
| 5307 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5308 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5309 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 5310 | |
| 5311 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 5312 | BinOp->getOpcode() == Instruction::LShr)) { |
| 5313 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 5314 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5315 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5316 | |
| 5317 | return false; |
| 5318 | } |
| 5319 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5320 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5321 | if (GEPI->hasAllZeroIndices()) { |
| 5322 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 5323 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 5324 | GEPI->getName(), GEPI); |
| 5325 | GEPI->replaceAllUsesWith(NC); |
| 5326 | GEPI->eraseFromParent(); |
| 5327 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5328 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5329 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5330 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5331 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5332 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5333 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5334 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5335 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5336 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5337 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5338 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5339 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5340 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5341 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5342 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5343 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 5344 | return optimizeSwitchInst(Switch); |
| 5345 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5346 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5347 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5348 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5349 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5350 | } |
| 5351 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5352 | /// Given an OR instruction, check to see if this is a bitreverse |
| 5353 | /// idiom. If so, insert the new intrinsic and return true. |
| 5354 | static bool makeBitReverse(Instruction &I, const DataLayout &DL, |
| 5355 | const TargetLowering &TLI) { |
| 5356 | if (!I.getType()->isIntegerTy() || |
| 5357 | !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, |
| 5358 | TLI.getValueType(DL, I.getType(), true))) |
| 5359 | return false; |
| 5360 | |
| 5361 | SmallVector<Instruction*, 4> Insts; |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 5362 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5363 | return false; |
| 5364 | Instruction *LastInst = Insts.back(); |
| 5365 | I.replaceAllUsesWith(LastInst); |
| 5366 | RecursivelyDeleteTriviallyDeadInstructions(&I); |
| 5367 | return true; |
| 5368 | } |
| 5369 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5370 | // In this pass we look for GEP and cast instructions that are used |
| 5371 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 5372 | // selection. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5373 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 5374 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 5375 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 5376 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 5377 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5378 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5379 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5380 | if (ModifiedDT) |
| 5381 | return true; |
| 5382 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 5383 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5384 | bool MadeBitReverse = true; |
| 5385 | while (TLI && MadeBitReverse) { |
| 5386 | MadeBitReverse = false; |
| 5387 | for (auto &I : reverse(BB)) { |
| 5388 | if (makeBitReverse(I, *DL, *TLI)) { |
| 5389 | MadeBitReverse = MadeChange = true; |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 5390 | ModifiedDT = true; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5391 | break; |
| 5392 | } |
| 5393 | } |
| 5394 | } |
James Molloy | 3ef84c4 | 2016-01-15 10:36:01 +0000 | [diff] [blame] | 5395 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Junmo Park | 7d6c5f1 | 2016-01-28 09:42:39 +0000 | [diff] [blame] | 5396 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5397 | return MadeChange; |
| 5398 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5399 | |
| 5400 | // 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] | 5401 | // 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] | 5402 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5403 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5404 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5405 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 5406 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5407 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5408 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5409 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 5410 | // Leave dbg.values that refer to an alloca alone. These |
| 5411 | // instrinsics describe the address of a variable (= the alloca) |
| 5412 | // being taken. They should not be moved next to the alloca |
| 5413 | // (and to the beginning of the scope), but rather stay close to |
| 5414 | // where said address is used. |
| 5415 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5416 | PrevNonDbgInst = Insn; |
| 5417 | continue; |
| 5418 | } |
| 5419 | |
| 5420 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 5421 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 5422 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 5423 | // after it. |
| 5424 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 5425 | continue; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5426 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 5427 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 5428 | if (isa<PHINode>(VI)) |
| 5429 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 5430 | else |
| 5431 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5432 | MadeChange = true; |
| 5433 | ++NumDbgValueMoved; |
| 5434 | } |
| 5435 | } |
| 5436 | } |
| 5437 | return MadeChange; |
| 5438 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5439 | |
| 5440 | // If there is a sequence that branches based on comparing a single bit |
| 5441 | // against zero that can be combined into a single instruction, and the |
| 5442 | // target supports folding these into a single instruction, sink the |
| 5443 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 5444 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 5445 | // searched for. |
| 5446 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 5447 | if (!EnableAndCmpSinking) |
| 5448 | return false; |
| 5449 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 5450 | return false; |
| 5451 | bool MadeChange = false; |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5452 | for (BasicBlock &BB : F) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5453 | // Does this BB end with the following? |
| 5454 | // %andVal = and %val, #single-bit-set |
| 5455 | // %icmpVal = icmp %andResult, 0 |
| 5456 | // br i1 %cmpVal label %dest1, label %dest2" |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5457 | BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator()); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5458 | if (!Brcc || !Brcc->isConditional()) |
| 5459 | continue; |
| 5460 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5461 | if (!Cmp || Cmp->getParent() != &BB) |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5462 | continue; |
| 5463 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 5464 | if (!Zero || !Zero->isZero()) |
| 5465 | continue; |
| 5466 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5467 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB) |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5468 | continue; |
| 5469 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 5470 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 5471 | continue; |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5472 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump()); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5473 | |
| 5474 | // Push the "and; icmp" for any users that are conditional branches. |
| 5475 | // Since there can only be one branch use per BB, we don't need to keep |
| 5476 | // track of which BBs we insert into. |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5477 | for (Use &TheUse : Cmp->uses()) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5478 | // Find brcc use. |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5479 | BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5480 | if (!BrccUser || !BrccUser->isConditional()) |
| 5481 | continue; |
| 5482 | BasicBlock *UserBB = BrccUser->getParent(); |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5483 | if (UserBB == &BB) continue; |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5484 | DEBUG(dbgs() << "found Brcc use\n"); |
| 5485 | |
| 5486 | // Sink the "and; icmp" to use. |
| 5487 | MadeChange = true; |
| 5488 | BinaryOperator *NewAnd = |
| 5489 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 5490 | BrccUser); |
| 5491 | CmpInst *NewCmp = |
| 5492 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 5493 | "", BrccUser); |
| 5494 | TheUse = NewCmp; |
| 5495 | ++NumAndCmpsMoved; |
| 5496 | DEBUG(BrccUser->getParent()->dump()); |
| 5497 | } |
| 5498 | } |
| 5499 | return MadeChange; |
| 5500 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5501 | |
| 5502 | /// \brief Scale down both weights to fit into uint32_t. |
| 5503 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 5504 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 5505 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 5506 | NewTrue = NewTrue / Scale; |
| 5507 | NewFalse = NewFalse / Scale; |
| 5508 | } |
| 5509 | |
| 5510 | /// \brief Some targets prefer to split a conditional branch like: |
| 5511 | /// \code |
| 5512 | /// %0 = icmp ne i32 %a, 0 |
| 5513 | /// %1 = icmp ne i32 %b, 0 |
| 5514 | /// %or.cond = or i1 %0, %1 |
| 5515 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 5516 | /// \endcode |
| 5517 | /// into multiple branch instructions like: |
| 5518 | /// \code |
| 5519 | /// bb1: |
| 5520 | /// %0 = icmp ne i32 %a, 0 |
| 5521 | /// br i1 %0, label %TrueBB, label %bb2 |
| 5522 | /// bb2: |
| 5523 | /// %1 = icmp ne i32 %b, 0 |
| 5524 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 5525 | /// \endcode |
| 5526 | /// This usually allows instruction selection to do even further optimizations |
| 5527 | /// and combine the compare with the branch instruction. Currently this is |
| 5528 | /// applied for targets which have "cheap" jump instructions. |
| 5529 | /// |
| 5530 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 5531 | /// |
| 5532 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 5533 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5534 | return false; |
| 5535 | |
| 5536 | bool MadeChange = false; |
| 5537 | for (auto &BB : F) { |
| 5538 | // Does this BB end with the following? |
| 5539 | // %cond1 = icmp|fcmp|binary instruction ... |
| 5540 | // %cond2 = icmp|fcmp|binary instruction ... |
| 5541 | // %cond.or = or|and i1 %cond1, cond2 |
| 5542 | // br i1 %cond.or label %dest1, label %dest2" |
| 5543 | BinaryOperator *LogicOp; |
| 5544 | BasicBlock *TBB, *FBB; |
| 5545 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 5546 | continue; |
| 5547 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 5548 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 5549 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 5550 | continue; |
| 5551 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5552 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5553 | Value *Cond1, *Cond2; |
| 5554 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 5555 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5556 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5557 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 5558 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5559 | Opc = Instruction::Or; |
| 5560 | else |
| 5561 | continue; |
| 5562 | |
| 5563 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 5564 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 5565 | continue; |
| 5566 | |
| 5567 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 5568 | |
| 5569 | // Create a new BB. |
Duncan P. N. Exon Smith | a848c47 | 2016-02-21 19:52:15 +0000 | [diff] [blame] | 5570 | auto TmpBB = |
| 5571 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", |
| 5572 | BB.getParent(), BB.getNextNode()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5573 | |
| 5574 | // Update original basic block by using the first condition directly by the |
| 5575 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5576 | Br1->setCondition(Cond1); |
| 5577 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5578 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5579 | // Depending on the conditon we have to either replace the true or the false |
| 5580 | // successor of the original branch instruction. |
| 5581 | if (Opc == Instruction::And) |
| 5582 | Br1->setSuccessor(0, TmpBB); |
| 5583 | else |
| 5584 | Br1->setSuccessor(1, TmpBB); |
| 5585 | |
| 5586 | // Fill in the new basic block. |
| 5587 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5588 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 5589 | I->removeFromParent(); |
| 5590 | I->insertBefore(Br2); |
| 5591 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5592 | |
| 5593 | // Update PHI nodes in both successors. The original BB needs to be |
| 5594 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 5595 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 5596 | // incoming edge to the PHI nodes, because both branch instructions target |
| 5597 | // now the same successor. Depending on the original branch condition |
| 5598 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
| 5599 | // we perfrom the correct update for the PHI nodes. |
| 5600 | // This doesn't change the successor order of the just created branch |
| 5601 | // instruction (or any other instruction). |
| 5602 | if (Opc == Instruction::Or) |
| 5603 | std::swap(TBB, FBB); |
| 5604 | |
| 5605 | // Replace the old BB with the new BB. |
| 5606 | for (auto &I : *TBB) { |
| 5607 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5608 | if (!PN) |
| 5609 | break; |
| 5610 | int i; |
| 5611 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 5612 | PN->setIncomingBlock(i, TmpBB); |
| 5613 | } |
| 5614 | |
| 5615 | // Add another incoming edge form the new BB. |
| 5616 | for (auto &I : *FBB) { |
| 5617 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5618 | if (!PN) |
| 5619 | break; |
| 5620 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 5621 | PN->addIncoming(Val, TmpBB); |
| 5622 | } |
| 5623 | |
| 5624 | // Update the branch weights (from SelectionDAGBuilder:: |
| 5625 | // FindMergedConditions). |
| 5626 | if (Opc == Instruction::Or) { |
| 5627 | // Codegen X | Y as: |
| 5628 | // BB1: |
| 5629 | // jmp_if_X TBB |
| 5630 | // jmp TmpBB |
| 5631 | // TmpBB: |
| 5632 | // jmp_if_Y TBB |
| 5633 | // jmp FBB |
| 5634 | // |
| 5635 | |
| 5636 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 5637 | // The requirement is that |
| 5638 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 5639 | // = TrueProb for orignal BB. |
| 5640 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5641 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 5642 | // assumes that |
| 5643 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 5644 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 5645 | // TmpBB, but the math is more complicated. |
| 5646 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 5647 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5648 | uint64_t NewTrueWeight = TrueWeight; |
| 5649 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 5650 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5651 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5652 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5653 | |
| 5654 | NewTrueWeight = TrueWeight; |
| 5655 | NewFalseWeight = 2 * FalseWeight; |
| 5656 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5657 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5658 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5659 | } |
| 5660 | } else { |
| 5661 | // Codegen X & Y as: |
| 5662 | // BB1: |
| 5663 | // jmp_if_X TmpBB |
| 5664 | // jmp FBB |
| 5665 | // TmpBB: |
| 5666 | // jmp_if_Y TBB |
| 5667 | // jmp FBB |
| 5668 | // |
| 5669 | // This requires creation of TmpBB after CurBB. |
| 5670 | |
| 5671 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 5672 | // The requirement is that |
| 5673 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 5674 | // = FalseProb for orignal BB. |
| 5675 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5676 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 5677 | // assumes that |
| 5678 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 5679 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 5680 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5681 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 5682 | uint64_t NewFalseWeight = FalseWeight; |
| 5683 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5684 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5685 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5686 | |
| 5687 | NewTrueWeight = 2 * TrueWeight; |
| 5688 | NewFalseWeight = FalseWeight; |
| 5689 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5690 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5691 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5692 | } |
| 5693 | } |
| 5694 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5695 | // 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] | 5696 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5697 | ModifiedDT = true; |
| 5698 | |
| 5699 | MadeChange = true; |
| 5700 | |
| 5701 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 5702 | TmpBB->dump()); |
| 5703 | } |
| 5704 | return MadeChange; |
| 5705 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5706 | |
| 5707 | void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) { |
Piotr Padlewski | ea09288 | 2015-09-17 20:25:07 +0000 | [diff] [blame] | 5708 | if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group)) |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5709 | I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID()); |
| 5710 | } |