Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1 | //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass munges the code in the input function to better prepare it for |
Gordon Henriksen | 829046b | 2008-05-08 17:46:35 +0000 | [diff] [blame] | 11 | // SelectionDAG-based code generation. This works around limitations in it's |
| 12 | // basic-block-at-a-time approach. It should eventually be removed. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Quentin Colombet | a349084 | 2014-02-22 00:07:45 +0000 | [diff] [blame] | 16 | #include "llvm/CodeGen/Passes.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/DenseMap.h" |
| 18 | #include "llvm/ADT/SmallSet.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/TargetTransformInfo.h" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 24 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 25 | #include "llvm/IR/Constants.h" |
| 26 | #include "llvm/IR/DataLayout.h" |
| 27 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 30 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 31 | #include "llvm/IR/IRBuilder.h" |
| 32 | #include "llvm/IR/InlineAsm.h" |
| 33 | #include "llvm/IR/Instructions.h" |
| 34 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 35 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 36 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 38 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 39 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 40 | #include "llvm/Pass.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 41 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 42 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 43 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 44 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 45 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 47 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 49 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 50 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 51 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 52 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 53 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 54 | #define DEBUG_TYPE "codegenprepare" |
| 55 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 56 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 57 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 58 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 59 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 60 | "sunken Cmps"); |
| 61 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 62 | "of sunken Casts"); |
| 63 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 64 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 65 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 66 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 67 | STATISTIC(NumAndsAdded, |
| 68 | "Number of and mask instructions added to form ext loads"); |
| 69 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 70 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 71 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 72 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 73 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 74 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 75 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 76 | static cl::opt<bool> DisableBranchOpts( |
| 77 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 78 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 79 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 80 | static cl::opt<bool> |
| 81 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 82 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 83 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 84 | static cl::opt<bool> DisableSelectToBranch( |
| 85 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 86 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 87 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 88 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 89 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 90 | cl::desc("Address sinking in CGP using GEPs.")); |
| 91 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 92 | static cl::opt<bool> EnableAndCmpSinking( |
| 93 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 94 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 95 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 96 | static cl::opt<bool> DisableStoreExtract( |
| 97 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 98 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 99 | |
| 100 | static cl::opt<bool> StressStoreExtract( |
| 101 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 102 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 103 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 104 | static cl::opt<bool> DisableExtLdPromotion( |
| 105 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 106 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 107 | "CodeGenPrepare")); |
| 108 | |
| 109 | static cl::opt<bool> StressExtLdPromotion( |
| 110 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 111 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 112 | "optimization in CodeGenPrepare")); |
| 113 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 114 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 115 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 116 | typedef PointerIntPair<Type *, 1, bool> TypeIsSExt; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 117 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 118 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 119 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 120 | class CodeGenPrepare : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 121 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 122 | const TargetLowering *TLI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 123 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 124 | const TargetLibraryInfo *TLInfo; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 125 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 126 | /// As we scan instructions optimizing them, this is the next instruction |
| 127 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 128 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 129 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 130 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 131 | /// This allows us to avoid inserting duplicate code for blocks with |
| 132 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 133 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 134 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 135 | /// Keeps track of all instructions inserted for the current function. |
| 136 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 137 | /// Keeps track of the type of the related instruction before their |
| 138 | /// promotion for the current function. |
| 139 | InstrToOrigTy PromotedInsts; |
| 140 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 141 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 142 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 143 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 144 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 145 | bool OptSize; |
| 146 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 147 | /// DataLayout for the Function being processed. |
| 148 | const DataLayout *DL; |
| 149 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 150 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 151 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 152 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 153 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 154 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 155 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 156 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 157 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 158 | const char *getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 159 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 160 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 161 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 162 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 163 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 164 | } |
| 165 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 166 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 167 | bool eliminateFallThrough(Function &F); |
| 168 | bool eliminateMostlyEmptyBlocks(Function &F); |
| 169 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 170 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
| 171 | bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 172 | bool optimizeInst(Instruction *I, bool& ModifiedDT); |
| 173 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 174 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 175 | bool optimizeInlineAsmInst(CallInst *CS); |
| 176 | bool optimizeCallInst(CallInst *CI, bool& ModifiedDT); |
| 177 | bool moveExtToFormExtLoad(Instruction *&I); |
| 178 | bool optimizeExtUses(Instruction *I); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 179 | bool optimizeLoadExt(LoadInst *I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 180 | bool optimizeSelectInst(SelectInst *SI); |
| 181 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 182 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 183 | bool optimizeExtractElementInst(Instruction *Inst); |
| 184 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 185 | bool placeDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 186 | bool sinkAndCmp(Function &F); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 187 | bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 188 | Instruction *&Inst, |
| 189 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 190 | unsigned CreatedInstCost); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 191 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 192 | bool simplifyOffsetableRelocate(Instruction &I); |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 193 | void stripInvariantGroupMetadata(Instruction &I); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 194 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 195 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 196 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 197 | char CodeGenPrepare::ID = 0; |
Jiangning Liu | d623c52 | 2014-06-11 07:04:37 +0000 | [diff] [blame] | 198 | INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare", |
| 199 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 200 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 201 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 202 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 203 | } |
| 204 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 205 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 206 | if (skipOptnoneFunction(F)) |
| 207 | return false; |
| 208 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 209 | DL = &F.getParent()->getDataLayout(); |
| 210 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 211 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 212 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 213 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 214 | PromotedInsts.clear(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 215 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 216 | ModifiedDT = false; |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 217 | if (TM) |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 218 | TLI = TM->getSubtargetImpl(F)->getTargetLowering(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 219 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 220 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 221 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 222 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 223 | /// This optimization identifies DIV instructions that can be |
| 224 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 225 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 226 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 227 | TLI->getBypassSlowDivWidths(); |
Evan Cheng | 71be12b | 2012-09-14 21:25:34 +0000 | [diff] [blame] | 228 | for (Function::iterator I = F.begin(); I != F.end(); I++) |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 229 | EverMadeChange |= bypassSlowDivision(F, I, BypassWidths); |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 230 | } |
| 231 | |
| 232 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 233 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 234 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 235 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 236 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 237 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 238 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 239 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 240 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 241 | // If there is a mask, compare against zero, and branch that can be combined |
| 242 | // into a single target instruction, push the mask and compare into branch |
| 243 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 244 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 245 | if (!DisableBranchOpts) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 246 | EverMadeChange |= sinkAndCmp(F); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 247 | EverMadeChange |= splitBranchCondition(F); |
| 248 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 249 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 250 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 251 | while (MadeChange) { |
| 252 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 253 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 254 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 255 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 256 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 257 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 258 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 259 | if (ModifiedDTOnIteration) |
| 260 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 261 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 262 | EverMadeChange |= MadeChange; |
| 263 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 264 | |
| 265 | SunkAddrs.clear(); |
| 266 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 267 | if (!DisableBranchOpts) { |
| 268 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 269 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [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 | 97b9359 | 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 | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 281 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 282 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 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 | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 289 | |
Bill Wendling | f3614fd | 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 | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 295 | |
Nadav Rotem | 7040999 | 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) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 299 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 300 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 301 | EverMadeChange |= MadeChange; |
| 302 | } |
| 303 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 304 | if (!DisableGCOpts) { |
| 305 | SmallVector<Instruction *, 2> Statepoints; |
| 306 | for (BasicBlock &BB : F) |
| 307 | for (Instruction &I : BB) |
| 308 | if (isStatepoint(I)) |
| 309 | Statepoints.push_back(&I); |
| 310 | for (auto &I : Statepoints) |
| 311 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 312 | } |
| 313 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 314 | return EverMadeChange; |
| 315 | } |
| 316 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 317 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 318 | /// basic blocks has a single successor pointing to the other basic block, |
| 319 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 320 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 321 | bool Changed = false; |
| 322 | // Scan all of the blocks in the function, except for the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 323 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 324 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 325 | // If the destination block has a single pred, then this is a trivial |
| 326 | // edge, just collapse it. |
| 327 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 328 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 329 | // Don't merge if BB's address is taken. |
| 330 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 331 | |
| 332 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 333 | if (Term && !Term->isConditional()) { |
| 334 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 335 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 336 | // Remember if SinglePred was the entry block of the function. |
| 337 | // If so, we will need to move BB back to the entry position. |
| 338 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 339 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 340 | |
| 341 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 342 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 343 | |
| 344 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 345 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 346 | } |
| 347 | } |
| 348 | return Changed; |
| 349 | } |
| 350 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 351 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 352 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 353 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 354 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 355 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 356 | bool MadeChange = false; |
| 357 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 358 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 359 | BasicBlock *BB = &*I++; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 360 | |
| 361 | // If this block doesn't end with an uncond branch, ignore it. |
| 362 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 363 | if (!BI || !BI->isUnconditional()) |
| 364 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 365 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 366 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 367 | // node, then other stuff is happening here. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 368 | BasicBlock::iterator BBI = BI->getIterator(); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 369 | if (BBI != BB->begin()) { |
| 370 | --BBI; |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 371 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 372 | if (BBI == BB->begin()) |
| 373 | break; |
| 374 | --BBI; |
| 375 | } |
| 376 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 377 | continue; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 378 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 379 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 380 | // Do not break infinite loops. |
| 381 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 382 | if (DestBB == BB) |
| 383 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 384 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 385 | if (!canMergeBlocks(BB, DestBB)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 386 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 387 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 388 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 389 | MadeChange = true; |
| 390 | } |
| 391 | return MadeChange; |
| 392 | } |
| 393 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 394 | /// Return true if we can merge BB into DestBB if there is a single |
| 395 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 396 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 397 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 398 | const BasicBlock *DestBB) const { |
| 399 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 400 | // the successor. If there are more complex condition (e.g. preheaders), |
| 401 | // don't mess around with them. |
| 402 | BasicBlock::const_iterator BBI = BB->begin(); |
| 403 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 404 | for (const User *U : PN->users()) { |
| 405 | const Instruction *UI = cast<Instruction>(U); |
| 406 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 407 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 408 | // If User is inside DestBB block and it is a PHINode then check |
| 409 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 410 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 411 | if (UI->getParent() == DestBB) { |
| 412 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 413 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 414 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 415 | if (Insn && Insn->getParent() == BB && |
| 416 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 417 | return false; |
| 418 | } |
| 419 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 420 | } |
| 421 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 422 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 423 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 424 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 425 | // can't merge the block. |
| 426 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 427 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 428 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 429 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 430 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 431 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 432 | // It is faster to get preds from a PHI than with pred_iterator. |
| 433 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 434 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 435 | } else { |
| 436 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 437 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 438 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 439 | // Walk the preds of DestBB. |
| 440 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 441 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 442 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 443 | BBI = DestBB->begin(); |
| 444 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 445 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 446 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 447 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 448 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 449 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 450 | if (V2PN->getParent() == BB) |
| 451 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 452 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 453 | // If there is a conflict, bail out. |
| 454 | if (V1 != V2) return false; |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | return true; |
| 460 | } |
| 461 | |
| 462 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 463 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 464 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 465 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 466 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 467 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 468 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 469 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 470 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 471 | // If the destination block has a single pred, then this is a trivial edge, |
| 472 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 473 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 474 | if (SinglePred != DestBB) { |
| 475 | // Remember if SinglePred was the entry block of the function. If so, we |
| 476 | // will need to move BB back to the entry position. |
| 477 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 478 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 479 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 480 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 481 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 482 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 483 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 484 | return; |
| 485 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 486 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 487 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 488 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 489 | // to handle the new incoming edges it is about to have. |
| 490 | PHINode *PN; |
| 491 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 492 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 493 | // Remove the incoming value for BB, and remember it. |
| 494 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 495 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 496 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 497 | // value that dominates BB. |
| 498 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 499 | if (InValPhi && InValPhi->getParent() == BB) { |
| 500 | // Add all of the input values of the input PHI as inputs of this phi. |
| 501 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 502 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 503 | InValPhi->getIncomingBlock(i)); |
| 504 | } else { |
| 505 | // Otherwise, add one instance of the dominating value for each edge that |
| 506 | // we will be adding. |
| 507 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 508 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 509 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 510 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 511 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 512 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 513 | } |
| 514 | } |
| 515 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 516 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 517 | // The PHIs are now updated, change everything that refers to BB to use |
| 518 | // DestBB and remove BB. |
| 519 | BB->replaceAllUsesWith(DestBB); |
| 520 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 521 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 522 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 523 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 524 | } |
| 525 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 526 | // Computes a map of base pointer relocation instructions to corresponding |
| 527 | // derived pointer relocation instructions given a vector of all relocate calls |
| 528 | static void computeBaseDerivedRelocateMap( |
| 529 | const SmallVectorImpl<User *> &AllRelocateCalls, |
| 530 | DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> & |
| 531 | RelocateInstMap) { |
| 532 | // Collect information in two maps: one primarily for locating the base object |
| 533 | // while filling the second map; the second map is the final structure holding |
| 534 | // a mapping between Base and corresponding Derived relocate calls |
| 535 | DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap; |
| 536 | for (auto &U : AllRelocateCalls) { |
| 537 | GCRelocateOperands ThisRelocate(U); |
| 538 | IntrinsicInst *I = cast<IntrinsicInst>(U); |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 539 | auto K = std::make_pair(ThisRelocate.getBasePtrIndex(), |
| 540 | ThisRelocate.getDerivedPtrIndex()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 541 | RelocateIdxMap.insert(std::make_pair(K, I)); |
| 542 | } |
| 543 | for (auto &Item : RelocateIdxMap) { |
| 544 | std::pair<unsigned, unsigned> Key = Item.first; |
| 545 | if (Key.first == Key.second) |
| 546 | // Base relocation: nothing to insert |
| 547 | continue; |
| 548 | |
| 549 | IntrinsicInst *I = Item.second; |
| 550 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 551 | |
| 552 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 553 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 554 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 555 | // TODO: We might want to insert a new base object relocate and gep off |
| 556 | // that, if there are enough derived object relocates. |
| 557 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 558 | |
| 559 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 560 | } |
| 561 | } |
| 562 | |
| 563 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 564 | // small integer constants |
| 565 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 566 | SmallVectorImpl<Value *> &OffsetV) { |
| 567 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 568 | // Only accept small constant integer operands |
| 569 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 570 | if (!Op || Op->getZExtValue() > 20) |
| 571 | return false; |
| 572 | } |
| 573 | |
| 574 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 575 | OffsetV.push_back(GEP->getOperand(i)); |
| 576 | return true; |
| 577 | } |
| 578 | |
| 579 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 580 | // replace, computes a replacement, and affects it. |
| 581 | static bool |
| 582 | simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase, |
| 583 | const SmallVectorImpl<IntrinsicInst *> &Targets) { |
| 584 | bool MadeChange = false; |
| 585 | for (auto &ToReplace : Targets) { |
| 586 | GCRelocateOperands MasterRelocate(RelocatedBase); |
| 587 | GCRelocateOperands ThisRelocate(ToReplace); |
| 588 | |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 589 | assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 590 | "Not relocating a derived object of the original base object"); |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 591 | if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 592 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 593 | continue; |
| 594 | } |
| 595 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 596 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 597 | // Base and derived relocates are in different basic blocks. |
| 598 | // In this case transform is only valid when base dominates derived |
| 599 | // relocate. However it would be too expensive to check dominance |
| 600 | // for each such relocate, so we skip the whole transformation. |
| 601 | continue; |
| 602 | } |
| 603 | |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 604 | Value *Base = ThisRelocate.getBasePtr(); |
| 605 | auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 606 | if (!Derived || Derived->getPointerOperand() != Base) |
| 607 | continue; |
| 608 | |
| 609 | SmallVector<Value *, 2> OffsetV; |
| 610 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 611 | continue; |
| 612 | |
| 613 | // Create a Builder and replace the target callsite with a gep |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 614 | assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator"); |
| 615 | |
| 616 | // Insert after RelocatedBase |
| 617 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 618 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 619 | |
| 620 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 621 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 622 | // match, and we should reuse it to get the derived pointer. But it could be |
| 623 | // cases like this: |
| 624 | // bb1: |
| 625 | // ... |
| 626 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 627 | // br label %merge |
| 628 | // |
| 629 | // bb2: |
| 630 | // ... |
| 631 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 632 | // br label %merge |
| 633 | // |
| 634 | // merge: |
| 635 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 636 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 637 | // |
| 638 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 639 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 640 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame^] | 641 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 642 | if (RelocatedBase->getType() != Base->getType()) { |
| 643 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame^] | 644 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 645 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 646 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 647 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 648 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 649 | // If the newly generated derived pointer's type does not match the original derived |
| 650 | // pointer's type, cast the new derived pointer to match it. Same reasoning as above. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame^] | 651 | Value *ActualReplacement = Replacement; |
| 652 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 653 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame^] | 654 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 655 | } |
| 656 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 657 | ToReplace->eraseFromParent(); |
| 658 | |
| 659 | MadeChange = true; |
| 660 | } |
| 661 | return MadeChange; |
| 662 | } |
| 663 | |
| 664 | // Turns this: |
| 665 | // |
| 666 | // %base = ... |
| 667 | // %ptr = gep %base + 15 |
| 668 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 669 | // %base' = relocate(%tok, i32 4, i32 4) |
| 670 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 671 | // %val = load %ptr' |
| 672 | // |
| 673 | // into this: |
| 674 | // |
| 675 | // %base = ... |
| 676 | // %ptr = gep %base + 15 |
| 677 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 678 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 679 | // %ptr' = gep %base' + 15 |
| 680 | // %val = load %ptr' |
| 681 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 682 | bool MadeChange = false; |
| 683 | SmallVector<User *, 2> AllRelocateCalls; |
| 684 | |
| 685 | for (auto *U : I.users()) |
| 686 | if (isGCRelocate(dyn_cast<Instruction>(U))) |
| 687 | // Collect all the relocate calls associated with a statepoint |
| 688 | AllRelocateCalls.push_back(U); |
| 689 | |
| 690 | // We need atleast one base pointer relocation + one derived pointer |
| 691 | // relocation to mangle |
| 692 | if (AllRelocateCalls.size() < 2) |
| 693 | return false; |
| 694 | |
| 695 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 696 | // corresponding derived relocate instructions |
| 697 | DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap; |
| 698 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 699 | if (RelocateInstMap.empty()) |
| 700 | return false; |
| 701 | |
| 702 | for (auto &Item : RelocateInstMap) |
| 703 | // Item.first is the RelocatedBase to offset against |
| 704 | // Item.second is the vector of Targets to replace |
| 705 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 706 | return MadeChange; |
| 707 | } |
| 708 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 709 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 710 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 711 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 712 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 713 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 714 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 715 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 716 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 717 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 718 | UI != E; ) { |
| 719 | Use &TheUse = UI.getUse(); |
| 720 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 721 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 722 | // Figure out which BB this cast is used in. For PHI's this is the |
| 723 | // appropriate predecessor block. |
| 724 | BasicBlock *UserBB = User->getParent(); |
| 725 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 726 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 727 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 728 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 729 | // Preincrement use iterator so we don't invalidate it. |
| 730 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 731 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 732 | // If the block selected to receive the cast is an EH pad that does not |
| 733 | // allow non-PHI instructions before the terminator, we can't sink the |
| 734 | // cast. |
| 735 | if (UserBB->getTerminator()->isEHPad()) |
| 736 | continue; |
| 737 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 738 | // If this user is in the same block as the cast, don't change the cast. |
| 739 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 740 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 741 | // If we have already inserted a cast into this block, use it. |
| 742 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 743 | |
| 744 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 745 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 746 | assert(InsertPt != UserBB->end()); |
| 747 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 748 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 749 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 750 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 751 | // Replace a use of the cast with a use of the new cast. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 752 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 753 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 754 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 755 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 756 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 757 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 758 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 759 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 760 | MadeChange = true; |
| 761 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 762 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 763 | return MadeChange; |
| 764 | } |
| 765 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 766 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 767 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 768 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 769 | /// |
| 770 | /// Return true if any changes are made. |
| 771 | /// |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 772 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 773 | const DataLayout &DL) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 774 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 775 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 776 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 777 | |
| 778 | // This is an fp<->int conversion? |
| 779 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 780 | return false; |
| 781 | |
| 782 | // If this is an extension, it will be a zero or sign extension, which |
| 783 | // isn't a noop. |
| 784 | if (SrcVT.bitsLT(DstVT)) return false; |
| 785 | |
| 786 | // If these values will be promoted, find out what they will be promoted |
| 787 | // to. This helps us consider truncates on PPC as noop copies when they |
| 788 | // are. |
| 789 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 790 | TargetLowering::TypePromoteInteger) |
| 791 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 792 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 793 | TargetLowering::TypePromoteInteger) |
| 794 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 795 | |
| 796 | // If, after promotion, these are the same types, this is a noop copy. |
| 797 | if (SrcVT != DstVT) |
| 798 | return false; |
| 799 | |
| 800 | return SinkCast(CI); |
| 801 | } |
| 802 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 803 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 804 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 805 | /// |
| 806 | /// Return true if any changes were made. |
| 807 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 808 | Value *A, *B; |
| 809 | Instruction *AddI; |
| 810 | if (!match(CI, |
| 811 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 812 | return false; |
| 813 | |
| 814 | Type *Ty = AddI->getType(); |
| 815 | if (!isa<IntegerType>(Ty)) |
| 816 | return false; |
| 817 | |
| 818 | // We don't want to move around uses of condition values this late, so we we |
| 819 | // check if it is legal to create the call to the intrinsic in the basic |
| 820 | // block containing the icmp: |
| 821 | |
| 822 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 823 | return false; |
| 824 | |
| 825 | #ifndef NDEBUG |
| 826 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 827 | // for now: |
| 828 | if (AddI->hasOneUse()) |
| 829 | assert(*AddI->user_begin() == CI && "expected!"); |
| 830 | #endif |
| 831 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 832 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 833 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 834 | |
| 835 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 836 | |
| 837 | auto *UAddWithOverflow = |
| 838 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 839 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 840 | auto *Overflow = |
| 841 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 842 | |
| 843 | CI->replaceAllUsesWith(Overflow); |
| 844 | AddI->replaceAllUsesWith(UAdd); |
| 845 | CI->eraseFromParent(); |
| 846 | AddI->eraseFromParent(); |
| 847 | return true; |
| 848 | } |
| 849 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 850 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 851 | /// registers that must be created and coalesced. This is a clear win except on |
| 852 | /// targets with multiple condition code registers (PowerPC), where it might |
| 853 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 854 | /// |
| 855 | /// Return true if any changes are made. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 856 | static bool SinkCmpExpression(CmpInst *CI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 857 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 858 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 859 | /// Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 860 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 861 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 862 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 863 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 864 | UI != E; ) { |
| 865 | Use &TheUse = UI.getUse(); |
| 866 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 867 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 868 | // Preincrement use iterator so we don't invalidate it. |
| 869 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 870 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 871 | // Don't bother for PHI nodes. |
| 872 | if (isa<PHINode>(User)) |
| 873 | continue; |
| 874 | |
| 875 | // Figure out which BB this cmp is used in. |
| 876 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 877 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 878 | // If this user is in the same block as the cmp, don't change the cmp. |
| 879 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 880 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 881 | // If we have already inserted a cmp into this block, use it. |
| 882 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 883 | |
| 884 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 885 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 886 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 887 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 888 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 889 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 890 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 891 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 892 | // Replace a use of the cmp with a use of the new cmp. |
| 893 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 894 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 895 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 896 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 897 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 898 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 899 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 900 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 901 | MadeChange = true; |
| 902 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 903 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 904 | return MadeChange; |
| 905 | } |
| 906 | |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 907 | static bool OptimizeCmpExpression(CmpInst *CI) { |
| 908 | if (SinkCmpExpression(CI)) |
| 909 | return true; |
| 910 | |
| 911 | if (CombineUAddWithOverflow(CI)) |
| 912 | return true; |
| 913 | |
| 914 | return false; |
| 915 | } |
| 916 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 917 | /// Check if the candidates could be combined with a shift instruction, which |
| 918 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 919 | /// 1. Truncate instruction |
| 920 | /// 2. And instruction and the imm is a mask of the low bits: |
| 921 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 922 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 923 | if (!isa<TruncInst>(User)) { |
| 924 | if (User->getOpcode() != Instruction::And || |
| 925 | !isa<ConstantInt>(User->getOperand(1))) |
| 926 | return false; |
| 927 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 928 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 929 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 930 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 931 | return false; |
| 932 | } |
| 933 | return true; |
| 934 | } |
| 935 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 936 | /// Sink both shift and truncate instruction to the use of truncate's BB. |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 937 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 938 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 939 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 940 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 941 | BasicBlock *UserBB = User->getParent(); |
| 942 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 943 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 944 | bool MadeChange = false; |
| 945 | |
| 946 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 947 | TruncE = TruncI->user_end(); |
| 948 | TruncUI != TruncE;) { |
| 949 | |
| 950 | Use &TruncTheUse = TruncUI.getUse(); |
| 951 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 952 | // Preincrement use iterator so we don't invalidate it. |
| 953 | |
| 954 | ++TruncUI; |
| 955 | |
| 956 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 957 | if (!ISDOpcode) |
| 958 | continue; |
| 959 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 960 | // If the use is actually a legal node, there will not be an |
| 961 | // implicit truncate. |
| 962 | // FIXME: always querying the result type is just an |
| 963 | // approximation; some nodes' legality is determined by the |
| 964 | // operand or other means. There's no good way to find out though. |
Ahmed Bougacha | 0788d49 | 2014-11-12 22:16:55 +0000 | [diff] [blame] | 965 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 966 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 967 | continue; |
| 968 | |
| 969 | // Don't bother for PHI nodes. |
| 970 | if (isa<PHINode>(TruncUser)) |
| 971 | continue; |
| 972 | |
| 973 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 974 | |
| 975 | if (UserBB == TruncUserBB) |
| 976 | continue; |
| 977 | |
| 978 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 979 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 980 | |
| 981 | if (!InsertedShift && !InsertedTrunc) { |
| 982 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 983 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 984 | // Sink the shift |
| 985 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 986 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 987 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 988 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 989 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 990 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 991 | |
| 992 | // Sink the trunc |
| 993 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 994 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 995 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 996 | |
| 997 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 998 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 999 | |
| 1000 | MadeChange = true; |
| 1001 | |
| 1002 | TruncTheUse = InsertedTrunc; |
| 1003 | } |
| 1004 | } |
| 1005 | return MadeChange; |
| 1006 | } |
| 1007 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1008 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1009 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1010 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1011 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1012 | /// BB1: |
| 1013 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1014 | /// BB2: |
| 1015 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1016 | /// ==> |
| 1017 | /// |
| 1018 | /// BB2: |
| 1019 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1020 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1021 | /// |
| 1022 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1023 | /// instruction. |
| 1024 | /// Return true if any changes are made. |
| 1025 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1026 | const TargetLowering &TLI, |
| 1027 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1028 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1029 | |
| 1030 | /// Only insert instructions in each block once. |
| 1031 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1032 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1033 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1034 | |
| 1035 | bool MadeChange = false; |
| 1036 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1037 | UI != E;) { |
| 1038 | Use &TheUse = UI.getUse(); |
| 1039 | Instruction *User = cast<Instruction>(*UI); |
| 1040 | // Preincrement use iterator so we don't invalidate it. |
| 1041 | ++UI; |
| 1042 | |
| 1043 | // Don't bother for PHI nodes. |
| 1044 | if (isa<PHINode>(User)) |
| 1045 | continue; |
| 1046 | |
| 1047 | if (!isExtractBitsCandidateUse(User)) |
| 1048 | continue; |
| 1049 | |
| 1050 | BasicBlock *UserBB = User->getParent(); |
| 1051 | |
| 1052 | if (UserBB == DefBB) { |
| 1053 | // If the shift and truncate instruction are in the same BB. The use of |
| 1054 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1055 | // legal. In this case, we would like to sink both shift and truncate |
| 1056 | // instruction to the BB of TruncUse. |
| 1057 | // for example: |
| 1058 | // BB1: |
| 1059 | // i64 shift.result = lshr i64 opnd, imm |
| 1060 | // trunc.result = trunc shift.result to i16 |
| 1061 | // |
| 1062 | // BB2: |
| 1063 | // ----> We will have an implicit truncate here if the architecture does |
| 1064 | // not have i16 compare. |
| 1065 | // cmp i16 trunc.result, opnd2 |
| 1066 | // |
| 1067 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1068 | // If the type of the truncate is legal, no trucate will be |
| 1069 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1070 | && |
| 1071 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1072 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1073 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1074 | |
| 1075 | continue; |
| 1076 | } |
| 1077 | // If we have already inserted a shift into this block, use it. |
| 1078 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1079 | |
| 1080 | if (!InsertedShift) { |
| 1081 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1082 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1083 | |
| 1084 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1085 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1086 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1087 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1088 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1089 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1090 | |
| 1091 | MadeChange = true; |
| 1092 | } |
| 1093 | |
| 1094 | // Replace a use of the shift with a use of the new shift. |
| 1095 | TheUse = InsertedShift; |
| 1096 | } |
| 1097 | |
| 1098 | // If we removed all uses, nuke the shift. |
| 1099 | if (ShiftI->use_empty()) |
| 1100 | ShiftI->eraseFromParent(); |
| 1101 | |
| 1102 | return MadeChange; |
| 1103 | } |
| 1104 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1105 | // Translate a masked load intrinsic like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1106 | // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, |
| 1107 | // <16 x i1> %mask, <16 x i32> %passthru) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1108 | // to a chain of basic blocks, with loading element one-by-one if |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1109 | // the appropriate mask bit is set |
| 1110 | // |
| 1111 | // %1 = bitcast i8* %addr to i32* |
| 1112 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1113 | // %3 = icmp eq i1 %2, true |
| 1114 | // br i1 %3, label %cond.load, label %else |
| 1115 | // |
| 1116 | //cond.load: ; preds = %0 |
| 1117 | // %4 = getelementptr i32* %1, i32 0 |
| 1118 | // %5 = load i32* %4 |
| 1119 | // %6 = insertelement <16 x i32> undef, i32 %5, i32 0 |
| 1120 | // br label %else |
| 1121 | // |
| 1122 | //else: ; preds = %0, %cond.load |
| 1123 | // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] |
| 1124 | // %7 = extractelement <16 x i1> %mask, i32 1 |
| 1125 | // %8 = icmp eq i1 %7, true |
| 1126 | // br i1 %8, label %cond.load1, label %else2 |
| 1127 | // |
| 1128 | //cond.load1: ; preds = %else |
| 1129 | // %9 = getelementptr i32* %1, i32 1 |
| 1130 | // %10 = load i32* %9 |
| 1131 | // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 |
| 1132 | // br label %else2 |
| 1133 | // |
| 1134 | //else2: ; preds = %else, %cond.load1 |
| 1135 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1136 | // %12 = extractelement <16 x i1> %mask, i32 2 |
| 1137 | // %13 = icmp eq i1 %12, true |
| 1138 | // br i1 %13, label %cond.load4, label %else5 |
| 1139 | // |
| 1140 | static void ScalarizeMaskedLoad(CallInst *CI) { |
| 1141 | Value *Ptr = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1142 | Value *Alignment = CI->getArgOperand(1); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1143 | Value *Mask = CI->getArgOperand(2); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1144 | Value *Src0 = CI->getArgOperand(3); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1145 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1146 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1147 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1148 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1149 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1150 | Type *EltTy = CI->getType()->getVectorElementType(); |
| 1151 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1152 | IRBuilder<> Builder(CI->getContext()); |
| 1153 | Instruction *InsertPt = CI; |
| 1154 | BasicBlock *IfBlock = CI->getParent(); |
| 1155 | BasicBlock *CondBlock = nullptr; |
| 1156 | BasicBlock *PrevIfBlock = CI->getParent(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1157 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1158 | Builder.SetInsertPoint(InsertPt); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1159 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1160 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1161 | // Short-cut if the mask is all-true. |
| 1162 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1163 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1164 | |
| 1165 | if (IsAllOnesMask) { |
| 1166 | Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); |
| 1167 | CI->replaceAllUsesWith(NewI); |
| 1168 | CI->eraseFromParent(); |
| 1169 | return; |
| 1170 | } |
| 1171 | |
| 1172 | // Adjust alignment for the scalar instruction. |
| 1173 | AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1174 | // Bitcast %addr fron i8* to EltTy* |
| 1175 | Type *NewPtrType = |
| 1176 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1177 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1178 | unsigned VectorWidth = VecType->getNumElements(); |
| 1179 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1180 | Value *UndefVal = UndefValue::get(VecType); |
| 1181 | |
| 1182 | // The result vector |
| 1183 | Value *VResult = UndefVal; |
| 1184 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1185 | if (isa<ConstantVector>(Mask)) { |
| 1186 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1187 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1188 | continue; |
| 1189 | Value *Gep = |
| 1190 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1191 | LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
| 1192 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1193 | Builder.getInt32(Idx)); |
| 1194 | } |
| 1195 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1196 | CI->replaceAllUsesWith(NewI); |
| 1197 | CI->eraseFromParent(); |
| 1198 | return; |
| 1199 | } |
| 1200 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1201 | PHINode *Phi = nullptr; |
| 1202 | Value *PrevPhi = UndefVal; |
| 1203 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1204 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1205 | |
| 1206 | // Fill the "else" block, created in the previous iteration |
| 1207 | // |
| 1208 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1209 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1210 | // %to_load = icmp eq i1 %mask_1, true |
| 1211 | // br i1 %to_load, label %cond.load, label %else |
| 1212 | // |
| 1213 | if (Idx > 0) { |
| 1214 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1215 | Phi->addIncoming(VResult, CondBlock); |
| 1216 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1217 | PrevPhi = Phi; |
| 1218 | VResult = Phi; |
| 1219 | } |
| 1220 | |
| 1221 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1222 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1223 | ConstantInt::get(Predicate->getType(), 1)); |
| 1224 | |
| 1225 | // Create "cond" block |
| 1226 | // |
| 1227 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1228 | // %Elt = load i32* %EltAddr |
| 1229 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1230 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1231 | CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1232 | Builder.SetInsertPoint(InsertPt); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1233 | |
| 1234 | Value *Gep = |
| 1235 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1236 | LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1237 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); |
| 1238 | |
| 1239 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1240 | BasicBlock *NewIfBlock = |
| 1241 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1242 | Builder.SetInsertPoint(InsertPt); |
| 1243 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1244 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1245 | OldBr->eraseFromParent(); |
| 1246 | PrevIfBlock = IfBlock; |
| 1247 | IfBlock = NewIfBlock; |
| 1248 | } |
| 1249 | |
| 1250 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1251 | Phi->addIncoming(VResult, CondBlock); |
| 1252 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1253 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1254 | CI->replaceAllUsesWith(NewI); |
| 1255 | CI->eraseFromParent(); |
| 1256 | } |
| 1257 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1258 | // Translate a masked store intrinsic, like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1259 | // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, |
| 1260 | // <16 x i1> %mask) |
| 1261 | // to a chain of basic blocks, that stores element one-by-one if |
| 1262 | // the appropriate mask bit is set |
| 1263 | // |
| 1264 | // %1 = bitcast i8* %addr to i32* |
| 1265 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1266 | // %3 = icmp eq i1 %2, true |
| 1267 | // br i1 %3, label %cond.store, label %else |
| 1268 | // |
| 1269 | // cond.store: ; preds = %0 |
| 1270 | // %4 = extractelement <16 x i32> %val, i32 0 |
| 1271 | // %5 = getelementptr i32* %1, i32 0 |
| 1272 | // store i32 %4, i32* %5 |
| 1273 | // br label %else |
| 1274 | // |
| 1275 | // else: ; preds = %0, %cond.store |
| 1276 | // %6 = extractelement <16 x i1> %mask, i32 1 |
| 1277 | // %7 = icmp eq i1 %6, true |
| 1278 | // br i1 %7, label %cond.store1, label %else2 |
| 1279 | // |
| 1280 | // cond.store1: ; preds = %else |
| 1281 | // %8 = extractelement <16 x i32> %val, i32 1 |
| 1282 | // %9 = getelementptr i32* %1, i32 1 |
| 1283 | // store i32 %8, i32* %9 |
| 1284 | // br label %else2 |
| 1285 | // . . . |
| 1286 | static void ScalarizeMaskedStore(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1287 | Value *Src = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1288 | Value *Ptr = CI->getArgOperand(1); |
| 1289 | Value *Alignment = CI->getArgOperand(2); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1290 | Value *Mask = CI->getArgOperand(3); |
| 1291 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1292 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1293 | VectorType *VecType = dyn_cast<VectorType>(Src->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1294 | assert(VecType && "Unexpected data type in masked store intrinsic"); |
| 1295 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1296 | Type *EltTy = VecType->getElementType(); |
| 1297 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1298 | IRBuilder<> Builder(CI->getContext()); |
| 1299 | Instruction *InsertPt = CI; |
| 1300 | BasicBlock *IfBlock = CI->getParent(); |
| 1301 | Builder.SetInsertPoint(InsertPt); |
| 1302 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1303 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1304 | // Short-cut if the mask is all-true. |
| 1305 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1306 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1307 | |
| 1308 | if (IsAllOnesMask) { |
| 1309 | Builder.CreateAlignedStore(Src, Ptr, AlignVal); |
| 1310 | CI->eraseFromParent(); |
| 1311 | return; |
| 1312 | } |
| 1313 | |
| 1314 | // Adjust alignment for the scalar instruction. |
| 1315 | AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1316 | // Bitcast %addr fron i8* to EltTy* |
| 1317 | Type *NewPtrType = |
| 1318 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1319 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1320 | unsigned VectorWidth = VecType->getNumElements(); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1321 | |
| 1322 | if (isa<ConstantVector>(Mask)) { |
| 1323 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1324 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1325 | continue; |
| 1326 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
| 1327 | Value *Gep = |
| 1328 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1329 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
| 1330 | } |
| 1331 | CI->eraseFromParent(); |
| 1332 | return; |
| 1333 | } |
| 1334 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1335 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1336 | |
| 1337 | // Fill the "else" block, created in the previous iteration |
| 1338 | // |
| 1339 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1340 | // %to_store = icmp eq i1 %mask_1, true |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1341 | // br i1 %to_store, label %cond.store, label %else |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1342 | // |
| 1343 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1344 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1345 | ConstantInt::get(Predicate->getType(), 1)); |
| 1346 | |
| 1347 | // Create "cond" block |
| 1348 | // |
| 1349 | // %OneElt = extractelement <16 x i32> %Src, i32 Idx |
| 1350 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1351 | // %store i32 %OneElt, i32* %EltAddr |
| 1352 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1353 | BasicBlock *CondBlock = |
| 1354 | IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1355 | Builder.SetInsertPoint(InsertPt); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1356 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1357 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1358 | Value *Gep = |
| 1359 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1360 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1361 | |
| 1362 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1363 | BasicBlock *NewIfBlock = |
| 1364 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1365 | Builder.SetInsertPoint(InsertPt); |
| 1366 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1367 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1368 | OldBr->eraseFromParent(); |
| 1369 | IfBlock = NewIfBlock; |
| 1370 | } |
| 1371 | CI->eraseFromParent(); |
| 1372 | } |
| 1373 | |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1374 | // Translate a masked gather intrinsic like |
| 1375 | // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, |
| 1376 | // <16 x i1> %Mask, <16 x i32> %Src) |
| 1377 | // to a chain of basic blocks, with loading element one-by-one if |
| 1378 | // the appropriate mask bit is set |
| 1379 | // |
| 1380 | // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind |
| 1381 | // % Mask0 = extractelement <16 x i1> %Mask, i32 0 |
| 1382 | // % ToLoad0 = icmp eq i1 % Mask0, true |
| 1383 | // br i1 % ToLoad0, label %cond.load, label %else |
| 1384 | // |
| 1385 | // cond.load: |
| 1386 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1387 | // % Load0 = load i32, i32* % Ptr0, align 4 |
| 1388 | // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 |
| 1389 | // br label %else |
| 1390 | // |
| 1391 | // else: |
| 1392 | // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] |
| 1393 | // % Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1394 | // % ToLoad1 = icmp eq i1 % Mask1, true |
| 1395 | // br i1 % ToLoad1, label %cond.load1, label %else2 |
| 1396 | // |
| 1397 | // cond.load1: |
| 1398 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1399 | // % Load1 = load i32, i32* % Ptr1, align 4 |
| 1400 | // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 |
| 1401 | // br label %else2 |
| 1402 | // . . . |
| 1403 | // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src |
| 1404 | // ret <16 x i32> %Result |
| 1405 | static void ScalarizeMaskedGather(CallInst *CI) { |
| 1406 | Value *Ptrs = CI->getArgOperand(0); |
| 1407 | Value *Alignment = CI->getArgOperand(1); |
| 1408 | Value *Mask = CI->getArgOperand(2); |
| 1409 | Value *Src0 = CI->getArgOperand(3); |
| 1410 | |
| 1411 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
| 1412 | |
| 1413 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1414 | |
| 1415 | IRBuilder<> Builder(CI->getContext()); |
| 1416 | Instruction *InsertPt = CI; |
| 1417 | BasicBlock *IfBlock = CI->getParent(); |
| 1418 | BasicBlock *CondBlock = nullptr; |
| 1419 | BasicBlock *PrevIfBlock = CI->getParent(); |
| 1420 | Builder.SetInsertPoint(InsertPt); |
| 1421 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1422 | |
| 1423 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1424 | |
| 1425 | Value *UndefVal = UndefValue::get(VecType); |
| 1426 | |
| 1427 | // The result vector |
| 1428 | Value *VResult = UndefVal; |
| 1429 | unsigned VectorWidth = VecType->getNumElements(); |
| 1430 | |
| 1431 | // Shorten the way if the mask is a vector of constants. |
| 1432 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1433 | |
| 1434 | if (IsConstMask) { |
| 1435 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1436 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1437 | continue; |
| 1438 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1439 | "Ptr" + Twine(Idx)); |
| 1440 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1441 | "Load" + Twine(Idx)); |
| 1442 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1443 | Builder.getInt32(Idx), |
| 1444 | "Res" + Twine(Idx)); |
| 1445 | } |
| 1446 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1447 | CI->replaceAllUsesWith(NewI); |
| 1448 | CI->eraseFromParent(); |
| 1449 | return; |
| 1450 | } |
| 1451 | |
| 1452 | PHINode *Phi = nullptr; |
| 1453 | Value *PrevPhi = UndefVal; |
| 1454 | |
| 1455 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1456 | |
| 1457 | // Fill the "else" block, created in the previous iteration |
| 1458 | // |
| 1459 | // %Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1460 | // %ToLoad1 = icmp eq i1 %Mask1, true |
| 1461 | // br i1 %ToLoad1, label %cond.load, label %else |
| 1462 | // |
| 1463 | if (Idx > 0) { |
| 1464 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1465 | Phi->addIncoming(VResult, CondBlock); |
| 1466 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1467 | PrevPhi = Phi; |
| 1468 | VResult = Phi; |
| 1469 | } |
| 1470 | |
| 1471 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1472 | Builder.getInt32(Idx), |
| 1473 | "Mask" + Twine(Idx)); |
| 1474 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1475 | ConstantInt::get(Predicate->getType(), 1), |
| 1476 | "ToLoad" + Twine(Idx)); |
| 1477 | |
| 1478 | // Create "cond" block |
| 1479 | // |
| 1480 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1481 | // %Elt = load i32* %EltAddr |
| 1482 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1483 | // |
| 1484 | CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); |
| 1485 | Builder.SetInsertPoint(InsertPt); |
| 1486 | |
| 1487 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1488 | "Ptr" + Twine(Idx)); |
| 1489 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1490 | "Load" + Twine(Idx)); |
| 1491 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), |
| 1492 | "Res" + Twine(Idx)); |
| 1493 | |
| 1494 | // Create "else" block, fill it in the next iteration |
| 1495 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1496 | Builder.SetInsertPoint(InsertPt); |
| 1497 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1498 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1499 | OldBr->eraseFromParent(); |
| 1500 | PrevIfBlock = IfBlock; |
| 1501 | IfBlock = NewIfBlock; |
| 1502 | } |
| 1503 | |
| 1504 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1505 | Phi->addIncoming(VResult, CondBlock); |
| 1506 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1507 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1508 | CI->replaceAllUsesWith(NewI); |
| 1509 | CI->eraseFromParent(); |
| 1510 | } |
| 1511 | |
| 1512 | // Translate a masked scatter intrinsic, like |
| 1513 | // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, |
| 1514 | // <16 x i1> %Mask) |
| 1515 | // to a chain of basic blocks, that stores element one-by-one if |
| 1516 | // the appropriate mask bit is set. |
| 1517 | // |
| 1518 | // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind |
| 1519 | // % Mask0 = extractelement <16 x i1> % Mask, i32 0 |
| 1520 | // % ToStore0 = icmp eq i1 % Mask0, true |
| 1521 | // br i1 %ToStore0, label %cond.store, label %else |
| 1522 | // |
| 1523 | // cond.store: |
| 1524 | // % Elt0 = extractelement <16 x i32> %Src, i32 0 |
| 1525 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1526 | // store i32 %Elt0, i32* % Ptr0, align 4 |
| 1527 | // br label %else |
| 1528 | // |
| 1529 | // else: |
| 1530 | // % Mask1 = extractelement <16 x i1> % Mask, i32 1 |
| 1531 | // % ToStore1 = icmp eq i1 % Mask1, true |
| 1532 | // br i1 % ToStore1, label %cond.store1, label %else2 |
| 1533 | // |
| 1534 | // cond.store1: |
| 1535 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1536 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1537 | // store i32 % Elt1, i32* % Ptr1, align 4 |
| 1538 | // br label %else2 |
| 1539 | // . . . |
| 1540 | static void ScalarizeMaskedScatter(CallInst *CI) { |
| 1541 | Value *Src = CI->getArgOperand(0); |
| 1542 | Value *Ptrs = CI->getArgOperand(1); |
| 1543 | Value *Alignment = CI->getArgOperand(2); |
| 1544 | Value *Mask = CI->getArgOperand(3); |
| 1545 | |
| 1546 | assert(isa<VectorType>(Src->getType()) && |
| 1547 | "Unexpected data type in masked scatter intrinsic"); |
| 1548 | assert(isa<VectorType>(Ptrs->getType()) && |
| 1549 | isa<PointerType>(Ptrs->getType()->getVectorElementType()) && |
| 1550 | "Vector of pointers is expected in masked scatter intrinsic"); |
| 1551 | |
| 1552 | IRBuilder<> Builder(CI->getContext()); |
| 1553 | Instruction *InsertPt = CI; |
| 1554 | BasicBlock *IfBlock = CI->getParent(); |
| 1555 | Builder.SetInsertPoint(InsertPt); |
| 1556 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1557 | |
| 1558 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1559 | unsigned VectorWidth = Src->getType()->getVectorNumElements(); |
| 1560 | |
| 1561 | // Shorten the way if the mask is a vector of constants. |
| 1562 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1563 | |
| 1564 | if (IsConstMask) { |
| 1565 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1566 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1567 | continue; |
| 1568 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1569 | "Elt" + Twine(Idx)); |
| 1570 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1571 | "Ptr" + Twine(Idx)); |
| 1572 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1573 | } |
| 1574 | CI->eraseFromParent(); |
| 1575 | return; |
| 1576 | } |
| 1577 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1578 | // Fill the "else" block, created in the previous iteration |
| 1579 | // |
| 1580 | // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx |
| 1581 | // % ToStore = icmp eq i1 % Mask1, true |
| 1582 | // br i1 % ToStore, label %cond.store, label %else |
| 1583 | // |
| 1584 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1585 | Builder.getInt32(Idx), |
| 1586 | "Mask" + Twine(Idx)); |
| 1587 | Value *Cmp = |
| 1588 | Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1589 | ConstantInt::get(Predicate->getType(), 1), |
| 1590 | "ToStore" + Twine(Idx)); |
| 1591 | |
| 1592 | // Create "cond" block |
| 1593 | // |
| 1594 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1595 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1596 | // %store i32 % Elt1, i32* % Ptr1 |
| 1597 | // |
| 1598 | BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); |
| 1599 | Builder.SetInsertPoint(InsertPt); |
| 1600 | |
| 1601 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1602 | "Elt" + Twine(Idx)); |
| 1603 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1604 | "Ptr" + Twine(Idx)); |
| 1605 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1606 | |
| 1607 | // Create "else" block, fill it in the next iteration |
| 1608 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1609 | Builder.SetInsertPoint(InsertPt); |
| 1610 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1611 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1612 | OldBr->eraseFromParent(); |
| 1613 | IfBlock = NewIfBlock; |
| 1614 | } |
| 1615 | CI->eraseFromParent(); |
| 1616 | } |
| 1617 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1618 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 1619 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 1620 | /// |
| 1621 | /// We want to transform: |
| 1622 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 1623 | /// |
| 1624 | /// into: |
| 1625 | /// entry: |
| 1626 | /// %cmpz = icmp eq i64 %A, 0 |
| 1627 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 1628 | /// cond.false: |
| 1629 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 1630 | /// br label %cond.end |
| 1631 | /// cond.end: |
| 1632 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 1633 | /// |
| 1634 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 1635 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 1636 | const TargetLowering *TLI, |
| 1637 | const DataLayout *DL, |
| 1638 | bool &ModifiedDT) { |
| 1639 | if (!TLI || !DL) |
| 1640 | return false; |
| 1641 | |
| 1642 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 1643 | if (match(CountZeros->getOperand(1), m_One())) |
| 1644 | return false; |
| 1645 | |
| 1646 | // If it's cheap to speculate, there's nothing to do. |
| 1647 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 1648 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 1649 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 1650 | return false; |
| 1651 | |
| 1652 | // Only handle legal scalar cases. Anything else requires too much work. |
| 1653 | Type *Ty = CountZeros->getType(); |
| 1654 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
| 1655 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize()) |
| 1656 | return false; |
| 1657 | |
| 1658 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 1659 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 1660 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 1661 | |
| 1662 | // Create another block after the count zero intrinsic. A PHI will be added |
| 1663 | // in this block to select the result of the intrinsic or the bit-width |
| 1664 | // constant if the input to the intrinsic is zero. |
| 1665 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 1666 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 1667 | |
| 1668 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 1669 | IRBuilder<> Builder(CountZeros->getContext()); |
| 1670 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 1671 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 1672 | |
| 1673 | // Replace the unconditional branch that was created by the first split with |
| 1674 | // a compare against zero and a conditional branch. |
| 1675 | Value *Zero = Constant::getNullValue(Ty); |
| 1676 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 1677 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 1678 | StartBlock->getTerminator()->eraseFromParent(); |
| 1679 | |
| 1680 | // Create a PHI in the end block to select either the output of the intrinsic |
| 1681 | // or the bit width of the operand. |
| 1682 | Builder.SetInsertPoint(&EndBlock->front()); |
| 1683 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 1684 | CountZeros->replaceAllUsesWith(PN); |
| 1685 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 1686 | PN->addIncoming(BitWidth, StartBlock); |
| 1687 | PN->addIncoming(CountZeros, CallBlock); |
| 1688 | |
| 1689 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 1690 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 1691 | // intrinsic; we only despeculate when a zero input is defined. |
| 1692 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 1693 | ModifiedDT = true; |
| 1694 | return true; |
| 1695 | } |
| 1696 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1697 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1698 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1699 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1700 | // Lower inline assembly if we can. |
| 1701 | // If we found an inline asm expession, and if the target knows how to |
| 1702 | // lower it to normal LLVM code, do so now. |
| 1703 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 1704 | if (TLI->ExpandInlineAsm(CI)) { |
| 1705 | // Avoid invalidating the iterator. |
| 1706 | CurInstIterator = BB->begin(); |
| 1707 | // Avoid processing instructions out of order, which could cause |
| 1708 | // reuse before a value is defined. |
| 1709 | SunkAddrs.clear(); |
| 1710 | return true; |
| 1711 | } |
| 1712 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1713 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1714 | return true; |
| 1715 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1716 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1717 | // Align the pointer arguments to this call if the target thinks it's a good |
| 1718 | // idea |
| 1719 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1720 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1721 | for (auto &Arg : CI->arg_operands()) { |
| 1722 | // We want to align both objects whose address is used directly and |
| 1723 | // objects whose address is used in casts and GEPs, though it only makes |
| 1724 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 1725 | // if size - offset meets the size threshold. |
| 1726 | if (!Arg->getType()->isPointerTy()) |
| 1727 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1728 | APInt Offset(DL->getPointerSizeInBits( |
| 1729 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 1730 | 0); |
| 1731 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1732 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1733 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 1734 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1735 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1736 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 1737 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1738 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1739 | // Global variables can only be aligned if they are defined in this |
| 1740 | // object (i.e. they are uniquely initialized in this object), and |
| 1741 | // over-aligning global variables that have an explicit section is |
| 1742 | // forbidden. |
| 1743 | GlobalVariable *GV; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1744 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() && |
| 1745 | !GV->hasSection() && GV->getAlignment() < PrefAlign && |
| 1746 | DL->getTypeAllocSize(GV->getType()->getElementType()) >= |
| 1747 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1748 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1749 | } |
| 1750 | // If this is a memcpy (or similar) then we may be able to improve the |
| 1751 | // alignment |
| 1752 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1753 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1754 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1755 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1756 | if (Align > MI->getAlignment()) |
| 1757 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1758 | } |
| 1759 | } |
| 1760 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1761 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1762 | if (II) { |
| 1763 | switch (II->getIntrinsicID()) { |
| 1764 | default: break; |
| 1765 | case Intrinsic::objectsize: { |
| 1766 | // Lower all uses of llvm.objectsize.* |
| 1767 | bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1); |
| 1768 | Type *ReturnTy = CI->getType(); |
| 1769 | Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1770 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1771 | // Substituting this can cause recursive simplifications, which can |
| 1772 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 1773 | // happens. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1774 | WeakVH IterHandle(&*CurInstIterator); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1775 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1776 | replaceAndRecursivelySimplify(CI, RetVal, |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 1777 | TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1778 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1779 | // If the iterator instruction was recursively deleted, start over at the |
| 1780 | // start of the block. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1781 | if (IterHandle != CurInstIterator.getNodePtrUnchecked()) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1782 | CurInstIterator = BB->begin(); |
| 1783 | SunkAddrs.clear(); |
| 1784 | } |
| 1785 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 1786 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1787 | case Intrinsic::masked_load: { |
| 1788 | // Scalarize unsupported vector masked load |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1789 | if (!TTI->isLegalMaskedLoad(CI->getType())) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1790 | ScalarizeMaskedLoad(CI); |
| 1791 | ModifiedDT = true; |
| 1792 | return true; |
| 1793 | } |
| 1794 | return false; |
| 1795 | } |
| 1796 | case Intrinsic::masked_store: { |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1797 | if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1798 | ScalarizeMaskedStore(CI); |
| 1799 | ModifiedDT = true; |
| 1800 | return true; |
| 1801 | } |
| 1802 | return false; |
| 1803 | } |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1804 | case Intrinsic::masked_gather: { |
| 1805 | if (!TTI->isLegalMaskedGather(CI->getType())) { |
| 1806 | ScalarizeMaskedGather(CI); |
| 1807 | ModifiedDT = true; |
| 1808 | return true; |
| 1809 | } |
| 1810 | return false; |
| 1811 | } |
| 1812 | case Intrinsic::masked_scatter: { |
| 1813 | if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { |
| 1814 | ScalarizeMaskedScatter(CI); |
| 1815 | ModifiedDT = true; |
| 1816 | return true; |
| 1817 | } |
| 1818 | return false; |
| 1819 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1820 | case Intrinsic::aarch64_stlxr: |
| 1821 | case Intrinsic::aarch64_stxr: { |
| 1822 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 1823 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 1824 | ExtVal->getParent() == CI->getParent()) |
| 1825 | return false; |
| 1826 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 1827 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 1828 | // Mark this instruction as "inserted by CGP", so that other |
| 1829 | // optimizations don't touch it. |
| 1830 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1831 | return true; |
| 1832 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 1833 | case Intrinsic::invariant_group_barrier: |
| 1834 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 1835 | II->eraseFromParent(); |
| 1836 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1837 | |
| 1838 | case Intrinsic::cttz: |
| 1839 | case Intrinsic::ctlz: |
| 1840 | // If counting zeros is expensive, try to avoid it. |
| 1841 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1842 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1843 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1844 | if (TLI) { |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1845 | // Unknown address space. |
| 1846 | // TODO: Target hook to pick which address space the intrinsic cares |
| 1847 | // about? |
| 1848 | unsigned AddrSpace = ~0u; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1849 | SmallVector<Value*, 2> PtrOps; |
| 1850 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1851 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1852 | while (!PtrOps.empty()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1853 | if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1854 | return true; |
| 1855 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 1856 | } |
| 1857 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1858 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1859 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 1860 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 1861 | // Lower all default uses of _chk calls. This is very similar |
| 1862 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1863 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 1864 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1865 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1866 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 1867 | CI->replaceAllUsesWith(V); |
| 1868 | CI->eraseFromParent(); |
| 1869 | return true; |
| 1870 | } |
| 1871 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1872 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1873 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1874 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 1875 | /// to enable tail call optimizations. The case it is currently looking for is: |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1876 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1877 | /// bb0: |
| 1878 | /// %tmp0 = tail call i32 @f0() |
| 1879 | /// br label %return |
| 1880 | /// bb1: |
| 1881 | /// %tmp1 = tail call i32 @f1() |
| 1882 | /// br label %return |
| 1883 | /// bb2: |
| 1884 | /// %tmp2 = tail call i32 @f2() |
| 1885 | /// br label %return |
| 1886 | /// return: |
| 1887 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 1888 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1889 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1890 | /// |
| 1891 | /// => |
| 1892 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1893 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1894 | /// bb0: |
| 1895 | /// %tmp0 = tail call i32 @f0() |
| 1896 | /// ret i32 %tmp0 |
| 1897 | /// bb1: |
| 1898 | /// %tmp1 = tail call i32 @f1() |
| 1899 | /// ret i32 %tmp1 |
| 1900 | /// bb2: |
| 1901 | /// %tmp2 = tail call i32 @f2() |
| 1902 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1903 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1904 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 1905 | if (!TLI) |
| 1906 | return false; |
| 1907 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 1908 | ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 1909 | if (!RI) |
| 1910 | return false; |
| 1911 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1912 | PHINode *PN = nullptr; |
| 1913 | BitCastInst *BCI = nullptr; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1914 | Value *V = RI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1915 | if (V) { |
| 1916 | BCI = dyn_cast<BitCastInst>(V); |
| 1917 | if (BCI) |
| 1918 | V = BCI->getOperand(0); |
| 1919 | |
| 1920 | PN = dyn_cast<PHINode>(V); |
| 1921 | if (!PN) |
| 1922 | return false; |
| 1923 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1924 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1925 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1926 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1927 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1928 | // It's not safe to eliminate the sign / zero extension of the return value. |
| 1929 | // See llvm::isInTailCallPosition(). |
| 1930 | const Function *F = BB->getParent(); |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1931 | AttributeSet CallerAttrs = F->getAttributes(); |
| 1932 | if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || |
| 1933 | CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1934 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1935 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1936 | // Make sure there are no instructions between the PHI and return, or that the |
| 1937 | // return is the first instruction in the block. |
| 1938 | if (PN) { |
| 1939 | BasicBlock::iterator BI = BB->begin(); |
| 1940 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1941 | if (&*BI == BCI) |
| 1942 | // Also skip over the bitcast. |
| 1943 | ++BI; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1944 | if (&*BI != RI) |
| 1945 | return false; |
| 1946 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1947 | BasicBlock::iterator BI = BB->begin(); |
| 1948 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
| 1949 | if (&*BI != RI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1950 | return false; |
| 1951 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1952 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1953 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 1954 | /// call. |
| 1955 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1956 | if (PN) { |
| 1957 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 1958 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 1959 | // Make sure the phi value is indeed produced by the tail call. |
| 1960 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
| 1961 | TLI->mayBeEmittedAsTailCall(CI)) |
| 1962 | TailCalls.push_back(CI); |
| 1963 | } |
| 1964 | } else { |
| 1965 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1966 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 1967 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1968 | continue; |
| 1969 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1970 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1971 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 1972 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1973 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 1974 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1975 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1976 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1977 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Cameron Zwarich | 2edfe77 | 2011-03-24 15:54:11 +0000 | [diff] [blame] | 1978 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1979 | TailCalls.push_back(CI); |
| 1980 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1981 | } |
| 1982 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1983 | bool Changed = false; |
| 1984 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1985 | CallInst *CI = TailCalls[i]; |
| 1986 | CallSite CS(CI); |
| 1987 | |
| 1988 | // Conservatively require the attributes of the call to match those of the |
| 1989 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1990 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 1991 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1992 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1993 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1994 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1995 | continue; |
| 1996 | |
| 1997 | // Make sure the call instruction is followed by an unconditional branch to |
| 1998 | // the return block. |
| 1999 | BasicBlock *CallBB = CI->getParent(); |
| 2000 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 2001 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 2002 | continue; |
| 2003 | |
| 2004 | // Duplicate the return into CallBB. |
| 2005 | (void)FoldReturnIntoUncondBranch(RI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 2006 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2007 | ++NumRetsDup; |
| 2008 | } |
| 2009 | |
| 2010 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 2011 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2012 | BB->eraseFromParent(); |
| 2013 | |
| 2014 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2015 | } |
| 2016 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2017 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2018 | // Memory Optimization |
| 2019 | //===----------------------------------------------------------------------===// |
| 2020 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2021 | namespace { |
| 2022 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2023 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2024 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 2025 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2026 | Value *BaseReg; |
| 2027 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2028 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2029 | void print(raw_ostream &OS) const; |
| 2030 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2031 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2032 | bool operator==(const ExtAddrMode& O) const { |
| 2033 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 2034 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 2035 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 2036 | } |
| 2037 | }; |
| 2038 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2039 | #ifndef NDEBUG |
| 2040 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2041 | AM.print(OS); |
| 2042 | return OS; |
| 2043 | } |
| 2044 | #endif |
| 2045 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2046 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2047 | bool NeedPlus = false; |
| 2048 | OS << "["; |
| 2049 | if (BaseGV) { |
| 2050 | OS << (NeedPlus ? " + " : "") |
| 2051 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2052 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2053 | NeedPlus = true; |
| 2054 | } |
| 2055 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2056 | if (BaseOffs) { |
| 2057 | OS << (NeedPlus ? " + " : "") |
| 2058 | << BaseOffs; |
| 2059 | NeedPlus = true; |
| 2060 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2061 | |
| 2062 | if (BaseReg) { |
| 2063 | OS << (NeedPlus ? " + " : "") |
| 2064 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2065 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2066 | NeedPlus = true; |
| 2067 | } |
| 2068 | if (Scale) { |
| 2069 | OS << (NeedPlus ? " + " : "") |
| 2070 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2071 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2072 | } |
| 2073 | |
| 2074 | OS << ']'; |
| 2075 | } |
| 2076 | |
| 2077 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 2078 | void ExtAddrMode::dump() const { |
| 2079 | print(dbgs()); |
| 2080 | dbgs() << '\n'; |
| 2081 | } |
| 2082 | #endif |
| 2083 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2084 | /// \brief This class provides transaction based operation on the IR. |
| 2085 | /// Every change made through this class is recorded in the internal state and |
| 2086 | /// can be undone (rollback) until commit is called. |
| 2087 | class TypePromotionTransaction { |
| 2088 | |
| 2089 | /// \brief This represents the common interface of the individual transaction. |
| 2090 | /// Each class implements the logic for doing one specific modification on |
| 2091 | /// the IR via the TypePromotionTransaction. |
| 2092 | class TypePromotionAction { |
| 2093 | protected: |
| 2094 | /// The Instruction modified. |
| 2095 | Instruction *Inst; |
| 2096 | |
| 2097 | public: |
| 2098 | /// \brief Constructor of the action. |
| 2099 | /// The constructor performs the related action on the IR. |
| 2100 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2101 | |
| 2102 | virtual ~TypePromotionAction() {} |
| 2103 | |
| 2104 | /// \brief Undo the modification done by this action. |
| 2105 | /// When this method is called, the IR must be in the same state as it was |
| 2106 | /// before this action was applied. |
| 2107 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2108 | /// state as it was directly after this action was applied. |
| 2109 | virtual void undo() = 0; |
| 2110 | |
| 2111 | /// \brief Advocate every change made by this action. |
| 2112 | /// When the results on the IR of the action are to be kept, it is important |
| 2113 | /// to call this function, otherwise hidden information may be kept forever. |
| 2114 | virtual void commit() { |
| 2115 | // Nothing to be done, this action is not doing anything. |
| 2116 | } |
| 2117 | }; |
| 2118 | |
| 2119 | /// \brief Utility to remember the position of an instruction. |
| 2120 | class InsertionHandler { |
| 2121 | /// Position of an instruction. |
| 2122 | /// Either an instruction: |
| 2123 | /// - Is the first in a basic block: BB is used. |
| 2124 | /// - Has a previous instructon: PrevInst is used. |
| 2125 | union { |
| 2126 | Instruction *PrevInst; |
| 2127 | BasicBlock *BB; |
| 2128 | } Point; |
| 2129 | /// Remember whether or not the instruction had a previous instruction. |
| 2130 | bool HasPrevInstruction; |
| 2131 | |
| 2132 | public: |
| 2133 | /// \brief Record the position of \p Inst. |
| 2134 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2135 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2136 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2137 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2138 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2139 | else |
| 2140 | Point.BB = Inst->getParent(); |
| 2141 | } |
| 2142 | |
| 2143 | /// \brief Insert \p Inst at the recorded position. |
| 2144 | void insert(Instruction *Inst) { |
| 2145 | if (HasPrevInstruction) { |
| 2146 | if (Inst->getParent()) |
| 2147 | Inst->removeFromParent(); |
| 2148 | Inst->insertAfter(Point.PrevInst); |
| 2149 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2150 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2151 | if (Inst->getParent()) |
| 2152 | Inst->moveBefore(Position); |
| 2153 | else |
| 2154 | Inst->insertBefore(Position); |
| 2155 | } |
| 2156 | } |
| 2157 | }; |
| 2158 | |
| 2159 | /// \brief Move an instruction before another. |
| 2160 | class InstructionMoveBefore : public TypePromotionAction { |
| 2161 | /// Original position of the instruction. |
| 2162 | InsertionHandler Position; |
| 2163 | |
| 2164 | public: |
| 2165 | /// \brief Move \p Inst before \p Before. |
| 2166 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2167 | : TypePromotionAction(Inst), Position(Inst) { |
| 2168 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2169 | Inst->moveBefore(Before); |
| 2170 | } |
| 2171 | |
| 2172 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2173 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2174 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2175 | Position.insert(Inst); |
| 2176 | } |
| 2177 | }; |
| 2178 | |
| 2179 | /// \brief Set the operand of an instruction with a new value. |
| 2180 | class OperandSetter : public TypePromotionAction { |
| 2181 | /// Original operand of the instruction. |
| 2182 | Value *Origin; |
| 2183 | /// Index of the modified instruction. |
| 2184 | unsigned Idx; |
| 2185 | |
| 2186 | public: |
| 2187 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2188 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2189 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2190 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2191 | << "for:" << *Inst << "\n" |
| 2192 | << "with:" << *NewVal << "\n"); |
| 2193 | Origin = Inst->getOperand(Idx); |
| 2194 | Inst->setOperand(Idx, NewVal); |
| 2195 | } |
| 2196 | |
| 2197 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2198 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2199 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2200 | << "for: " << *Inst << "\n" |
| 2201 | << "with: " << *Origin << "\n"); |
| 2202 | Inst->setOperand(Idx, Origin); |
| 2203 | } |
| 2204 | }; |
| 2205 | |
| 2206 | /// \brief Hide the operands of an instruction. |
| 2207 | /// Do as if this instruction was not using any of its operands. |
| 2208 | class OperandsHider : public TypePromotionAction { |
| 2209 | /// The list of original operands. |
| 2210 | SmallVector<Value *, 4> OriginalValues; |
| 2211 | |
| 2212 | public: |
| 2213 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2214 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2215 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2216 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2217 | OriginalValues.reserve(NumOpnds); |
| 2218 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2219 | // Save the current operand. |
| 2220 | Value *Val = Inst->getOperand(It); |
| 2221 | OriginalValues.push_back(Val); |
| 2222 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2223 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2224 | // that we are not willing to pay. |
| 2225 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2226 | } |
| 2227 | } |
| 2228 | |
| 2229 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2230 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2231 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2232 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2233 | Inst->setOperand(It, OriginalValues[It]); |
| 2234 | } |
| 2235 | }; |
| 2236 | |
| 2237 | /// \brief Build a truncate instruction. |
| 2238 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2239 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2240 | public: |
| 2241 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2242 | /// result. |
| 2243 | /// trunc Opnd to Ty. |
| 2244 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2245 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2246 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2247 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2248 | } |
| 2249 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2250 | /// \brief Get the built value. |
| 2251 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2252 | |
| 2253 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2254 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2255 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2256 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2257 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2258 | } |
| 2259 | }; |
| 2260 | |
| 2261 | /// \brief Build a sign extension instruction. |
| 2262 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2263 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2264 | public: |
| 2265 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2266 | /// result. |
| 2267 | /// sext Opnd to Ty. |
| 2268 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2269 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2270 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2271 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2272 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2273 | } |
| 2274 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2275 | /// \brief Get the built value. |
| 2276 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2277 | |
| 2278 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2279 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2280 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2281 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2282 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2283 | } |
| 2284 | }; |
| 2285 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2286 | /// \brief Build a zero extension instruction. |
| 2287 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2288 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2289 | public: |
| 2290 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2291 | /// result. |
| 2292 | /// zext Opnd to Ty. |
| 2293 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2294 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2295 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2296 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2297 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2298 | } |
| 2299 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2300 | /// \brief Get the built value. |
| 2301 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2302 | |
| 2303 | /// \brief Remove the built instruction. |
| 2304 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2305 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2306 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2307 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2308 | } |
| 2309 | }; |
| 2310 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2311 | /// \brief Mutate an instruction to another type. |
| 2312 | class TypeMutator : public TypePromotionAction { |
| 2313 | /// Record the original type. |
| 2314 | Type *OrigTy; |
| 2315 | |
| 2316 | public: |
| 2317 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2318 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2319 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2320 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2321 | << "\n"); |
| 2322 | Inst->mutateType(NewTy); |
| 2323 | } |
| 2324 | |
| 2325 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2326 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2327 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2328 | << "\n"); |
| 2329 | Inst->mutateType(OrigTy); |
| 2330 | } |
| 2331 | }; |
| 2332 | |
| 2333 | /// \brief Replace the uses of an instruction by another instruction. |
| 2334 | class UsesReplacer : public TypePromotionAction { |
| 2335 | /// Helper structure to keep track of the replaced uses. |
| 2336 | struct InstructionAndIdx { |
| 2337 | /// The instruction using the instruction. |
| 2338 | Instruction *Inst; |
| 2339 | /// The index where this instruction is used for Inst. |
| 2340 | unsigned Idx; |
| 2341 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2342 | : Inst(Inst), Idx(Idx) {} |
| 2343 | }; |
| 2344 | |
| 2345 | /// Keep track of the original uses (pair Instruction, Index). |
| 2346 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 2347 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 2348 | |
| 2349 | public: |
| 2350 | /// \brief Replace all the use of \p Inst by \p New. |
| 2351 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2352 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2353 | << "\n"); |
| 2354 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2355 | for (Use &U : Inst->uses()) { |
| 2356 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2357 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2358 | } |
| 2359 | // Now, we can replace the uses. |
| 2360 | Inst->replaceAllUsesWith(New); |
| 2361 | } |
| 2362 | |
| 2363 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2364 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2365 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2366 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2367 | EndIt = OriginalUses.end(); |
| 2368 | UseIt != EndIt; ++UseIt) { |
| 2369 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2370 | } |
| 2371 | } |
| 2372 | }; |
| 2373 | |
| 2374 | /// \brief Remove an instruction from the IR. |
| 2375 | class InstructionRemover : public TypePromotionAction { |
| 2376 | /// Original position of the instruction. |
| 2377 | InsertionHandler Inserter; |
| 2378 | /// Helper structure to hide all the link to the instruction. In other |
| 2379 | /// words, this helps to do as if the instruction was removed. |
| 2380 | OperandsHider Hider; |
| 2381 | /// Keep track of the uses replaced, if any. |
| 2382 | UsesReplacer *Replacer; |
| 2383 | |
| 2384 | public: |
| 2385 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2386 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2387 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 2388 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2389 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2390 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2391 | if (New) |
| 2392 | Replacer = new UsesReplacer(Inst, New); |
| 2393 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 2394 | Inst->removeFromParent(); |
| 2395 | } |
| 2396 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2397 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2398 | |
| 2399 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2400 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2401 | |
| 2402 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2403 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2404 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2405 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2406 | Inserter.insert(Inst); |
| 2407 | if (Replacer) |
| 2408 | Replacer->undo(); |
| 2409 | Hider.undo(); |
| 2410 | } |
| 2411 | }; |
| 2412 | |
| 2413 | public: |
| 2414 | /// Restoration point. |
| 2415 | /// The restoration point is a pointer to an action instead of an iterator |
| 2416 | /// because the iterator may be invalidated but not the pointer. |
| 2417 | typedef const TypePromotionAction *ConstRestorationPt; |
| 2418 | /// Advocate every changes made in that transaction. |
| 2419 | void commit(); |
| 2420 | /// Undo all the changes made after the given point. |
| 2421 | void rollback(ConstRestorationPt Point); |
| 2422 | /// Get the current restoration point. |
| 2423 | ConstRestorationPt getRestorationPoint() const; |
| 2424 | |
| 2425 | /// \name API for IR modification with state keeping to support rollback. |
| 2426 | /// @{ |
| 2427 | /// Same as Instruction::setOperand. |
| 2428 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2429 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2430 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2431 | /// Same as Value::replaceAllUsesWith. |
| 2432 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2433 | /// Same as Value::mutateType. |
| 2434 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2435 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2436 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2437 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2438 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2439 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2440 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2441 | /// Same as Instruction::moveBefore. |
| 2442 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2443 | /// @} |
| 2444 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2445 | private: |
| 2446 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2447 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2448 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2449 | }; |
| 2450 | |
| 2451 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2452 | Value *NewVal) { |
| 2453 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2454 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2455 | } |
| 2456 | |
| 2457 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2458 | Value *NewVal) { |
| 2459 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2460 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2461 | } |
| 2462 | |
| 2463 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2464 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2465 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2466 | } |
| 2467 | |
| 2468 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2469 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2470 | } |
| 2471 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2472 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2473 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2474 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2475 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2476 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2477 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2478 | } |
| 2479 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2480 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2481 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2482 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2483 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2484 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2485 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2486 | } |
| 2487 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2488 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2489 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2490 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2491 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2492 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2493 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2494 | } |
| 2495 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2496 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2497 | Instruction *Before) { |
| 2498 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2499 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2500 | } |
| 2501 | |
| 2502 | TypePromotionTransaction::ConstRestorationPt |
| 2503 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2504 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2505 | } |
| 2506 | |
| 2507 | void TypePromotionTransaction::commit() { |
| 2508 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2509 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2510 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2511 | Actions.clear(); |
| 2512 | } |
| 2513 | |
| 2514 | void TypePromotionTransaction::rollback( |
| 2515 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2516 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2517 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2518 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2519 | } |
| 2520 | } |
| 2521 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2522 | /// \brief A helper class for matching addressing modes. |
| 2523 | /// |
| 2524 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2525 | class AddressingModeMatcher { |
| 2526 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2527 | const TargetMachine &TM; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2528 | const TargetLowering &TLI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2529 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2530 | |
| 2531 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2532 | /// the memory instruction that we're computing this address for. |
| 2533 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2534 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2535 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2536 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2537 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2538 | /// part of the return value of this addressing mode matching stuff. |
| 2539 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2540 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2541 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2542 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2543 | /// A map from the instructions to their type before promotion. |
| 2544 | InstrToOrigTy &PromotedInsts; |
| 2545 | /// The ongoing transaction where every action should be registered. |
| 2546 | TypePromotionTransaction &TPT; |
| 2547 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2548 | /// This is set to true when we should not do profitability checks. |
| 2549 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2550 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2551 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2552 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2553 | const TargetMachine &TM, Type *AT, unsigned AS, |
| 2554 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2555 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2556 | InstrToOrigTy &PromotedInsts, |
| 2557 | TypePromotionTransaction &TPT) |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2558 | : AddrModeInsts(AMI), TM(TM), |
| 2559 | TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent()) |
| 2560 | ->getTargetLowering()), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2561 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 2562 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 2563 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2564 | IgnoreProfitability = false; |
| 2565 | } |
| 2566 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2567 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2568 | /// Find the maximal addressing mode that a load/store of V can fold, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2569 | /// give an access type of AccessTy. This returns a list of involved |
| 2570 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2571 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2572 | /// optimizations. |
| 2573 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2574 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2575 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2576 | Instruction *MemoryInst, |
| 2577 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2578 | const TargetMachine &TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2579 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2580 | InstrToOrigTy &PromotedInsts, |
| 2581 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2582 | ExtAddrMode Result; |
| 2583 | |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2584 | bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2585 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2586 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2587 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2588 | return Result; |
| 2589 | } |
| 2590 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2591 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 2592 | bool matchAddr(Value *V, unsigned Depth); |
| 2593 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2594 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2595 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2596 | ExtAddrMode &AMBefore, |
| 2597 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2598 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 2599 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2600 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2601 | }; |
| 2602 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2603 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2604 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 2605 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2606 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2607 | unsigned Depth) { |
| 2608 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 2609 | // mode. Just process that directly. |
| 2610 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2611 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2612 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2613 | // If the scale is 0, it takes nothing to add this. |
| 2614 | if (Scale == 0) |
| 2615 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2616 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2617 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 2618 | // need an available scale field. |
| 2619 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 2620 | return false; |
| 2621 | |
| 2622 | ExtAddrMode TestAddrMode = AddrMode; |
| 2623 | |
| 2624 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 2625 | // [A+B + A*7] -> [B+A*8]. |
| 2626 | TestAddrMode.Scale += Scale; |
| 2627 | TestAddrMode.ScaledReg = ScaleReg; |
| 2628 | |
| 2629 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2630 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2631 | return false; |
| 2632 | |
| 2633 | // It was legal, so commit it. |
| 2634 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2635 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2636 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 2637 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 2638 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2639 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2640 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 2641 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 2642 | TestAddrMode.ScaledReg = AddLHS; |
| 2643 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2644 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2645 | // If this addressing mode is legal, commit it and remember that we folded |
| 2646 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2647 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2648 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 2649 | AddrMode = TestAddrMode; |
| 2650 | return true; |
| 2651 | } |
| 2652 | } |
| 2653 | |
| 2654 | // Otherwise, not (x+c)*scale, just return what we have. |
| 2655 | return true; |
| 2656 | } |
| 2657 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2658 | /// This is a little filter, which returns true if an addressing computation |
| 2659 | /// involving I might be folded into a load/store accessing it. |
| 2660 | /// This doesn't need to be perfect, but needs to accept at least |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2661 | /// the set of instructions that MatchOperationAddr can. |
| 2662 | static bool MightBeFoldableInst(Instruction *I) { |
| 2663 | switch (I->getOpcode()) { |
| 2664 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 2665 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2666 | // Don't touch identity bitcasts. |
| 2667 | if (I->getType() == I->getOperand(0)->getType()) |
| 2668 | return false; |
| 2669 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 2670 | case Instruction::PtrToInt: |
| 2671 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2672 | return true; |
| 2673 | case Instruction::IntToPtr: |
| 2674 | // We know the input is intptr_t, so this is foldable. |
| 2675 | return true; |
| 2676 | case Instruction::Add: |
| 2677 | return true; |
| 2678 | case Instruction::Mul: |
| 2679 | case Instruction::Shl: |
| 2680 | // Can only handle X*C and X << C. |
| 2681 | return isa<ConstantInt>(I->getOperand(1)); |
| 2682 | case Instruction::GetElementPtr: |
| 2683 | return true; |
| 2684 | default: |
| 2685 | return false; |
| 2686 | } |
| 2687 | } |
| 2688 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2689 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 2690 | /// \note \p Val is assumed to be the product of some type promotion. |
| 2691 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 2692 | /// to be legal, as the non-promoted value would have had the same state. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2693 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 2694 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2695 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 2696 | if (!PromotedInst) |
| 2697 | return false; |
| 2698 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 2699 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 2700 | if (!ISDOpcode) |
| 2701 | return true; |
| 2702 | // Otherwise, check if the promoted instruction is legal or not. |
| 2703 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2704 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2705 | } |
| 2706 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2707 | /// \brief Hepler class to perform type promotion. |
| 2708 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2709 | /// \brief Utility function to check whether or not a sign or zero extension |
| 2710 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 2711 | /// either using the operands of \p Inst or promoting \p Inst. |
| 2712 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2713 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2714 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2715 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2716 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2717 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2718 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2719 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2720 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 2721 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2722 | |
| 2723 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 2724 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2725 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 2726 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2727 | } |
| 2728 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2729 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2730 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2731 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2732 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2733 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2734 | /// Newly added extensions are inserted in \p Exts. |
| 2735 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2736 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2737 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2738 | static Value *promoteOperandForTruncAndAnyExt( |
| 2739 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2740 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2741 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2742 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2743 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2744 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2745 | /// operand is promotable and is not a supported trunc or sext. |
| 2746 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2747 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2748 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2749 | /// Newly added extensions are inserted in \p Exts. |
| 2750 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2751 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2752 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2753 | static Value *promoteOperandForOther(Instruction *Ext, |
| 2754 | TypePromotionTransaction &TPT, |
| 2755 | InstrToOrigTy &PromotedInsts, |
| 2756 | unsigned &CreatedInstsCost, |
| 2757 | SmallVectorImpl<Instruction *> *Exts, |
| 2758 | SmallVectorImpl<Instruction *> *Truncs, |
| 2759 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2760 | |
| 2761 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2762 | static Value *signExtendOperandForOther( |
| 2763 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2764 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2765 | SmallVectorImpl<Instruction *> *Exts, |
| 2766 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2767 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2768 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2769 | } |
| 2770 | |
| 2771 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2772 | static Value *zeroExtendOperandForOther( |
| 2773 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2774 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2775 | SmallVectorImpl<Instruction *> *Exts, |
| 2776 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2777 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2778 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2779 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2780 | |
| 2781 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2782 | /// Type for the utility function that promotes the operand of Ext. |
| 2783 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2784 | InstrToOrigTy &PromotedInsts, |
| 2785 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2786 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2787 | SmallVectorImpl<Instruction *> *Truncs, |
| 2788 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2789 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 2790 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2791 | /// \return NULL if no promotable action is possible with the current |
| 2792 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2793 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 2794 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2795 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 2796 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 2797 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2798 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2799 | const TargetLowering &TLI, |
| 2800 | const InstrToOrigTy &PromotedInsts); |
| 2801 | }; |
| 2802 | |
| 2803 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2804 | Type *ConsideredExtType, |
| 2805 | const InstrToOrigTy &PromotedInsts, |
| 2806 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2807 | // The promotion helper does not know how to deal with vector types yet. |
| 2808 | // To be able to fix that, we would need to fix the places where we |
| 2809 | // statically extend, e.g., constants and such. |
| 2810 | if (Inst->getType()->isVectorTy()) |
| 2811 | return false; |
| 2812 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2813 | // We can always get through zext. |
| 2814 | if (isa<ZExtInst>(Inst)) |
| 2815 | return true; |
| 2816 | |
| 2817 | // sext(sext) is ok too. |
| 2818 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2819 | return true; |
| 2820 | |
| 2821 | // We can get through binary operator, if it is legal. In other words, the |
| 2822 | // binary operator must have a nuw or nsw flag. |
| 2823 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 2824 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2825 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 2826 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2827 | return true; |
| 2828 | |
| 2829 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2830 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2831 | if (!isa<TruncInst>(Inst)) |
| 2832 | return false; |
| 2833 | |
| 2834 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2835 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2836 | // If the type is larger than the result type of the extension, we cannot. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2837 | if (!OpndVal->getType()->isIntegerTy() || |
| 2838 | OpndVal->getType()->getIntegerBitWidth() > |
| 2839 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2840 | return false; |
| 2841 | |
| 2842 | // If the operand of the truncate is not an instruction, we will not have |
| 2843 | // any information on the dropped bits. |
| 2844 | // (Actually we could for constant but it is not worth the extra logic). |
| 2845 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 2846 | if (!Opnd) |
| 2847 | return false; |
| 2848 | |
| 2849 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2850 | // I.e., check that trunc just drops extended bits of the same kind of |
| 2851 | // the extension. |
| 2852 | // #1 get the type of the operand and check the kind of the extended bits. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2853 | const Type *OpndType; |
| 2854 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 2855 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 2856 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2857 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 2858 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2859 | else |
| 2860 | return false; |
| 2861 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2862 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 2863 | return Inst->getType()->getIntegerBitWidth() >= |
| 2864 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2865 | } |
| 2866 | |
| 2867 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2868 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2869 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2870 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 2871 | "Unexpected instruction type"); |
| 2872 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 2873 | Type *ExtTy = Ext->getType(); |
| 2874 | bool IsSExt = isa<SExtInst>(Ext); |
| 2875 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2876 | // get through. |
| 2877 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2878 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2879 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2880 | |
| 2881 | // Do not promote if the operand has been added by codegenprepare. |
| 2882 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 2883 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2884 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2885 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2886 | |
| 2887 | // SExt or Trunc instructions. |
| 2888 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2889 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 2890 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2891 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2892 | |
| 2893 | // Regular instruction. |
| 2894 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2895 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2896 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2897 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2898 | } |
| 2899 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2900 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2901 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2902 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2903 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2904 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2905 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 2906 | // get through it and this method should not be called. |
| 2907 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2908 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2909 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2910 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2911 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2912 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2913 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2914 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2915 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 2916 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 2917 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2918 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2919 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2920 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 2921 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2922 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 2923 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2924 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2925 | |
| 2926 | // Remove dead code. |
| 2927 | if (SExtOpnd->use_empty()) |
| 2928 | TPT.eraseInstruction(SExtOpnd); |
| 2929 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2930 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2931 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2932 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2933 | if (ExtInst) { |
| 2934 | if (Exts) |
| 2935 | Exts->push_back(ExtInst); |
| 2936 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 2937 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2938 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2939 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2940 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2941 | // At this point we have: ext ty opnd to ty. |
| 2942 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 2943 | Value *NextVal = ExtInst->getOperand(0); |
| 2944 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2945 | return NextVal; |
| 2946 | } |
| 2947 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2948 | Value *TypePromotionHelper::promoteOperandForOther( |
| 2949 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2950 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2951 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2952 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 2953 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2954 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2955 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2956 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2957 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2958 | if (!ExtOpnd->hasOneUse()) { |
| 2959 | // ExtOpnd will be promoted. |
| 2960 | // All its uses, but Ext, will need to use a truncated value of the |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2961 | // promoted version. |
| 2962 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2963 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2964 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 2965 | ITrunc->removeFromParent(); |
| 2966 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2967 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2968 | if (Truncs) |
| 2969 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2970 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2971 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2972 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2973 | // Restore the operand of Ext (which has been replaced by the previous call |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2974 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2975 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2976 | } |
| 2977 | |
| 2978 | // Get through the Instruction: |
| 2979 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2980 | // 2. Replace the uses of Ext by Inst. |
| 2981 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2982 | |
| 2983 | // Remember the original type of the instruction before promotion. |
| 2984 | // This is useful to know that the high bits are sign extended bits. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2985 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 2986 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2987 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2988 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2989 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2990 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2991 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2992 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2993 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2994 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 2995 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2996 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2997 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 2998 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 2999 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3000 | DEBUG(dbgs() << "No need to propagate\n"); |
| 3001 | continue; |
| 3002 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3003 | // Check if we can statically extend the operand. |
| 3004 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3005 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3006 | DEBUG(dbgs() << "Statically extend\n"); |
| 3007 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3008 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3009 | : Cst->getValue().zext(BitWidth); |
| 3010 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3011 | continue; |
| 3012 | } |
| 3013 | // UndefValue are typed, so we have to statically sign extend them. |
| 3014 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3015 | DEBUG(dbgs() << "Statically extend\n"); |
| 3016 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3017 | continue; |
| 3018 | } |
| 3019 | |
| 3020 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3021 | // Check if Ext was reused to extend an operand. |
| 3022 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3023 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3024 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3025 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3026 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3027 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3028 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3029 | continue; |
| 3030 | } |
| 3031 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3032 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3033 | if (Exts) |
| 3034 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3035 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3036 | |
| 3037 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3038 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3039 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3040 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3041 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3042 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3043 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3044 | if (ExtForOpnd == Ext) { |
| 3045 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 3046 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3047 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3048 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3049 | } |
| 3050 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3051 | /// Check whether or not promoting an instruction to a wider type is profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3052 | /// \p NewCost gives the cost of extension instructions created by the |
| 3053 | /// promotion. |
| 3054 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3055 | /// plus the number of instructions that have been |
| 3056 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3057 | /// \p PromotedOperand is the value that has been promoted. |
| 3058 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3059 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3060 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 3061 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 3062 | // The cost of the new extensions is greater than the cost of the |
| 3063 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3064 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3065 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3066 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3067 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3068 | return true; |
| 3069 | // The promotion is neutral but it may help folding the sign extension in |
| 3070 | // loads for instance. |
| 3071 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3072 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3073 | } |
| 3074 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3075 | /// Given an instruction or constant expr, see if we can fold the operation |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3076 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3077 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3078 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3079 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3080 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3081 | /// because it has been moved away. |
| 3082 | /// Thus AddrInst must not be added in the matched instructions. |
| 3083 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3084 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3085 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3086 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3087 | unsigned Depth, |
| 3088 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3089 | // Avoid exponential behavior on extremely deep expression trees. |
| 3090 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3091 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3092 | // By default, all matched instructions stay in place. |
| 3093 | if (MovedAway) |
| 3094 | *MovedAway = false; |
| 3095 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3096 | switch (Opcode) { |
| 3097 | case Instruction::PtrToInt: |
| 3098 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3099 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3100 | case Instruction::IntToPtr: { |
| 3101 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3102 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3103 | // This inttoptr is a no-op if the integer type is pointer sized. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3104 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3105 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3106 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3107 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3108 | case Instruction::BitCast: |
| 3109 | // BitCast is always a noop, and we can handle it as long as it is |
| 3110 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3111 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3112 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3113 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3114 | // and we don't want to mess around with them. Assume it knows what it |
| 3115 | // is doing. |
| 3116 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3117 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3118 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3119 | case Instruction::AddrSpaceCast: { |
| 3120 | unsigned SrcAS |
| 3121 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3122 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3123 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3124 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3125 | return false; |
| 3126 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3127 | case Instruction::Add: { |
| 3128 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3129 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3130 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3131 | // Start a transaction at this point. |
| 3132 | // The LHS may match but not the RHS. |
| 3133 | // Therefore, we need a higher level restoration point to undo partially |
| 3134 | // matched operation. |
| 3135 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3136 | TPT.getRestorationPoint(); |
| 3137 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3138 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3139 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3140 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3141 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3142 | // Restore the old addr mode info. |
| 3143 | AddrMode = BackupAddrMode; |
| 3144 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3145 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3146 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3147 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3148 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3149 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3150 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3151 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3152 | // Otherwise we definitely can't merge the ADD in. |
| 3153 | AddrMode = BackupAddrMode; |
| 3154 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3155 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3156 | break; |
| 3157 | } |
| 3158 | //case Instruction::Or: |
| 3159 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3160 | //break; |
| 3161 | case Instruction::Mul: |
| 3162 | case Instruction::Shl: { |
| 3163 | // Can only handle X*C and X << C. |
| 3164 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3165 | if (!RHS) |
| 3166 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3167 | int64_t Scale = RHS->getSExtValue(); |
| 3168 | if (Opcode == Instruction::Shl) |
| 3169 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3170 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3171 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3172 | } |
| 3173 | case Instruction::GetElementPtr: { |
| 3174 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3175 | // one variable offset. |
| 3176 | int VariableOperand = -1; |
| 3177 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3178 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3179 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3180 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3181 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
| 3182 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3183 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3184 | unsigned Idx = |
| 3185 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3186 | ConstantOffset += SL->getElementOffset(Idx); |
| 3187 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3188 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3189 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3190 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3191 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3192 | // We only allow one variable index at the moment. |
| 3193 | if (VariableOperand != -1) |
| 3194 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3195 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3196 | // Remember the variable index. |
| 3197 | VariableOperand = i; |
| 3198 | VariableScale = TypeSize; |
| 3199 | } |
| 3200 | } |
| 3201 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3202 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3203 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3204 | // just add it to the disp field and check validity. |
| 3205 | if (VariableOperand == -1) { |
| 3206 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3207 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3208 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3209 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3210 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3211 | return true; |
| 3212 | } |
| 3213 | AddrMode.BaseOffs -= ConstantOffset; |
| 3214 | return false; |
| 3215 | } |
| 3216 | |
| 3217 | // Save the valid addressing mode in case we can't match. |
| 3218 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3219 | unsigned OldSize = AddrModeInsts.size(); |
| 3220 | |
| 3221 | // See if the scale and offset amount is valid for this target. |
| 3222 | AddrMode.BaseOffs += ConstantOffset; |
| 3223 | |
| 3224 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3225 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3226 | // If it couldn't be matched, just stuff the value in a register. |
| 3227 | if (AddrMode.HasBaseReg) { |
| 3228 | AddrMode = BackupAddrMode; |
| 3229 | AddrModeInsts.resize(OldSize); |
| 3230 | return false; |
| 3231 | } |
| 3232 | AddrMode.HasBaseReg = true; |
| 3233 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3234 | } |
| 3235 | |
| 3236 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3237 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3238 | Depth)) { |
| 3239 | // If it couldn't be matched, try stuffing the base into a register |
| 3240 | // instead of matching it, and retrying the match of the scale. |
| 3241 | AddrMode = BackupAddrMode; |
| 3242 | AddrModeInsts.resize(OldSize); |
| 3243 | if (AddrMode.HasBaseReg) |
| 3244 | return false; |
| 3245 | AddrMode.HasBaseReg = true; |
| 3246 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3247 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3248 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3249 | VariableScale, Depth)) { |
| 3250 | // If even that didn't work, bail. |
| 3251 | AddrMode = BackupAddrMode; |
| 3252 | AddrModeInsts.resize(OldSize); |
| 3253 | return false; |
| 3254 | } |
| 3255 | } |
| 3256 | |
| 3257 | return true; |
| 3258 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3259 | case Instruction::SExt: |
| 3260 | case Instruction::ZExt: { |
| 3261 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3262 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3263 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3264 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3265 | // Try to move this ext out of the way of the addressing mode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3266 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3267 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3268 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3269 | if (!TPH) |
| 3270 | return false; |
| 3271 | |
| 3272 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3273 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3274 | unsigned CreatedInstsCost = 0; |
| 3275 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3276 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3277 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3278 | // SExt has been moved away. |
| 3279 | // Thus either it will be rematched later in the recursive calls or it is |
| 3280 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3281 | // E.g., |
| 3282 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3283 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3284 | // addr = gep base, idx |
| 3285 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3286 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3287 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3288 | // addr = gep base, op <- match |
| 3289 | if (MovedAway) |
| 3290 | *MovedAway = true; |
| 3291 | |
| 3292 | assert(PromotedOperand && |
| 3293 | "TypePromotionHelper should have filtered out those cases"); |
| 3294 | |
| 3295 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3296 | unsigned OldSize = AddrModeInsts.size(); |
| 3297 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3298 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3299 | // The total of the new cost is equal to the cost of the created |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3300 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3301 | // The total of the old cost is equal to the cost of the extension plus |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3302 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3303 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3304 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3305 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3306 | AddrMode = BackupAddrMode; |
| 3307 | AddrModeInsts.resize(OldSize); |
| 3308 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3309 | TPT.rollback(LastKnownGood); |
| 3310 | return false; |
| 3311 | } |
| 3312 | return true; |
| 3313 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3314 | } |
| 3315 | return false; |
| 3316 | } |
| 3317 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3318 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3319 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3320 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3321 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3322 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3323 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3324 | // Start a transaction at this point that we will rollback if the matching |
| 3325 | // fails. |
| 3326 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3327 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3328 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 3329 | // Fold in immediates if legal for the target. |
| 3330 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3331 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3332 | return true; |
| 3333 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 3334 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 3335 | // If this is a global variable, try to fold it into the addressing mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3336 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3337 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3338 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3339 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3340 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3341 | } |
| 3342 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 3343 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3344 | unsigned OldSize = AddrModeInsts.size(); |
| 3345 | |
| 3346 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3347 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3348 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3349 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3350 | // to check here. |
| 3351 | if (MovedAway) |
| 3352 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3353 | // Okay, it's possible to fold this. Check to see if it is actually |
| 3354 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 3355 | // register pressure too much. |
| 3356 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3357 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3358 | AddrModeInsts.push_back(I); |
| 3359 | return true; |
| 3360 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3361 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3362 | // It isn't profitable to do this, roll back. |
| 3363 | //cerr << "NOT FOLDING: " << *I; |
| 3364 | AddrMode = BackupAddrMode; |
| 3365 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3366 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3367 | } |
| 3368 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3369 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3370 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3371 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3372 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 3373 | // Null pointer gets folded without affecting the addressing mode. |
| 3374 | return true; |
| 3375 | } |
| 3376 | |
| 3377 | // Worse case, the target should support [reg] addressing modes. :) |
| 3378 | if (!AddrMode.HasBaseReg) { |
| 3379 | AddrMode.HasBaseReg = true; |
| 3380 | AddrMode.BaseReg = Addr; |
| 3381 | // Still check for legality in case the target supports [imm] but not [i+r]. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3382 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3383 | return true; |
| 3384 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3385 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3386 | } |
| 3387 | |
| 3388 | // If the base register is already taken, see if we can do [r+r]. |
| 3389 | if (AddrMode.Scale == 0) { |
| 3390 | AddrMode.Scale = 1; |
| 3391 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3392 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3393 | return true; |
| 3394 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3395 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3396 | } |
| 3397 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3398 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3399 | return false; |
| 3400 | } |
| 3401 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3402 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 3403 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3404 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3405 | const TargetMachine &TM) { |
| 3406 | const Function *F = CI->getParent()->getParent(); |
| 3407 | const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering(); |
| 3408 | const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3409 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3410 | TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI, |
| 3411 | ImmutableCallSite(CI)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3412 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3413 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3414 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3415 | // Compute the constraint code and ConstraintType to use. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3416 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3417 | |
| 3418 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 3419 | // operand, we can't fold it! |
| 3420 | if (OpInfo.CallOperandVal == OpVal && |
| 3421 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 3422 | !OpInfo.isIndirect)) |
| 3423 | return false; |
| 3424 | } |
| 3425 | |
| 3426 | return true; |
| 3427 | } |
| 3428 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3429 | /// Recursively walk all the uses of I until we find a memory use. |
| 3430 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3431 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3432 | static bool FindAllMemoryUses( |
| 3433 | Instruction *I, |
| 3434 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
| 3435 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3436 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3437 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3438 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3439 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3440 | // If this is an obviously unfoldable instruction, bail out. |
| 3441 | if (!MightBeFoldableInst(I)) |
| 3442 | return true; |
| 3443 | |
| 3444 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3445 | for (Use &U : I->uses()) { |
| 3446 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3447 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3448 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3449 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3450 | continue; |
| 3451 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3452 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3453 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3454 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3455 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 3456 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3457 | continue; |
| 3458 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3459 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3460 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3461 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 3462 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3463 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3464 | // If this is a memory operand, we're cool, otherwise bail out. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3465 | if (!IsOperandAMemoryOperand(CI, IA, I, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3466 | return true; |
| 3467 | continue; |
| 3468 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3469 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3470 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3471 | return true; |
| 3472 | } |
| 3473 | |
| 3474 | return false; |
| 3475 | } |
| 3476 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3477 | /// Return true if Val is already known to be live at the use site that we're |
| 3478 | /// folding it into. If so, there is no cost to include it in the addressing |
| 3479 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 3480 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3481 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3482 | Value *KnownLive2) { |
| 3483 | // If Val is either of the known-live values, we know it is live! |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3484 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3485 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3486 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3487 | // All values other than instructions and arguments (e.g. constants) are live. |
| 3488 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3489 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3490 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 3491 | // true because it is just a reference to the stack/frame pointer, which is |
| 3492 | // live for the whole function. |
| 3493 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 3494 | if (AI->isStaticAlloca()) |
| 3495 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3496 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3497 | // Check to see if this value is already used in the memory instruction's |
| 3498 | // block. If so, it's already live into the block at the very least, so we |
| 3499 | // can reasonably fold it. |
| 3500 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 3501 | } |
| 3502 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3503 | /// It is possible for the addressing mode of the machine to fold the specified |
| 3504 | /// instruction into a load or store that ultimately uses it. |
| 3505 | /// However, the specified instruction has multiple uses. |
| 3506 | /// Given this, it may actually increase register pressure to fold it |
| 3507 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3508 | /// |
| 3509 | /// X = ... |
| 3510 | /// Y = X+1 |
| 3511 | /// use(Y) -> nonload/store |
| 3512 | /// Z = Y+1 |
| 3513 | /// load Z |
| 3514 | /// |
| 3515 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 3516 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 3517 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 3518 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 3519 | /// number of computations either. |
| 3520 | /// |
| 3521 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 3522 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 3523 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 3524 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3525 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3526 | ExtAddrMode &AMAfter) { |
| 3527 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3528 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3529 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 3530 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 3531 | // the set of registers referenced by AMAfter and subtract out those |
| 3532 | // referenced by AMBefore: this is the set of values which folding in this |
| 3533 | // address extends the lifetime of. |
| 3534 | // |
| 3535 | // Note that there are only two potential values being referenced here, |
| 3536 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 3537 | // folded immediates). |
| 3538 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3539 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3540 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 3541 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3542 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3543 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3544 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3545 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3546 | |
| 3547 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 3548 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3549 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3550 | return true; |
| 3551 | |
| 3552 | // If all uses of this instruction are ultimately load/store/inlineasm's, |
| 3553 | // check to see if their addressing modes will include this instruction. If |
| 3554 | // so, we can fold it into all uses, so it doesn't matter if it has multiple |
| 3555 | // uses. |
| 3556 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 3557 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3558 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3559 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3560 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3561 | // Now that we know that all uses of this instruction are part of a chain of |
| 3562 | // computation involving only operations that could theoretically be folded |
| 3563 | // into a memory use, loop over each of these uses and see if they could |
| 3564 | // *actually* fold the instruction. |
| 3565 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 3566 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 3567 | Instruction *User = MemoryUses[i].first; |
| 3568 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3569 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3570 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 3571 | // know what it accesses. |
| 3572 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3573 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 3574 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3575 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3576 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 3577 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3578 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3579 | // Do a match against the root of this address, ignoring profitability. This |
| 3580 | // will tell us if the addressing mode for the memory operation will |
| 3581 | // *actually* cover the shared instruction. |
| 3582 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3583 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3584 | TPT.getRestorationPoint(); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3585 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3586 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3587 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3588 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3589 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3590 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3591 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3592 | // The match was to check the profitability, the changes made are not |
| 3593 | // part of the original matcher. Therefore, they should be dropped |
| 3594 | // otherwise the original matcher will not present the right state. |
| 3595 | TPT.rollback(LastKnownGood); |
| 3596 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3597 | // If the match didn't cover I, then it won't be shared by it. |
| 3598 | if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(), |
| 3599 | I) == MatchedAddrModeInsts.end()) |
| 3600 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3601 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3602 | MatchedAddrModeInsts.clear(); |
| 3603 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3604 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3605 | return true; |
| 3606 | } |
| 3607 | |
| 3608 | } // end anonymous namespace |
| 3609 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3610 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3611 | /// different basic block than BB. |
| 3612 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 3613 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 3614 | return I->getParent() != BB; |
| 3615 | return false; |
| 3616 | } |
| 3617 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3618 | /// Load and Store Instructions often have addressing modes that can do |
| 3619 | /// significant amounts of computation. As such, instruction selection will try |
| 3620 | /// to get the load or store to do as much computation as possible for the |
| 3621 | /// program. The problem is that isel can only see within a single block. As |
| 3622 | /// such, we sink as much legal addressing mode work into the block as possible. |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 3623 | /// |
| 3624 | /// This method is used to optimize both load/store and inline asms with memory |
| 3625 | /// operands. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3626 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3627 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3628 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3629 | |
| 3630 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3631 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 3632 | SmallVector<Value*, 8> worklist; |
| 3633 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3634 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3635 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3636 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 3637 | // the addressing mode obtained from the non-PHI roots of the graph |
| 3638 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3639 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3640 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3641 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3642 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 3643 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3644 | TypePromotionTransaction TPT; |
| 3645 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3646 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3647 | while (!worklist.empty()) { |
| 3648 | Value *V = worklist.back(); |
| 3649 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3650 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3651 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3652 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3653 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3654 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3655 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3656 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3657 | // For a PHI node, push all of its incoming values. |
| 3658 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 3659 | for (Value *IncValue : P->incoming_values()) |
| 3660 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3661 | continue; |
| 3662 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3663 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3664 | // For non-PHIs, determine the addressing mode being computed. |
| 3665 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3666 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3667 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3668 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3669 | |
| 3670 | // This check is broken into two cases with very similar code to avoid using |
| 3671 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 3672 | // calling getNumUses() unconditionally caused a significant compile-time |
| 3673 | // regression. |
| 3674 | if (!Consensus) { |
| 3675 | Consensus = V; |
| 3676 | AddrMode = NewAddrMode; |
| 3677 | AddrModeInsts = NewAddrModeInsts; |
| 3678 | continue; |
| 3679 | } else if (NewAddrMode == AddrMode) { |
| 3680 | if (!IsNumUsesConsensusValid) { |
| 3681 | NumUsesConsensus = Consensus->getNumUses(); |
| 3682 | IsNumUsesConsensusValid = true; |
| 3683 | } |
| 3684 | |
| 3685 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 3686 | // for all other roots of the PHI traversal. Also, when choosing one |
| 3687 | // such root as representative, select the one with the most uses in order |
| 3688 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 3689 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3690 | unsigned NumUses = V->getNumUses(); |
| 3691 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3692 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3693 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3694 | AddrModeInsts = NewAddrModeInsts; |
| 3695 | } |
| 3696 | continue; |
| 3697 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3698 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3699 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3700 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3701 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3702 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3703 | // If the addressing mode couldn't be determined, or if multiple different |
| 3704 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3705 | if (!Consensus) { |
| 3706 | TPT.rollback(LastKnownGood); |
| 3707 | return false; |
| 3708 | } |
| 3709 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3710 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3711 | // Check to see if any of the instructions supersumed by this addr mode are |
| 3712 | // non-local to I's BB. |
| 3713 | bool AnyNonLocal = false; |
| 3714 | for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) { |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 3715 | if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) { |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3716 | AnyNonLocal = true; |
| 3717 | break; |
| 3718 | } |
| 3719 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3720 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3721 | // If all the instructions matched are already in this BB, don't do anything. |
| 3722 | if (!AnyNonLocal) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3723 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3724 | return false; |
| 3725 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3726 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3727 | // Insert this computation right after this user. Since our caller is |
| 3728 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 3729 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3730 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3731 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3732 | // Now that we determined the addressing expression we want to use and know |
| 3733 | // that we have to sink it into this block. Check to see if we have already |
| 3734 | // done this for some other load/store instr in this block. If so, reuse the |
| 3735 | // computation. |
| 3736 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 3737 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3738 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3739 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3740 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 3741 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 3742 | } else if (AddrSinkUsingGEPs || |
| 3743 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Eric Christopher | 2c63549 | 2015-01-27 07:54:39 +0000 | [diff] [blame] | 3744 | TM->getSubtargetImpl(*MemoryInst->getParent()->getParent()) |
| 3745 | ->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3746 | // By default, we use the GEP-based method when AA is used later. This |
| 3747 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 3748 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3749 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3750 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3751 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3752 | |
| 3753 | // First, find the pointer. |
| 3754 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 3755 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3756 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3757 | } |
| 3758 | |
| 3759 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 3760 | // We can't add more than one pointer together, nor can we scale a |
| 3761 | // pointer (both of which seem meaningless). |
| 3762 | if (ResultPtr || AddrMode.Scale != 1) |
| 3763 | return false; |
| 3764 | |
| 3765 | ResultPtr = AddrMode.ScaledReg; |
| 3766 | AddrMode.Scale = 0; |
| 3767 | } |
| 3768 | |
| 3769 | if (AddrMode.BaseGV) { |
| 3770 | if (ResultPtr) |
| 3771 | return false; |
| 3772 | |
| 3773 | ResultPtr = AddrMode.BaseGV; |
| 3774 | } |
| 3775 | |
| 3776 | // If the real base value actually came from an inttoptr, then the matcher |
| 3777 | // will look through it and provide only the integer value. In that case, |
| 3778 | // use it here. |
| 3779 | if (!ResultPtr && AddrMode.BaseReg) { |
| 3780 | ResultPtr = |
| 3781 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3782 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3783 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 3784 | ResultPtr = |
| 3785 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 3786 | AddrMode.Scale = 0; |
| 3787 | } |
| 3788 | |
| 3789 | if (!ResultPtr && |
| 3790 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 3791 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 3792 | } else if (!ResultPtr) { |
| 3793 | return false; |
| 3794 | } else { |
| 3795 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3796 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 3797 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3798 | |
| 3799 | // Start with the base register. Do this first so that subsequent address |
| 3800 | // matching finds it last, which will prevent it from trying to match it |
| 3801 | // as the scaled value in case it happens to be a mul. That would be |
| 3802 | // problematic if we've sunk a different mul for the scale, because then |
| 3803 | // we'd end up sinking both muls. |
| 3804 | if (AddrMode.BaseReg) { |
| 3805 | Value *V = AddrMode.BaseReg; |
| 3806 | if (V->getType() != IntPtrTy) |
| 3807 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 3808 | |
| 3809 | ResultIndex = V; |
| 3810 | } |
| 3811 | |
| 3812 | // Add the scale value. |
| 3813 | if (AddrMode.Scale) { |
| 3814 | Value *V = AddrMode.ScaledReg; |
| 3815 | if (V->getType() == IntPtrTy) { |
| 3816 | // done. |
| 3817 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3818 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 3819 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 3820 | } else { |
| 3821 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3822 | // required to create it did not overflow before we extend it. Since |
| 3823 | // the original IR value was tossed in favor of a constant back when |
| 3824 | // the AddrMode was created we need to bail out gracefully if widths |
| 3825 | // do not match instead of extending it. |
| 3826 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 3827 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 3828 | I->eraseFromParent(); |
| 3829 | return false; |
| 3830 | } |
| 3831 | |
| 3832 | if (AddrMode.Scale != 1) |
| 3833 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3834 | "sunkaddr"); |
| 3835 | if (ResultIndex) |
| 3836 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 3837 | else |
| 3838 | ResultIndex = V; |
| 3839 | } |
| 3840 | |
| 3841 | // Add in the Base Offset if present. |
| 3842 | if (AddrMode.BaseOffs) { |
| 3843 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 3844 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 3845 | // We need to add this separately from the scale above to help with |
| 3846 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3847 | if (ResultPtr->getType() != I8PtrTy) |
| 3848 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3849 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3850 | } |
| 3851 | |
| 3852 | ResultIndex = V; |
| 3853 | } |
| 3854 | |
| 3855 | if (!ResultIndex) { |
| 3856 | SunkAddr = ResultPtr; |
| 3857 | } else { |
| 3858 | if (ResultPtr->getType() != I8PtrTy) |
| 3859 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3860 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3861 | } |
| 3862 | |
| 3863 | if (SunkAddr->getType() != Addr->getType()) |
| 3864 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 3865 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3866 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3867 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3868 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3869 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3870 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3871 | |
| 3872 | // Start with the base register. Do this first so that subsequent address |
| 3873 | // matching finds it last, which will prevent it from trying to match it |
| 3874 | // as the scaled value in case it happens to be a mul. That would be |
| 3875 | // problematic if we've sunk a different mul for the scale, because then |
| 3876 | // we'd end up sinking both muls. |
| 3877 | if (AddrMode.BaseReg) { |
| 3878 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3879 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3880 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3881 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3882 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3883 | Result = V; |
| 3884 | } |
| 3885 | |
| 3886 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3887 | if (AddrMode.Scale) { |
| 3888 | Value *V = AddrMode.ScaledReg; |
| 3889 | if (V->getType() == IntPtrTy) { |
| 3890 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3891 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3892 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3893 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3894 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3895 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3896 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3897 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3898 | // required to create it did not overflow before we extend it. Since |
| 3899 | // the original IR value was tossed in favor of a constant back when |
| 3900 | // the AddrMode was created we need to bail out gracefully if widths |
| 3901 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 3902 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 3903 | if (I && (Result != AddrMode.BaseReg)) |
| 3904 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3905 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3906 | } |
| 3907 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3908 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3909 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3910 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3911 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3912 | else |
| 3913 | Result = V; |
| 3914 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3915 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3916 | // Add in the BaseGV if present. |
| 3917 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3918 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3919 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3920 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3921 | else |
| 3922 | Result = V; |
| 3923 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3924 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3925 | // Add in the Base Offset if present. |
| 3926 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 3927 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3928 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3929 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3930 | else |
| 3931 | Result = V; |
| 3932 | } |
| 3933 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3934 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3935 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3936 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3937 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3938 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3939 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3940 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3941 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3942 | // If we have no uses, recursively delete the value and all dead instructions |
| 3943 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3944 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3945 | // This can cause recursive deletion, which can invalidate our iterator. |
| 3946 | // Use a WeakVH to hold onto it in case this happens. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 3947 | WeakVH IterHandle(&*CurInstIterator); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3948 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3949 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 3950 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3951 | |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 3952 | if (IterHandle != CurInstIterator.getNodePtrUnchecked()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3953 | // If the iterator instruction was recursively deleted, start over at the |
| 3954 | // start of the block. |
| 3955 | CurInstIterator = BB->begin(); |
| 3956 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3957 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 3958 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 3959 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3960 | return true; |
| 3961 | } |
| 3962 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3963 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 3964 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3965 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3966 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3967 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3968 | const TargetRegisterInfo *TRI = |
| 3969 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3970 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 3971 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 3972 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 3973 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3974 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3975 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3976 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 3977 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3978 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 3979 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 3980 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 3981 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3982 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 3983 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 3984 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3985 | } |
| 3986 | |
| 3987 | return MadeChange; |
| 3988 | } |
| 3989 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3990 | /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or |
| 3991 | /// sign extensions. |
| 3992 | static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) { |
| 3993 | assert(!Inst->use_empty() && "Input must have at least one use"); |
| 3994 | const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin()); |
| 3995 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 3996 | Type *ExtTy = FirstUser->getType(); |
| 3997 | for (const User *U : Inst->users()) { |
| 3998 | const Instruction *UI = cast<Instruction>(U); |
| 3999 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4000 | return false; |
| 4001 | Type *CurTy = UI->getType(); |
| 4002 | // Same input and output types: Same instruction after CSE. |
| 4003 | if (CurTy == ExtTy) |
| 4004 | continue; |
| 4005 | |
| 4006 | // If IsSExt is true, we are in this situation: |
| 4007 | // a = Inst |
| 4008 | // b = sext ty1 a to ty2 |
| 4009 | // c = sext ty1 a to ty3 |
| 4010 | // Assuming ty2 is shorter than ty3, this could be turned into: |
| 4011 | // a = Inst |
| 4012 | // b = sext ty1 a to ty2 |
| 4013 | // c = sext ty2 b to ty3 |
| 4014 | // However, the last sext is not free. |
| 4015 | if (IsSExt) |
| 4016 | return false; |
| 4017 | |
| 4018 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4019 | // In that case, we would not account for a different use. |
| 4020 | Type *NarrowTy; |
| 4021 | Type *LargeTy; |
| 4022 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4023 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4024 | NarrowTy = CurTy; |
| 4025 | LargeTy = ExtTy; |
| 4026 | } else { |
| 4027 | NarrowTy = ExtTy; |
| 4028 | LargeTy = CurTy; |
| 4029 | } |
| 4030 | |
| 4031 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4032 | return false; |
| 4033 | } |
| 4034 | // All uses are the same or can be derived from one another for free. |
| 4035 | return true; |
| 4036 | } |
| 4037 | |
| 4038 | /// \brief Try to form ExtLd by promoting \p Exts until they reach a |
| 4039 | /// load instruction. |
| 4040 | /// If an ext(load) can be formed, it is returned via \p LI for the load |
| 4041 | /// and \p Inst for the extension. |
| 4042 | /// Otherwise LI == nullptr and Inst == nullptr. |
| 4043 | /// When some promotion happened, \p TPT contains the proper state to |
| 4044 | /// revert them. |
| 4045 | /// |
| 4046 | /// \return true when promoting was necessary to expose the ext(load) |
| 4047 | /// opportunity, false otherwise. |
| 4048 | /// |
| 4049 | /// Example: |
| 4050 | /// \code |
| 4051 | /// %ld = load i32* %addr |
| 4052 | /// %add = add nuw i32 %ld, 4 |
| 4053 | /// %zext = zext i32 %add to i64 |
| 4054 | /// \endcode |
| 4055 | /// => |
| 4056 | /// \code |
| 4057 | /// %ld = load i32* %addr |
| 4058 | /// %zext = zext i32 %ld to i64 |
| 4059 | /// %add = add nuw i64 %zext, 4 |
| 4060 | /// \encode |
| 4061 | /// Thanks to the promotion, we can match zext(load i32*) to i64. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4062 | bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4063 | LoadInst *&LI, Instruction *&Inst, |
| 4064 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4065 | unsigned CreatedInstsCost = 0) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4066 | // Iterate over all the extensions to see if one form an ext(load). |
| 4067 | for (auto I : Exts) { |
| 4068 | // Check if we directly have ext(load). |
| 4069 | if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) { |
| 4070 | Inst = I; |
| 4071 | // No promotion happened here. |
| 4072 | return false; |
| 4073 | } |
| 4074 | // Check whether or not we want to do any promotion. |
| 4075 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
| 4076 | continue; |
| 4077 | // Get the action to perform the promotion. |
| 4078 | TypePromotionHelper::Action TPH = TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4079 | I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4080 | // Check if we can promote. |
| 4081 | if (!TPH) |
| 4082 | continue; |
| 4083 | // Save the current state. |
| 4084 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4085 | TPT.getRestorationPoint(); |
| 4086 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4087 | unsigned NewCreatedInstsCost = 0; |
| 4088 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4089 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4090 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4091 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4092 | assert(PromotedVal && |
| 4093 | "TypePromotionHelper should have filtered out those cases"); |
| 4094 | |
| 4095 | // We would be able to merge only one extension in a load. |
| 4096 | // Therefore, if we have more than 1 new extension we heuristically |
| 4097 | // cut this search path, because it means we degrade the code quality. |
| 4098 | // With exactly 2, the transformation is neutral, because we will merge |
| 4099 | // one extension but leave one. However, we optimistically keep going, |
| 4100 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4101 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
| 4102 | TotalCreatedInstsCost -= ExtCost; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4103 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4104 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4105 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4106 | // The promotion is not profitable, rollback to the previous state. |
| 4107 | TPT.rollback(LastKnownGood); |
| 4108 | continue; |
| 4109 | } |
| 4110 | // The promotion is profitable. |
| 4111 | // Check if it exposes an ext(load). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4112 | (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4113 | if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4114 | // If we have created a new extension, i.e., now we have two |
| 4115 | // extensions. We must make sure one of them is merged with |
| 4116 | // the load, otherwise we may degrade the code quality. |
| 4117 | (LI->hasOneUse() || hasSameExtUse(LI, *TLI)))) |
| 4118 | // Promotion happened. |
| 4119 | return true; |
| 4120 | // If this does not help to expose an ext(load) then, rollback. |
| 4121 | TPT.rollback(LastKnownGood); |
| 4122 | } |
| 4123 | // None of the extension can form an ext(load). |
| 4124 | LI = nullptr; |
| 4125 | Inst = nullptr; |
| 4126 | return false; |
| 4127 | } |
| 4128 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4129 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4130 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4131 | /// extend into the load. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4132 | /// \p I[in/out] the extension may be modified during the process if some |
| 4133 | /// promotions apply. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4134 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4135 | bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4136 | // Try to promote a chain of computation if it allows to form |
| 4137 | // an extended load. |
| 4138 | TypePromotionTransaction TPT; |
| 4139 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4140 | TPT.getRestorationPoint(); |
| 4141 | SmallVector<Instruction *, 1> Exts; |
| 4142 | Exts.push_back(I); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4143 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4144 | LoadInst *LI = nullptr; |
| 4145 | Instruction *OldExt = I; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4146 | bool HasPromoted = extLdPromotion(TPT, LI, I, Exts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4147 | if (!LI || !I) { |
| 4148 | assert(!HasPromoted && !LI && "If we did not match any load instruction " |
| 4149 | "the code must remain the same"); |
| 4150 | I = OldExt; |
| 4151 | return false; |
| 4152 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4153 | |
| 4154 | // If they're already in the same block, there's nothing to do. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4155 | // Make the cheap checks first if we did not promote. |
| 4156 | // If we promoted, we need to check if it is indeed profitable. |
| 4157 | if (!HasPromoted && LI->getParent() == I->getParent()) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4158 | return false; |
| 4159 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4160 | EVT VT = TLI->getValueType(*DL, I->getType()); |
| 4161 | EVT LoadVT = TLI->getValueType(*DL, LI->getType()); |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4162 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4163 | // If the load has other users and the truncate is not free, this probably |
| 4164 | // isn't worthwhile. |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4165 | if (!LI->hasOneUse() && TLI && |
| 4166 | (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4167 | !TLI->isTruncateFree(I->getType(), LI->getType())) { |
| 4168 | I = OldExt; |
| 4169 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4170 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4171 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4172 | |
| 4173 | // Check whether the target supports casts folded into loads. |
| 4174 | unsigned LType; |
| 4175 | if (isa<ZExtInst>(I)) |
| 4176 | LType = ISD::ZEXTLOAD; |
| 4177 | else { |
| 4178 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 4179 | LType = ISD::SEXTLOAD; |
| 4180 | } |
Ahmed Bougacha | 2b6917b | 2015-01-08 00:51:32 +0000 | [diff] [blame] | 4181 | if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4182 | I = OldExt; |
| 4183 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4184 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4185 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4186 | |
| 4187 | // Move the extend into the same block as the load, so that SelectionDAG |
| 4188 | // can fold it. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4189 | TPT.commit(); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4190 | I->removeFromParent(); |
| 4191 | I->insertAfter(LI); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4192 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4193 | return true; |
| 4194 | } |
| 4195 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4196 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4197 | BasicBlock *DefBB = I->getParent(); |
| 4198 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 4199 | // If the result of a {s|z}ext and its source are both live out, rewrite all |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4200 | // other uses of the source with result of extension. |
| 4201 | Value *Src = I->getOperand(0); |
| 4202 | if (Src->hasOneUse()) |
| 4203 | return false; |
| 4204 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 4205 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 4206 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4207 | return false; |
| 4208 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4209 | // Only safe to perform the optimization if the source is also defined in |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4210 | // this block. |
| 4211 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4212 | return false; |
| 4213 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4214 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4215 | for (User *U : I->users()) { |
| 4216 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4217 | |
| 4218 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4219 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4220 | if (UserBB == DefBB) continue; |
| 4221 | DefIsLiveOut = true; |
| 4222 | break; |
| 4223 | } |
| 4224 | if (!DefIsLiveOut) |
| 4225 | return false; |
| 4226 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 4227 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4228 | for (User *U : Src->users()) { |
| 4229 | Instruction *UI = cast<Instruction>(U); |
| 4230 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4231 | if (UserBB == DefBB) continue; |
| 4232 | // Be conservative. We don't want this xform to end up introducing |
| 4233 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4234 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4235 | return false; |
| 4236 | } |
| 4237 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4238 | // InsertedTruncs - Only insert one trunc in each block once. |
| 4239 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 4240 | |
| 4241 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4242 | for (Use &U : Src->uses()) { |
| 4243 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4244 | |
| 4245 | // Figure out which BB this ext is used in. |
| 4246 | BasicBlock *UserBB = User->getParent(); |
| 4247 | if (UserBB == DefBB) continue; |
| 4248 | |
| 4249 | // Both src and def are live in this block. Rewrite the use. |
| 4250 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 4251 | |
| 4252 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 4253 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4254 | assert(InsertPt != UserBB->end()); |
| 4255 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4256 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4257 | } |
| 4258 | |
| 4259 | // Replace a use of the {s|z}ext source with a use of the result. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4260 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4261 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4262 | MadeChange = true; |
| 4263 | } |
| 4264 | |
| 4265 | return MadeChange; |
| 4266 | } |
| 4267 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 4268 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 4269 | // just after the load if the target can fold this into one extload instruction, |
| 4270 | // with the hope of eliminating some of the other later "and" instructions using |
| 4271 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 4272 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 4273 | // path from the load goes through a phi) are left for isel to potentially |
| 4274 | // remove. |
| 4275 | // |
| 4276 | // For example: |
| 4277 | // |
| 4278 | // b0: |
| 4279 | // x = load i32 |
| 4280 | // ... |
| 4281 | // b1: |
| 4282 | // y = and x, 0xff |
| 4283 | // z = use y |
| 4284 | // |
| 4285 | // becomes: |
| 4286 | // |
| 4287 | // b0: |
| 4288 | // x = load i32 |
| 4289 | // x' = and x, 0xff |
| 4290 | // ... |
| 4291 | // b1: |
| 4292 | // z = use x' |
| 4293 | // |
| 4294 | // whereas: |
| 4295 | // |
| 4296 | // b0: |
| 4297 | // x1 = load i32 |
| 4298 | // ... |
| 4299 | // b1: |
| 4300 | // x2 = load i32 |
| 4301 | // ... |
| 4302 | // b2: |
| 4303 | // x = phi x1, x2 |
| 4304 | // y = and x, 0xff |
| 4305 | // |
| 4306 | // becomes (after a call to optimizeLoadExt for each load): |
| 4307 | // |
| 4308 | // b0: |
| 4309 | // x1 = load i32 |
| 4310 | // x1' = and x1, 0xff |
| 4311 | // ... |
| 4312 | // b1: |
| 4313 | // x2 = load i32 |
| 4314 | // x2' = and x2, 0xff |
| 4315 | // ... |
| 4316 | // b2: |
| 4317 | // x = phi x1', x2' |
| 4318 | // y = and x, 0xff |
| 4319 | // |
| 4320 | |
| 4321 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
| 4322 | |
| 4323 | if (!Load->isSimple() || |
| 4324 | !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy())) |
| 4325 | return false; |
| 4326 | |
| 4327 | // Skip loads we've already transformed or have no reason to transform. |
| 4328 | if (Load->hasOneUse()) { |
| 4329 | User *LoadUser = *Load->user_begin(); |
| 4330 | if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() && |
| 4331 | !dyn_cast<PHINode>(LoadUser)) |
| 4332 | return false; |
| 4333 | } |
| 4334 | |
| 4335 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 4336 | // of the loaded value are needed. |
| 4337 | SmallVector<Instruction *, 8> WorkList; |
| 4338 | SmallPtrSet<Instruction *, 16> Visited; |
| 4339 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 4340 | for (auto *U : Load->users()) |
| 4341 | WorkList.push_back(cast<Instruction>(U)); |
| 4342 | |
| 4343 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 4344 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 4345 | APInt DemandBits(BitWidth, 0); |
| 4346 | APInt WidestAndBits(BitWidth, 0); |
| 4347 | |
| 4348 | while (!WorkList.empty()) { |
| 4349 | Instruction *I = WorkList.back(); |
| 4350 | WorkList.pop_back(); |
| 4351 | |
| 4352 | // Break use-def graph loops. |
| 4353 | if (!Visited.insert(I).second) |
| 4354 | continue; |
| 4355 | |
| 4356 | // For a PHI node, push all of its users. |
| 4357 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 4358 | for (auto *U : Phi->users()) |
| 4359 | WorkList.push_back(cast<Instruction>(U)); |
| 4360 | continue; |
| 4361 | } |
| 4362 | |
| 4363 | switch (I->getOpcode()) { |
| 4364 | case llvm::Instruction::And: { |
| 4365 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4366 | if (!AndC) |
| 4367 | return false; |
| 4368 | APInt AndBits = AndC->getValue(); |
| 4369 | DemandBits |= AndBits; |
| 4370 | // Keep track of the widest and mask we see. |
| 4371 | if (AndBits.ugt(WidestAndBits)) |
| 4372 | WidestAndBits = AndBits; |
| 4373 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 4374 | AndsToMaybeRemove.push_back(I); |
| 4375 | break; |
| 4376 | } |
| 4377 | |
| 4378 | case llvm::Instruction::Shl: { |
| 4379 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4380 | if (!ShlC) |
| 4381 | return false; |
| 4382 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
| 4383 | auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt); |
| 4384 | DemandBits |= ShlDemandBits; |
| 4385 | break; |
| 4386 | } |
| 4387 | |
| 4388 | case llvm::Instruction::Trunc: { |
| 4389 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 4390 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
| 4391 | auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth); |
| 4392 | DemandBits |= TruncBits; |
| 4393 | break; |
| 4394 | } |
| 4395 | |
| 4396 | default: |
| 4397 | return false; |
| 4398 | } |
| 4399 | } |
| 4400 | |
| 4401 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 4402 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 4403 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 4404 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 4405 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 4406 | // followed by an AND. |
| 4407 | // TODO: Look into removing this restriction by fixing backends to either |
| 4408 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 4409 | // a single instruction. |
| 4410 | // |
| 4411 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 4412 | // mask, since these are the only ands that will be removed by isel. |
| 4413 | if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) || |
| 4414 | WidestAndBits != DemandBits) |
| 4415 | return false; |
| 4416 | |
| 4417 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 4418 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 4419 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 4420 | |
| 4421 | // Reject cases that won't be matched as extloads. |
| 4422 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 4423 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 4424 | return false; |
| 4425 | |
| 4426 | IRBuilder<> Builder(Load->getNextNode()); |
| 4427 | auto *NewAnd = dyn_cast<Instruction>( |
| 4428 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
| 4429 | |
| 4430 | // Replace all uses of load with new and (except for the use of load in the |
| 4431 | // new and itself). |
| 4432 | Load->replaceAllUsesWith(NewAnd); |
| 4433 | NewAnd->setOperand(0, Load); |
| 4434 | |
| 4435 | // Remove any and instructions that are now redundant. |
| 4436 | for (auto *And : AndsToMaybeRemove) |
| 4437 | // Check that the and mask is the same as the one we decided to put on the |
| 4438 | // new and. |
| 4439 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 4440 | And->replaceAllUsesWith(NewAnd); |
| 4441 | if (&*CurInstIterator == And) |
| 4442 | CurInstIterator = std::next(And->getIterator()); |
| 4443 | And->eraseFromParent(); |
| 4444 | ++NumAndUses; |
| 4445 | } |
| 4446 | |
| 4447 | ++NumAndsAdded; |
| 4448 | return true; |
| 4449 | } |
| 4450 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4451 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 4452 | /// that is only used once. |
| 4453 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 4454 | auto *I = dyn_cast<Instruction>(V); |
| 4455 | // If it's safe to speculatively execute, then it should not have side |
| 4456 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 4457 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 4458 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4459 | } |
| 4460 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4461 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4462 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
| 4463 | SelectInst *SI) { |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4464 | // FIXME: This should use the same heuristics as IfConversion to determine |
| 4465 | // whether a select is better represented as a branch. This requires that |
| 4466 | // branch probability metadata is preserved for the select, which is not the |
| 4467 | // case currently. |
| 4468 | |
| 4469 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 4470 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 4471 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 4472 | // comparison condition. If the compare has more than one use, there's |
| 4473 | // probably another cmov or setcc around, so it's not worth emitting a branch. |
Sanjay Patel | 5e5f0e9 | 2015-09-28 21:44:46 +0000 | [diff] [blame] | 4474 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4475 | return false; |
| 4476 | |
| 4477 | Value *CmpOp0 = Cmp->getOperand(0); |
| 4478 | Value *CmpOp1 = Cmp->getOperand(1); |
| 4479 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 4480 | // Emit "cmov on compare with a memory operand" as a branch to avoid stalls |
| 4481 | // on a load from memory. But if the load is used more than once, do not |
| 4482 | // change the select to a branch because the load is probably needed |
| 4483 | // regardless of whether the branch is taken or not. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4484 | if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) || |
| 4485 | (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse())) |
| 4486 | return true; |
| 4487 | |
| 4488 | // If either operand of the select is expensive and only needed on one side |
| 4489 | // of the select, we should form a branch. |
| 4490 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 4491 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 4492 | return true; |
| 4493 | |
| 4494 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4495 | } |
| 4496 | |
| 4497 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4498 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 4499 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4500 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4501 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 4502 | |
| 4503 | // Can we convert the 'select' to CF ? |
| 4504 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4505 | return false; |
| 4506 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4507 | TargetLowering::SelectSupportKind SelectKind; |
| 4508 | if (VectorCond) |
| 4509 | SelectKind = TargetLowering::VectorMaskSelect; |
| 4510 | else if (SI->getType()->isVectorTy()) |
| 4511 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 4512 | else |
| 4513 | SelectKind = TargetLowering::ScalarValSelect; |
| 4514 | |
| 4515 | // Do we have efficient codegen support for this kind of 'selects' ? |
| 4516 | if (TLI->isSelectSupported(SelectKind)) { |
| 4517 | // We have efficient codegen support for the select instruction. |
| 4518 | // Check if it is profitable to keep this 'select'. |
| 4519 | if (!TLI->isPredictableSelectExpensive() || |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4520 | !isFormingBranchFromSelectProfitable(TTI, SI)) |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4521 | return false; |
| 4522 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4523 | |
| 4524 | ModifiedDT = true; |
| 4525 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4526 | // Transform a sequence like this: |
| 4527 | // start: |
| 4528 | // %cmp = cmp uge i32 %a, %b |
| 4529 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 4530 | // |
| 4531 | // Into: |
| 4532 | // start: |
| 4533 | // %cmp = cmp uge i32 %a, %b |
| 4534 | // br i1 %cmp, label %select.true, label %select.false |
| 4535 | // select.true: |
| 4536 | // br label %select.end |
| 4537 | // select.false: |
| 4538 | // br label %select.end |
| 4539 | // select.end: |
| 4540 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 4541 | // |
| 4542 | // In addition, we may sink instructions that produce %c or %d from |
| 4543 | // the entry block into the destination(s) of the new branch. |
| 4544 | // If the true or false blocks do not contain a sunken instruction, that |
| 4545 | // block and its branch may be optimized away. In that case, one side of the |
| 4546 | // first branch will point directly to select.end, and the corresponding PHI |
| 4547 | // predecessor block will be the start block. |
| 4548 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4549 | // First, we split the block containing the select into 2 blocks. |
| 4550 | BasicBlock *StartBlock = SI->getParent(); |
| 4551 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4552 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4553 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4554 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4555 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4556 | |
| 4557 | // These are the new basic blocks for the conditional branch. |
| 4558 | // At least one will become an actual new basic block. |
| 4559 | BasicBlock *TrueBlock = nullptr; |
| 4560 | BasicBlock *FalseBlock = nullptr; |
| 4561 | |
| 4562 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 4563 | // them speculatively. |
| 4564 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 4565 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 4566 | EndBlock->getParent(), EndBlock); |
| 4567 | auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 4568 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 4569 | TrueInst->moveBefore(TrueBranch); |
| 4570 | } |
| 4571 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 4572 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 4573 | EndBlock->getParent(), EndBlock); |
| 4574 | auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 4575 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 4576 | FalseInst->moveBefore(FalseBranch); |
| 4577 | } |
| 4578 | |
| 4579 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 4580 | // for a new input value to the PHI. |
| 4581 | if (TrueBlock == FalseBlock) { |
| 4582 | assert(TrueBlock == nullptr && |
| 4583 | "Unexpected basic block transform while optimizing select"); |
| 4584 | |
| 4585 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 4586 | EndBlock->getParent(), EndBlock); |
| 4587 | BranchInst::Create(EndBlock, FalseBlock); |
| 4588 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4589 | |
| 4590 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4591 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 4592 | // of the condition, it means that side of the branch goes to the end block |
| 4593 | // directly and the path originates from the start block from the point of |
| 4594 | // view of the new PHI. |
| 4595 | if (TrueBlock == nullptr) { |
| 4596 | BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI); |
| 4597 | TrueBlock = StartBlock; |
| 4598 | } else if (FalseBlock == nullptr) { |
| 4599 | BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI); |
| 4600 | FalseBlock = StartBlock; |
| 4601 | } else { |
| 4602 | BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI); |
| 4603 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4604 | |
| 4605 | // The select itself is replaced with a PHI Node. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4606 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4607 | PN->takeName(SI); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4608 | PN->addIncoming(SI->getTrueValue(), TrueBlock); |
| 4609 | PN->addIncoming(SI->getFalseValue(), FalseBlock); |
| 4610 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4611 | SI->replaceAllUsesWith(PN); |
| 4612 | SI->eraseFromParent(); |
| 4613 | |
| 4614 | // Instruct OptimizeBlock to skip to the next block. |
| 4615 | CurInstIterator = StartBlock->end(); |
| 4616 | ++NumSelectsExpanded; |
| 4617 | return true; |
| 4618 | } |
| 4619 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 4620 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4621 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 4622 | int SplatElem = -1; |
| 4623 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 4624 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 4625 | return false; |
| 4626 | SplatElem = Mask[i]; |
| 4627 | } |
| 4628 | |
| 4629 | return true; |
| 4630 | } |
| 4631 | |
| 4632 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 4633 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 4634 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 4635 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4636 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4637 | BasicBlock *DefBB = SVI->getParent(); |
| 4638 | |
| 4639 | // Only do this xform if variable vector shifts are particularly expensive. |
| 4640 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 4641 | return false; |
| 4642 | |
| 4643 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 4644 | // constant splat. |
| 4645 | if (!isBroadcastShuffle(SVI)) |
| 4646 | return false; |
| 4647 | |
| 4648 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 4649 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 4650 | |
| 4651 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4652 | for (User *U : SVI->users()) { |
| 4653 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4654 | |
| 4655 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4656 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4657 | if (UserBB == DefBB) continue; |
| 4658 | |
| 4659 | // For now only apply this when the splat is used by a shift instruction. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4660 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4661 | |
| 4662 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 4663 | // already have a copy. |
| 4664 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 4665 | |
| 4666 | if (!InsertedShuffle) { |
| 4667 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4668 | assert(InsertPt != UserBB->end()); |
| 4669 | InsertedShuffle = |
| 4670 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 4671 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4672 | } |
| 4673 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4674 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4675 | MadeChange = true; |
| 4676 | } |
| 4677 | |
| 4678 | // If we removed all uses, nuke the shuffle. |
| 4679 | if (SVI->use_empty()) { |
| 4680 | SVI->eraseFromParent(); |
| 4681 | MadeChange = true; |
| 4682 | } |
| 4683 | |
| 4684 | return MadeChange; |
| 4685 | } |
| 4686 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 4687 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 4688 | if (!TLI || !DL) |
| 4689 | return false; |
| 4690 | |
| 4691 | Value *Cond = SI->getCondition(); |
| 4692 | Type *OldType = Cond->getType(); |
| 4693 | LLVMContext &Context = Cond->getContext(); |
| 4694 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 4695 | unsigned RegWidth = RegType.getSizeInBits(); |
| 4696 | |
| 4697 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 4698 | return false; |
| 4699 | |
| 4700 | // If the register width is greater than the type width, expand the condition |
| 4701 | // of the switch instruction and each case constant to the width of the |
| 4702 | // register. By widening the type of the switch condition, subsequent |
| 4703 | // comparisons (for case comparisons) will not need to be extended to the |
| 4704 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 4705 | // where N is the number of cases in the switch. |
| 4706 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 4707 | |
| 4708 | // Zero-extend the switch condition and case constants unless the switch |
| 4709 | // condition is a function argument that is already being sign-extended. |
| 4710 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 4711 | // everything instead. |
| 4712 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 4713 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 4714 | if (Arg->hasSExtAttr()) |
| 4715 | ExtType = Instruction::SExt; |
| 4716 | |
| 4717 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 4718 | ExtInst->insertBefore(SI); |
| 4719 | SI->setCondition(ExtInst); |
| 4720 | for (SwitchInst::CaseIt Case : SI->cases()) { |
| 4721 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 4722 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 4723 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 4724 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 4725 | } |
| 4726 | |
| 4727 | return true; |
| 4728 | } |
| 4729 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4730 | namespace { |
| 4731 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 4732 | /// This class is used to move downward extractelement transition. |
| 4733 | /// E.g., |
| 4734 | /// a = vector_op <2 x i32> |
| 4735 | /// b = extractelement <2 x i32> a, i32 0 |
| 4736 | /// c = scalar_op b |
| 4737 | /// store c |
| 4738 | /// |
| 4739 | /// => |
| 4740 | /// a = vector_op <2 x i32> |
| 4741 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 4742 | /// * d = extractelement <2 x i32> c, i32 0 |
| 4743 | /// * store d |
| 4744 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 4745 | /// transition. |
| 4746 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4747 | /// DataLayout associated with the current module. |
| 4748 | const DataLayout &DL; |
| 4749 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4750 | /// Used to perform some checks on the legality of vector operations. |
| 4751 | const TargetLowering &TLI; |
| 4752 | |
| 4753 | /// Used to estimated the cost of the promoted chain. |
| 4754 | const TargetTransformInfo &TTI; |
| 4755 | |
| 4756 | /// The transition being moved downwards. |
| 4757 | Instruction *Transition; |
| 4758 | /// The sequence of instructions to be promoted. |
| 4759 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 4760 | /// Cost of combining a store and an extract. |
| 4761 | unsigned StoreExtractCombineCost; |
| 4762 | /// Instruction that will be combined with the transition. |
| 4763 | Instruction *CombineInst; |
| 4764 | |
| 4765 | /// \brief The instruction that represents the current end of the transition. |
| 4766 | /// Since we are faking the promotion until we reach the end of the chain |
| 4767 | /// of computation, we need a way to get the current end of the transition. |
| 4768 | Instruction *getEndOfTransition() const { |
| 4769 | if (InstsToBePromoted.empty()) |
| 4770 | return Transition; |
| 4771 | return InstsToBePromoted.back(); |
| 4772 | } |
| 4773 | |
| 4774 | /// \brief Return the index of the original value in the transition. |
| 4775 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 4776 | /// c, is at index 0. |
| 4777 | unsigned getTransitionOriginalValueIdx() const { |
| 4778 | assert(isa<ExtractElementInst>(Transition) && |
| 4779 | "Other kind of transitions are not supported yet"); |
| 4780 | return 0; |
| 4781 | } |
| 4782 | |
| 4783 | /// \brief Return the index of the index in the transition. |
| 4784 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 4785 | /// is at index 1. |
| 4786 | unsigned getTransitionIdx() const { |
| 4787 | assert(isa<ExtractElementInst>(Transition) && |
| 4788 | "Other kind of transitions are not supported yet"); |
| 4789 | return 1; |
| 4790 | } |
| 4791 | |
| 4792 | /// \brief Get the type of the transition. |
| 4793 | /// This is the type of the original value. |
| 4794 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 4795 | /// transition is <2 x i32>. |
| 4796 | Type *getTransitionType() const { |
| 4797 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 4798 | } |
| 4799 | |
| 4800 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 4801 | /// I.e., we have the following sequence: |
| 4802 | /// Def = Transition <ty1> a to <ty2> |
| 4803 | /// b = ToBePromoted <ty2> Def, ... |
| 4804 | /// => |
| 4805 | /// b = ToBePromoted <ty1> a, ... |
| 4806 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 4807 | void promoteImpl(Instruction *ToBePromoted); |
| 4808 | |
| 4809 | /// \brief Check whether or not it is profitable to promote all the |
| 4810 | /// instructions enqueued to be promoted. |
| 4811 | bool isProfitableToPromote() { |
| 4812 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 4813 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 4814 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 4815 | : -1; |
| 4816 | Type *PromotedType = getTransitionType(); |
| 4817 | |
| 4818 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 4819 | unsigned AS = ST->getPointerAddressSpace(); |
| 4820 | unsigned Align = ST->getAlignment(); |
| 4821 | // Check if this store is supported. |
| 4822 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4823 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 4824 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4825 | // If this is not supported, there is no way we can combine |
| 4826 | // the extract with the store. |
| 4827 | return false; |
| 4828 | } |
| 4829 | |
| 4830 | // The scalar chain of computation has to pay for the transition |
| 4831 | // scalar to vector. |
| 4832 | // The vector chain has to account for the combining cost. |
| 4833 | uint64_t ScalarCost = |
| 4834 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 4835 | uint64_t VectorCost = StoreExtractCombineCost; |
| 4836 | for (const auto &Inst : InstsToBePromoted) { |
| 4837 | // Compute the cost. |
| 4838 | // By construction, all instructions being promoted are arithmetic ones. |
| 4839 | // Moreover, one argument is a constant that can be viewed as a splat |
| 4840 | // constant. |
| 4841 | Value *Arg0 = Inst->getOperand(0); |
| 4842 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 4843 | isa<ConstantFP>(Arg0); |
| 4844 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 4845 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4846 | : TargetTransformInfo::OK_AnyValue; |
| 4847 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 4848 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4849 | : TargetTransformInfo::OK_AnyValue; |
| 4850 | ScalarCost += TTI.getArithmeticInstrCost( |
| 4851 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 4852 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 4853 | Arg0OVK, Arg1OVK); |
| 4854 | } |
| 4855 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 4856 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 4857 | return ScalarCost > VectorCost; |
| 4858 | } |
| 4859 | |
| 4860 | /// \brief Generate a constant vector with \p Val with the same |
| 4861 | /// number of elements as the transition. |
| 4862 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 4863 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4864 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 4865 | /// otherwise we generate a vector with as many undef as possible: |
| 4866 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 4867 | /// used at the index of the extract. |
| 4868 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 4869 | unsigned ExtractIdx = UINT_MAX; |
| 4870 | if (!UseSplat) { |
| 4871 | // If we cannot determine where the constant must be, we have to |
| 4872 | // use a splat constant. |
| 4873 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 4874 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 4875 | ExtractIdx = CstVal->getSExtValue(); |
| 4876 | else |
| 4877 | UseSplat = true; |
| 4878 | } |
| 4879 | |
| 4880 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 4881 | if (UseSplat) |
| 4882 | return ConstantVector::getSplat(End, Val); |
| 4883 | |
| 4884 | SmallVector<Constant *, 4> ConstVec; |
| 4885 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 4886 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 4887 | if (Idx == ExtractIdx) |
| 4888 | ConstVec.push_back(Val); |
| 4889 | else |
| 4890 | ConstVec.push_back(UndefVal); |
| 4891 | } |
| 4892 | return ConstantVector::get(ConstVec); |
| 4893 | } |
| 4894 | |
| 4895 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 4896 | /// in \p Use can trigger undefined behavior. |
| 4897 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 4898 | unsigned OperandIdx) { |
| 4899 | // This is not safe to introduce undef when the operand is on |
| 4900 | // the right hand side of a division-like instruction. |
| 4901 | if (OperandIdx != 1) |
| 4902 | return false; |
| 4903 | switch (Use->getOpcode()) { |
| 4904 | default: |
| 4905 | return false; |
| 4906 | case Instruction::SDiv: |
| 4907 | case Instruction::UDiv: |
| 4908 | case Instruction::SRem: |
| 4909 | case Instruction::URem: |
| 4910 | return true; |
| 4911 | case Instruction::FDiv: |
| 4912 | case Instruction::FRem: |
| 4913 | return !Use->hasNoNaNs(); |
| 4914 | } |
| 4915 | llvm_unreachable(nullptr); |
| 4916 | } |
| 4917 | |
| 4918 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4919 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 4920 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 4921 | unsigned CombineCost) |
| 4922 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4923 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 4924 | assert(Transition && "Do not know how to promote null"); |
| 4925 | } |
| 4926 | |
| 4927 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 4928 | bool canPromote(const Instruction *ToBePromoted) const { |
| 4929 | // We could support CastInst too. |
| 4930 | return isa<BinaryOperator>(ToBePromoted); |
| 4931 | } |
| 4932 | |
| 4933 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 4934 | /// by moving downward the transition through. |
| 4935 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 4936 | // Promote only if all the operands can be statically expanded. |
| 4937 | // Indeed, we do not want to introduce any new kind of transitions. |
| 4938 | for (const Use &U : ToBePromoted->operands()) { |
| 4939 | const Value *Val = U.get(); |
| 4940 | if (Val == getEndOfTransition()) { |
| 4941 | // If the use is a division and the transition is on the rhs, |
| 4942 | // we cannot promote the operation, otherwise we may create a |
| 4943 | // division by zero. |
| 4944 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 4945 | return false; |
| 4946 | continue; |
| 4947 | } |
| 4948 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 4949 | !isa<ConstantFP>(Val)) |
| 4950 | return false; |
| 4951 | } |
| 4952 | // Check that the resulting operation is legal. |
| 4953 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 4954 | if (!ISDOpcode) |
| 4955 | return false; |
| 4956 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 4957 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4958 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4959 | } |
| 4960 | |
| 4961 | /// \brief Check whether or not \p Use can be combined |
| 4962 | /// with the transition. |
| 4963 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 4964 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 4965 | |
| 4966 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 4967 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 4968 | InstsToBePromoted.push_back(ToBePromoted); |
| 4969 | } |
| 4970 | |
| 4971 | /// \brief Set the instruction that will be combined with the transition. |
| 4972 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 4973 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 4974 | CombineInst = ToBeCombined; |
| 4975 | } |
| 4976 | |
| 4977 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 4978 | /// is profitable. |
| 4979 | /// \return True if the promotion happened, false otherwise. |
| 4980 | bool promote() { |
| 4981 | // Check if there is something to promote. |
| 4982 | // Right now, if we do not have anything to combine with, |
| 4983 | // we assume the promotion is not profitable. |
| 4984 | if (InstsToBePromoted.empty() || !CombineInst) |
| 4985 | return false; |
| 4986 | |
| 4987 | // Check cost. |
| 4988 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 4989 | return false; |
| 4990 | |
| 4991 | // Promote. |
| 4992 | for (auto &ToBePromoted : InstsToBePromoted) |
| 4993 | promoteImpl(ToBePromoted); |
| 4994 | InstsToBePromoted.clear(); |
| 4995 | return true; |
| 4996 | } |
| 4997 | }; |
| 4998 | } // End of anonymous namespace. |
| 4999 | |
| 5000 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 5001 | // At this point, we know that all the operands of ToBePromoted but Def |
| 5002 | // can be statically promoted. |
| 5003 | // For Def, we need to use its parameter in ToBePromoted: |
| 5004 | // b = ToBePromoted ty1 a |
| 5005 | // Def = Transition ty1 b to ty2 |
| 5006 | // Move the transition down. |
| 5007 | // 1. Replace all uses of the promoted operation by the transition. |
| 5008 | // = ... b => = ... Def. |
| 5009 | assert(ToBePromoted->getType() == Transition->getType() && |
| 5010 | "The type of the result of the transition does not match " |
| 5011 | "the final type"); |
| 5012 | ToBePromoted->replaceAllUsesWith(Transition); |
| 5013 | // 2. Update the type of the uses. |
| 5014 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 5015 | Type *TransitionTy = getTransitionType(); |
| 5016 | ToBePromoted->mutateType(TransitionTy); |
| 5017 | // 3. Update all the operands of the promoted operation with promoted |
| 5018 | // operands. |
| 5019 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 5020 | for (Use &U : ToBePromoted->operands()) { |
| 5021 | Value *Val = U.get(); |
| 5022 | Value *NewVal = nullptr; |
| 5023 | if (Val == Transition) |
| 5024 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5025 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 5026 | isa<ConstantFP>(Val)) { |
| 5027 | // Use a splat constant if it is not safe to use undef. |
| 5028 | NewVal = getConstantVector( |
| 5029 | cast<Constant>(Val), |
| 5030 | isa<UndefValue>(Val) || |
| 5031 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 5032 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 5033 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 5034 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5035 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 5036 | } |
| 5037 | Transition->removeFromParent(); |
| 5038 | Transition->insertAfter(ToBePromoted); |
| 5039 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 5040 | } |
| 5041 | |
| 5042 | /// Some targets can do store(extractelement) with one instruction. |
| 5043 | /// Try to push the extractelement towards the stores when the target |
| 5044 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5045 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5046 | unsigned CombineCost = UINT_MAX; |
| 5047 | if (DisableStoreExtract || !TLI || |
| 5048 | (!StressStoreExtract && |
| 5049 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 5050 | Inst->getOperand(1), CombineCost))) |
| 5051 | return false; |
| 5052 | |
| 5053 | // At this point we know that Inst is a vector to scalar transition. |
| 5054 | // Try to move it down the def-use chain, until: |
| 5055 | // - We can combine the transition with its single use |
| 5056 | // => we got rid of the transition. |
| 5057 | // - We escape the current basic block |
| 5058 | // => we would need to check that we are moving it at a cheaper place and |
| 5059 | // we do not do that for now. |
| 5060 | BasicBlock *Parent = Inst->getParent(); |
| 5061 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5062 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5063 | // If the transition has more than one use, assume this is not going to be |
| 5064 | // beneficial. |
| 5065 | while (Inst->hasOneUse()) { |
| 5066 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 5067 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 5068 | |
| 5069 | if (ToBePromoted->getParent() != Parent) { |
| 5070 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 5071 | << ToBePromoted->getParent()->getName() |
| 5072 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 5073 | return false; |
| 5074 | } |
| 5075 | |
| 5076 | if (VPH.canCombine(ToBePromoted)) { |
| 5077 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 5078 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 5079 | VPH.recordCombineInstruction(ToBePromoted); |
| 5080 | bool Changed = VPH.promote(); |
| 5081 | NumStoreExtractExposed += Changed; |
| 5082 | return Changed; |
| 5083 | } |
| 5084 | |
| 5085 | DEBUG(dbgs() << "Try promoting.\n"); |
| 5086 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 5087 | return false; |
| 5088 | |
| 5089 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 5090 | |
| 5091 | VPH.enqueueForPromotion(ToBePromoted); |
| 5092 | Inst = ToBePromoted; |
| 5093 | } |
| 5094 | return false; |
| 5095 | } |
| 5096 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5097 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5098 | // Bail out if we inserted the instruction to prevent optimizations from |
| 5099 | // stepping on each other's toes. |
| 5100 | if (InsertedInsts.count(I)) |
| 5101 | return false; |
| 5102 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5103 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 5104 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 5105 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 5106 | // trivial PHI, go ahead and zap it here. |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 5107 | if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5108 | P->replaceAllUsesWith(V); |
| 5109 | P->eraseFromParent(); |
| 5110 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5111 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5112 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5113 | return false; |
| 5114 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5115 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5116 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5117 | // If the source of the cast is a constant, then this should have |
| 5118 | // already been constant folded. The only reason NOT to constant fold |
| 5119 | // it is if something (e.g. LSR) was careful to place the constant |
| 5120 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 5121 | // the address of globals out of a loop). If this is the case, we don't |
| 5122 | // want to forward-subst the cast. |
| 5123 | if (isa<Constant>(CI->getOperand(0))) |
| 5124 | return false; |
| 5125 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5126 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5127 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5128 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5129 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5130 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 5131 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5132 | if (TLI && |
| 5133 | TLI->getTypeAction(CI->getContext(), |
| 5134 | TLI->getValueType(*DL, CI->getType())) == |
| 5135 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5136 | return SinkCast(CI); |
| 5137 | } else { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5138 | bool MadeChange = moveExtToFormExtLoad(I); |
| 5139 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5140 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5141 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5142 | return false; |
| 5143 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5144 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5145 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 5146 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
| 5147 | return OptimizeCmpExpression(CI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5148 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5149 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5150 | stripInvariantGroupMetadata(*LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5151 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5152 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5153 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5154 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 5155 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5156 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 5157 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5158 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5159 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5160 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5161 | stripInvariantGroupMetadata(*SI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5162 | if (TLI) { |
| 5163 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5164 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5165 | SI->getOperand(0)->getType(), AS); |
| 5166 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5167 | return false; |
| 5168 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5169 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5170 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 5171 | |
| 5172 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 5173 | BinOp->getOpcode() == Instruction::LShr)) { |
| 5174 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 5175 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5176 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5177 | |
| 5178 | return false; |
| 5179 | } |
| 5180 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5181 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5182 | if (GEPI->hasAllZeroIndices()) { |
| 5183 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 5184 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 5185 | GEPI->getName(), GEPI); |
| 5186 | GEPI->replaceAllUsesWith(NC); |
| 5187 | GEPI->eraseFromParent(); |
| 5188 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5189 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5190 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5191 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5192 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5193 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5194 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5195 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5196 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5197 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5198 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5199 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5200 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5201 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5202 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5203 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5204 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 5205 | return optimizeSwitchInst(Switch); |
| 5206 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5207 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5208 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5209 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5210 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5211 | } |
| 5212 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5213 | // In this pass we look for GEP and cast instructions that are used |
| 5214 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 5215 | // selection. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5216 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 5217 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 5218 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 5219 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 5220 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5221 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5222 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5223 | if (ModifiedDT) |
| 5224 | return true; |
| 5225 | } |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5226 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 5227 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5228 | return MadeChange; |
| 5229 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5230 | |
| 5231 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5232 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5233 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5234 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5235 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5236 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 5237 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5238 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5239 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5240 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 5241 | // Leave dbg.values that refer to an alloca alone. These |
| 5242 | // instrinsics describe the address of a variable (= the alloca) |
| 5243 | // being taken. They should not be moved next to the alloca |
| 5244 | // (and to the beginning of the scope), but rather stay close to |
| 5245 | // where said address is used. |
| 5246 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5247 | PrevNonDbgInst = Insn; |
| 5248 | continue; |
| 5249 | } |
| 5250 | |
| 5251 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 5252 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 5253 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 5254 | // after it. |
| 5255 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 5256 | continue; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5257 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 5258 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 5259 | if (isa<PHINode>(VI)) |
| 5260 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 5261 | else |
| 5262 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5263 | MadeChange = true; |
| 5264 | ++NumDbgValueMoved; |
| 5265 | } |
| 5266 | } |
| 5267 | } |
| 5268 | return MadeChange; |
| 5269 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5270 | |
| 5271 | // If there is a sequence that branches based on comparing a single bit |
| 5272 | // against zero that can be combined into a single instruction, and the |
| 5273 | // target supports folding these into a single instruction, sink the |
| 5274 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 5275 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 5276 | // searched for. |
| 5277 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 5278 | if (!EnableAndCmpSinking) |
| 5279 | return false; |
| 5280 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 5281 | return false; |
| 5282 | bool MadeChange = false; |
| 5283 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5284 | BasicBlock *BB = &*I++; |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5285 | |
| 5286 | // Does this BB end with the following? |
| 5287 | // %andVal = and %val, #single-bit-set |
| 5288 | // %icmpVal = icmp %andResult, 0 |
| 5289 | // br i1 %cmpVal label %dest1, label %dest2" |
| 5290 | BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator()); |
| 5291 | if (!Brcc || !Brcc->isConditional()) |
| 5292 | continue; |
| 5293 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
| 5294 | if (!Cmp || Cmp->getParent() != BB) |
| 5295 | continue; |
| 5296 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 5297 | if (!Zero || !Zero->isZero()) |
| 5298 | continue; |
| 5299 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
| 5300 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB) |
| 5301 | continue; |
| 5302 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 5303 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 5304 | continue; |
| 5305 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump()); |
| 5306 | |
| 5307 | // Push the "and; icmp" for any users that are conditional branches. |
| 5308 | // Since there can only be one branch use per BB, we don't need to keep |
| 5309 | // track of which BBs we insert into. |
| 5310 | for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end(); |
| 5311 | UI != E; ) { |
| 5312 | Use &TheUse = *UI; |
| 5313 | // Find brcc use. |
| 5314 | BranchInst *BrccUser = dyn_cast<BranchInst>(*UI); |
| 5315 | ++UI; |
| 5316 | if (!BrccUser || !BrccUser->isConditional()) |
| 5317 | continue; |
| 5318 | BasicBlock *UserBB = BrccUser->getParent(); |
| 5319 | if (UserBB == BB) continue; |
| 5320 | DEBUG(dbgs() << "found Brcc use\n"); |
| 5321 | |
| 5322 | // Sink the "and; icmp" to use. |
| 5323 | MadeChange = true; |
| 5324 | BinaryOperator *NewAnd = |
| 5325 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 5326 | BrccUser); |
| 5327 | CmpInst *NewCmp = |
| 5328 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 5329 | "", BrccUser); |
| 5330 | TheUse = NewCmp; |
| 5331 | ++NumAndCmpsMoved; |
| 5332 | DEBUG(BrccUser->getParent()->dump()); |
| 5333 | } |
| 5334 | } |
| 5335 | return MadeChange; |
| 5336 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5337 | |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5338 | /// \brief Retrieve the probabilities of a conditional branch. Returns true on |
| 5339 | /// success, or returns false if no or invalid metadata was found. |
| 5340 | static bool extractBranchMetadata(BranchInst *BI, |
| 5341 | uint64_t &ProbTrue, uint64_t &ProbFalse) { |
| 5342 | assert(BI->isConditional() && |
| 5343 | "Looking for probabilities on unconditional branch?"); |
| 5344 | auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof); |
| 5345 | if (!ProfileData || ProfileData->getNumOperands() != 3) |
| 5346 | return false; |
| 5347 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 5348 | const auto *CITrue = |
| 5349 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)); |
| 5350 | const auto *CIFalse = |
| 5351 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2)); |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5352 | if (!CITrue || !CIFalse) |
| 5353 | return false; |
| 5354 | |
| 5355 | ProbTrue = CITrue->getValue().getZExtValue(); |
| 5356 | ProbFalse = CIFalse->getValue().getZExtValue(); |
| 5357 | |
| 5358 | return true; |
| 5359 | } |
| 5360 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5361 | /// \brief Scale down both weights to fit into uint32_t. |
| 5362 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 5363 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 5364 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 5365 | NewTrue = NewTrue / Scale; |
| 5366 | NewFalse = NewFalse / Scale; |
| 5367 | } |
| 5368 | |
| 5369 | /// \brief Some targets prefer to split a conditional branch like: |
| 5370 | /// \code |
| 5371 | /// %0 = icmp ne i32 %a, 0 |
| 5372 | /// %1 = icmp ne i32 %b, 0 |
| 5373 | /// %or.cond = or i1 %0, %1 |
| 5374 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 5375 | /// \endcode |
| 5376 | /// into multiple branch instructions like: |
| 5377 | /// \code |
| 5378 | /// bb1: |
| 5379 | /// %0 = icmp ne i32 %a, 0 |
| 5380 | /// br i1 %0, label %TrueBB, label %bb2 |
| 5381 | /// bb2: |
| 5382 | /// %1 = icmp ne i32 %b, 0 |
| 5383 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 5384 | /// \endcode |
| 5385 | /// This usually allows instruction selection to do even further optimizations |
| 5386 | /// and combine the compare with the branch instruction. Currently this is |
| 5387 | /// applied for targets which have "cheap" jump instructions. |
| 5388 | /// |
| 5389 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 5390 | /// |
| 5391 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 5392 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5393 | return false; |
| 5394 | |
| 5395 | bool MadeChange = false; |
| 5396 | for (auto &BB : F) { |
| 5397 | // Does this BB end with the following? |
| 5398 | // %cond1 = icmp|fcmp|binary instruction ... |
| 5399 | // %cond2 = icmp|fcmp|binary instruction ... |
| 5400 | // %cond.or = or|and i1 %cond1, cond2 |
| 5401 | // br i1 %cond.or label %dest1, label %dest2" |
| 5402 | BinaryOperator *LogicOp; |
| 5403 | BasicBlock *TBB, *FBB; |
| 5404 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 5405 | continue; |
| 5406 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 5407 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 5408 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 5409 | continue; |
| 5410 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5411 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5412 | Value *Cond1, *Cond2; |
| 5413 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 5414 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5415 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5416 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 5417 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5418 | Opc = Instruction::Or; |
| 5419 | else |
| 5420 | continue; |
| 5421 | |
| 5422 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 5423 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 5424 | continue; |
| 5425 | |
| 5426 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 5427 | |
| 5428 | // Create a new BB. |
| 5429 | auto *InsertBefore = std::next(Function::iterator(BB)) |
| 5430 | .getNodePtrUnchecked(); |
| 5431 | auto TmpBB = BasicBlock::Create(BB.getContext(), |
| 5432 | BB.getName() + ".cond.split", |
| 5433 | BB.getParent(), InsertBefore); |
| 5434 | |
| 5435 | // Update original basic block by using the first condition directly by the |
| 5436 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5437 | Br1->setCondition(Cond1); |
| 5438 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5439 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5440 | // Depending on the conditon we have to either replace the true or the false |
| 5441 | // successor of the original branch instruction. |
| 5442 | if (Opc == Instruction::And) |
| 5443 | Br1->setSuccessor(0, TmpBB); |
| 5444 | else |
| 5445 | Br1->setSuccessor(1, TmpBB); |
| 5446 | |
| 5447 | // Fill in the new basic block. |
| 5448 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5449 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 5450 | I->removeFromParent(); |
| 5451 | I->insertBefore(Br2); |
| 5452 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5453 | |
| 5454 | // Update PHI nodes in both successors. The original BB needs to be |
| 5455 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 5456 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 5457 | // incoming edge to the PHI nodes, because both branch instructions target |
| 5458 | // now the same successor. Depending on the original branch condition |
| 5459 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
| 5460 | // we perfrom the correct update for the PHI nodes. |
| 5461 | // This doesn't change the successor order of the just created branch |
| 5462 | // instruction (or any other instruction). |
| 5463 | if (Opc == Instruction::Or) |
| 5464 | std::swap(TBB, FBB); |
| 5465 | |
| 5466 | // Replace the old BB with the new BB. |
| 5467 | for (auto &I : *TBB) { |
| 5468 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5469 | if (!PN) |
| 5470 | break; |
| 5471 | int i; |
| 5472 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 5473 | PN->setIncomingBlock(i, TmpBB); |
| 5474 | } |
| 5475 | |
| 5476 | // Add another incoming edge form the new BB. |
| 5477 | for (auto &I : *FBB) { |
| 5478 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5479 | if (!PN) |
| 5480 | break; |
| 5481 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 5482 | PN->addIncoming(Val, TmpBB); |
| 5483 | } |
| 5484 | |
| 5485 | // Update the branch weights (from SelectionDAGBuilder:: |
| 5486 | // FindMergedConditions). |
| 5487 | if (Opc == Instruction::Or) { |
| 5488 | // Codegen X | Y as: |
| 5489 | // BB1: |
| 5490 | // jmp_if_X TBB |
| 5491 | // jmp TmpBB |
| 5492 | // TmpBB: |
| 5493 | // jmp_if_Y TBB |
| 5494 | // jmp FBB |
| 5495 | // |
| 5496 | |
| 5497 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 5498 | // The requirement is that |
| 5499 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 5500 | // = TrueProb for orignal BB. |
| 5501 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5502 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 5503 | // assumes that |
| 5504 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 5505 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 5506 | // TmpBB, but the math is more complicated. |
| 5507 | uint64_t TrueWeight, FalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5508 | if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5509 | uint64_t NewTrueWeight = TrueWeight; |
| 5510 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 5511 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5512 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5513 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5514 | |
| 5515 | NewTrueWeight = TrueWeight; |
| 5516 | NewFalseWeight = 2 * FalseWeight; |
| 5517 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5518 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5519 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5520 | } |
| 5521 | } else { |
| 5522 | // Codegen X & Y as: |
| 5523 | // BB1: |
| 5524 | // jmp_if_X TmpBB |
| 5525 | // jmp FBB |
| 5526 | // TmpBB: |
| 5527 | // jmp_if_Y TBB |
| 5528 | // jmp FBB |
| 5529 | // |
| 5530 | // This requires creation of TmpBB after CurBB. |
| 5531 | |
| 5532 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 5533 | // The requirement is that |
| 5534 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 5535 | // = FalseProb for orignal BB. |
| 5536 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5537 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 5538 | // assumes that |
| 5539 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 5540 | uint64_t TrueWeight, FalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5541 | if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5542 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 5543 | uint64_t NewFalseWeight = FalseWeight; |
| 5544 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5545 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5546 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5547 | |
| 5548 | NewTrueWeight = 2 * TrueWeight; |
| 5549 | NewFalseWeight = FalseWeight; |
| 5550 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5551 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5552 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5553 | } |
| 5554 | } |
| 5555 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5556 | // Note: No point in getting fancy here, since the DT info is never |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 5557 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5558 | ModifiedDT = true; |
| 5559 | |
| 5560 | MadeChange = true; |
| 5561 | |
| 5562 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 5563 | TmpBB->dump()); |
| 5564 | } |
| 5565 | return MadeChange; |
| 5566 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5567 | |
| 5568 | void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) { |
Piotr Padlewski | ea09288 | 2015-09-17 20:25:07 +0000 | [diff] [blame] | 5569 | if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group)) |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5570 | I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID()); |
| 5571 | } |