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