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" |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 20 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 21 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/InstructionSimplify.h" |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/LoopInfo.h" |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/TargetTransformInfo.h" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/ValueTracking.h" |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/MemoryBuiltins.h" |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 29 | #include "llvm/CodeGen/Analysis.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 30 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Constants.h" |
| 32 | #include "llvm/IR/DataLayout.h" |
| 33 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 34 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 35 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 36 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 37 | #include "llvm/IR/IRBuilder.h" |
| 38 | #include "llvm/IR/InlineAsm.h" |
| 39 | #include "llvm/IR/Instructions.h" |
| 40 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 41 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 42 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 43 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 44 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 45 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 46 | #include "llvm/Pass.h" |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 47 | #include "llvm/Support/BranchProbability.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 48 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 49 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 50 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 51 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 52 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 53 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 54 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 55 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 56 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 57 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 58 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 59 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 60 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 61 | #define DEBUG_TYPE "codegenprepare" |
| 62 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 63 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 64 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 65 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 66 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 67 | "sunken Cmps"); |
| 68 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 69 | "of sunken Casts"); |
| 70 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 71 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 72 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 73 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 74 | STATISTIC(NumAndsAdded, |
| 75 | "Number of and mask instructions added to form ext loads"); |
| 76 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 77 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 78 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 79 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 80 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 81 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 82 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 83 | static cl::opt<bool> DisableBranchOpts( |
| 84 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 85 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 86 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 87 | static cl::opt<bool> |
| 88 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 89 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 90 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 91 | static cl::opt<bool> DisableSelectToBranch( |
| 92 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 93 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 94 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 95 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 96 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 97 | cl::desc("Address sinking in CGP using GEPs.")); |
| 98 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 99 | static cl::opt<bool> EnableAndCmpSinking( |
| 100 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 101 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 102 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 103 | static cl::opt<bool> DisableStoreExtract( |
| 104 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 105 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 106 | |
| 107 | static cl::opt<bool> StressStoreExtract( |
| 108 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 109 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 110 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 111 | static cl::opt<bool> DisableExtLdPromotion( |
| 112 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 113 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 114 | "CodeGenPrepare")); |
| 115 | |
| 116 | static cl::opt<bool> StressExtLdPromotion( |
| 117 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 118 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 119 | "optimization in CodeGenPrepare")); |
| 120 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 121 | static cl::opt<bool> DisablePreheaderProtect( |
| 122 | "disable-preheader-prot", cl::Hidden, cl::init(false), |
| 123 | cl::desc("Disable protection against removing loop preheaders")); |
| 124 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 125 | static cl::opt<bool> ProfileGuidedSectionPrefix( |
| 126 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), |
| 127 | cl::desc("Use profile info to add section prefix for hot/cold functions")); |
| 128 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 129 | static cl::opt<unsigned> FreqRatioToSkipMerge( |
| 130 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), |
| 131 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " |
| 132 | "(frequency of destination block) is greater than this ratio")); |
| 133 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 134 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 135 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 136 | typedef PointerIntPair<Type *, 1, bool> TypeIsSExt; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 137 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 138 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 139 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 140 | class CodeGenPrepare : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 141 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 142 | const TargetLowering *TLI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 143 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 144 | const TargetLibraryInfo *TLInfo; |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 145 | const LoopInfo *LI; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 146 | std::unique_ptr<BlockFrequencyInfo> BFI; |
| 147 | std::unique_ptr<BranchProbabilityInfo> BPI; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 148 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 149 | /// As we scan instructions optimizing them, this is the next instruction |
| 150 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 151 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 152 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 153 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 154 | /// This allows us to avoid inserting duplicate code for blocks with |
| 155 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 156 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 157 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 158 | /// Keeps track of all instructions inserted for the current function. |
| 159 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 160 | /// Keeps track of the type of the related instruction before their |
| 161 | /// promotion for the current function. |
| 162 | InstrToOrigTy PromotedInsts; |
| 163 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 164 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 165 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 166 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 167 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 168 | bool OptSize; |
| 169 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 170 | /// DataLayout for the Function being processed. |
| 171 | const DataLayout *DL; |
| 172 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 173 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 174 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 175 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 176 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 177 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 178 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 179 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 180 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 181 | StringRef getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 182 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 183 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 184 | // FIXME: When we can selectively preserve passes, preserve the domtree. |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 185 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 186 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 187 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 188 | AU.addRequired<LoopInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 189 | } |
| 190 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 191 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 192 | bool eliminateFallThrough(Function &F); |
| 193 | bool eliminateMostlyEmptyBlocks(Function &F); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 194 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 195 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 196 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 197 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, |
| 198 | bool isPreheader); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 199 | bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 200 | bool optimizeInst(Instruction *I, bool& ModifiedDT); |
| 201 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 202 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 203 | bool optimizeInlineAsmInst(CallInst *CS); |
| 204 | bool optimizeCallInst(CallInst *CI, bool& ModifiedDT); |
| 205 | bool moveExtToFormExtLoad(Instruction *&I); |
| 206 | bool optimizeExtUses(Instruction *I); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 207 | bool optimizeLoadExt(LoadInst *I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 208 | bool optimizeSelectInst(SelectInst *SI); |
| 209 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 210 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 211 | bool optimizeExtractElementInst(Instruction *Inst); |
| 212 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 213 | bool placeDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 214 | bool sinkAndCmp(Function &F); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 215 | bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 216 | Instruction *&Inst, |
| 217 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 218 | unsigned CreatedInstCost); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 219 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 220 | bool simplifyOffsetableRelocate(Instruction &I); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 221 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 222 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 223 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 224 | char CodeGenPrepare::ID = 0; |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 225 | INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare", |
| 226 | "Optimize for code generation", false, false) |
| 227 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) |
| 228 | INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare", |
| 229 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 230 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 231 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 232 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 233 | } |
| 234 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 235 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 236 | if (skipFunction(F)) |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 237 | return false; |
| 238 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 239 | DL = &F.getParent()->getDataLayout(); |
| 240 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 241 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 242 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 243 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 244 | PromotedInsts.clear(); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 245 | BFI.reset(); |
| 246 | BPI.reset(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 247 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 248 | ModifiedDT = false; |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 249 | if (TM) |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 250 | TLI = TM->getSubtargetImpl(F)->getTargetLowering(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 251 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 252 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 253 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 254 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 255 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 256 | if (ProfileGuidedSectionPrefix) { |
| 257 | ProfileSummaryInfo *PSI = |
| 258 | getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); |
| 259 | if (PSI->isFunctionEntryHot(&F)) |
| 260 | F.setSectionPrefix(".hot"); |
| 261 | else if (PSI->isFunctionEntryCold(&F)) |
| 262 | F.setSectionPrefix(".cold"); |
| 263 | } |
| 264 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 265 | /// This optimization identifies DIV instructions that can be |
| 266 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 267 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 268 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 269 | TLI->getBypassSlowDivWidths(); |
Eric Christopher | 49a7d6c | 2016-01-04 23:18:58 +0000 | [diff] [blame] | 270 | BasicBlock* BB = &*F.begin(); |
| 271 | while (BB != nullptr) { |
| 272 | // bypassSlowDivision may create new BBs, but we don't want to reapply the |
| 273 | // optimization to those blocks. |
| 274 | BasicBlock* Next = BB->getNextNode(); |
| 275 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); |
| 276 | BB = Next; |
| 277 | } |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 278 | } |
| 279 | |
| 280 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 281 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 282 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 283 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 284 | // 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] | 285 | // 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] | 286 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 287 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 288 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 289 | // If there is a mask, compare against zero, and branch that can be combined |
| 290 | // into a single target instruction, push the mask and compare into branch |
| 291 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 292 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 293 | if (!DisableBranchOpts) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 294 | EverMadeChange |= sinkAndCmp(F); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 295 | EverMadeChange |= splitBranchCondition(F); |
| 296 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 297 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 298 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 299 | while (MadeChange) { |
| 300 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 301 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 302 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 303 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 304 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 305 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 306 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 307 | if (ModifiedDTOnIteration) |
| 308 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 309 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 310 | EverMadeChange |= MadeChange; |
| 311 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 312 | |
| 313 | SunkAddrs.clear(); |
| 314 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 315 | if (!DisableBranchOpts) { |
| 316 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 317 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 318 | for (BasicBlock &BB : F) { |
| 319 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 320 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 321 | if (!MadeChange) continue; |
| 322 | |
| 323 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 324 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 325 | if (pred_begin(*II) == pred_end(*II)) |
| 326 | WorkList.insert(*II); |
| 327 | } |
| 328 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 329 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 330 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 331 | while (!WorkList.empty()) { |
| 332 | BasicBlock *BB = *WorkList.begin(); |
| 333 | WorkList.erase(BB); |
| 334 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 335 | |
| 336 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 337 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 338 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 339 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 340 | if (pred_begin(*II) == pred_end(*II)) |
| 341 | WorkList.insert(*II); |
| 342 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 343 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 344 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 345 | // a single edge. |
| 346 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 347 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 348 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 349 | EverMadeChange |= MadeChange; |
| 350 | } |
| 351 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 352 | if (!DisableGCOpts) { |
| 353 | SmallVector<Instruction *, 2> Statepoints; |
| 354 | for (BasicBlock &BB : F) |
| 355 | for (Instruction &I : BB) |
| 356 | if (isStatepoint(I)) |
| 357 | Statepoints.push_back(&I); |
| 358 | for (auto &I : Statepoints) |
| 359 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 360 | } |
| 361 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 362 | return EverMadeChange; |
| 363 | } |
| 364 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 365 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 366 | /// basic blocks has a single successor pointing to the other basic block, |
| 367 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 368 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 369 | bool Changed = false; |
| 370 | // 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] | 371 | 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] | 372 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 373 | // If the destination block has a single pred, then this is a trivial |
| 374 | // edge, just collapse it. |
| 375 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 376 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 377 | // Don't merge if BB's address is taken. |
| 378 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 379 | |
| 380 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 381 | if (Term && !Term->isConditional()) { |
| 382 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 383 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 384 | // Remember if SinglePred was the entry block of the function. |
| 385 | // If so, we will need to move BB back to the entry position. |
| 386 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 387 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 388 | |
| 389 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 390 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 391 | |
| 392 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 393 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 394 | } |
| 395 | } |
| 396 | return Changed; |
| 397 | } |
| 398 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 399 | /// Find a destination block from BB if BB is mergeable empty block. |
| 400 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { |
| 401 | // If this block doesn't end with an uncond branch, ignore it. |
| 402 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 403 | if (!BI || !BI->isUnconditional()) |
| 404 | return nullptr; |
| 405 | |
| 406 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 407 | // node, then other stuff is happening here. |
| 408 | BasicBlock::iterator BBI = BI->getIterator(); |
| 409 | if (BBI != BB->begin()) { |
| 410 | --BBI; |
| 411 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 412 | if (BBI == BB->begin()) |
| 413 | break; |
| 414 | --BBI; |
| 415 | } |
| 416 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 417 | return nullptr; |
| 418 | } |
| 419 | |
| 420 | // Do not break infinite loops. |
| 421 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 422 | if (DestBB == BB) |
| 423 | return nullptr; |
| 424 | |
| 425 | if (!canMergeBlocks(BB, DestBB)) |
| 426 | DestBB = nullptr; |
| 427 | |
| 428 | return DestBB; |
| 429 | } |
| 430 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 431 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 432 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 433 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 434 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 435 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 436 | SmallPtrSet<BasicBlock *, 16> Preheaders; |
| 437 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); |
| 438 | while (!LoopList.empty()) { |
| 439 | Loop *L = LoopList.pop_back_val(); |
| 440 | LoopList.insert(LoopList.end(), L->begin(), L->end()); |
| 441 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 442 | Preheaders.insert(Preheader); |
| 443 | } |
| 444 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 445 | bool MadeChange = false; |
| 446 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 447 | 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] | 448 | BasicBlock *BB = &*I++; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 449 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); |
| 450 | if (!DestBB || |
| 451 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 452 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 453 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 454 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 455 | MadeChange = true; |
| 456 | } |
| 457 | return MadeChange; |
| 458 | } |
| 459 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame^] | 460 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, |
| 461 | BasicBlock *DestBB, |
| 462 | bool isPreheader) { |
| 463 | // Do not delete loop preheaders if doing so would create a critical edge. |
| 464 | // Loop preheaders can be good locations to spill registers. If the |
| 465 | // preheader is deleted and we create a critical edge, registers may be |
| 466 | // spilled in the loop body instead. |
| 467 | if (!DisablePreheaderProtect && isPreheader && |
| 468 | !(BB->getSinglePredecessor() && |
| 469 | BB->getSinglePredecessor()->getSingleSuccessor())) |
| 470 | return false; |
| 471 | |
| 472 | // Try to skip merging if the unique predecessor of BB is terminated by a |
| 473 | // switch or indirect branch instruction, and BB is used as an incoming block |
| 474 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to |
| 475 | // add COPY instructions in the predecessor of BB instead of BB (if it is not |
| 476 | // merged). Note that the critical edge created by merging such blocks wont be |
| 477 | // split in MachineSink because the jump table is not analyzable. By keeping |
| 478 | // such empty block (BB), ISel will place COPY instructions in BB, not in the |
| 479 | // predecessor of BB. |
| 480 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 481 | if (!Pred || |
| 482 | !(isa<SwitchInst>(Pred->getTerminator()) || |
| 483 | isa<IndirectBrInst>(Pred->getTerminator()))) |
| 484 | return true; |
| 485 | |
| 486 | if (BB->getTerminator() != BB->getFirstNonPHI()) |
| 487 | return true; |
| 488 | |
| 489 | // We use a simple cost heuristic which determine skipping merging is |
| 490 | // profitable if the cost of skipping merging is less than the cost of |
| 491 | // merging : Cost(skipping merging) < Cost(merging BB), where the |
| 492 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and |
| 493 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). |
| 494 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : |
| 495 | // Freq(Pred) / Freq(BB) > 2. |
| 496 | // Note that if there are multiple empty blocks sharing the same incoming |
| 497 | // value for the PHIs in the DestBB, we consider them together. In such |
| 498 | // case, Cost(merging BB) will be the sum of their frequencies. |
| 499 | |
| 500 | if (!isa<PHINode>(DestBB->begin())) |
| 501 | return true; |
| 502 | |
| 503 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; |
| 504 | |
| 505 | // Find all other incoming blocks from which incoming values of all PHIs in |
| 506 | // DestBB are the same as the ones from BB. |
| 507 | for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; |
| 508 | ++PI) { |
| 509 | BasicBlock *DestBBPred = *PI; |
| 510 | if (DestBBPred == BB) |
| 511 | continue; |
| 512 | |
| 513 | bool HasAllSameValue = true; |
| 514 | BasicBlock::const_iterator DestBBI = DestBB->begin(); |
| 515 | while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) { |
| 516 | if (DestPN->getIncomingValueForBlock(BB) != |
| 517 | DestPN->getIncomingValueForBlock(DestBBPred)) { |
| 518 | HasAllSameValue = false; |
| 519 | break; |
| 520 | } |
| 521 | } |
| 522 | if (HasAllSameValue) |
| 523 | SameIncomingValueBBs.insert(DestBBPred); |
| 524 | } |
| 525 | |
| 526 | // See if all BB's incoming values are same as the value from Pred. In this |
| 527 | // case, no reason to skip merging because COPYs are expected to be place in |
| 528 | // Pred already. |
| 529 | if (SameIncomingValueBBs.count(Pred)) |
| 530 | return true; |
| 531 | |
| 532 | if (!BFI) { |
| 533 | Function &F = *BB->getParent(); |
| 534 | LoopInfo LI{DominatorTree(F)}; |
| 535 | BPI.reset(new BranchProbabilityInfo(F, LI)); |
| 536 | BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); |
| 537 | } |
| 538 | |
| 539 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); |
| 540 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); |
| 541 | |
| 542 | for (auto SameValueBB : SameIncomingValueBBs) |
| 543 | if (SameValueBB->getUniquePredecessor() == Pred && |
| 544 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) |
| 545 | BBFreq += BFI->getBlockFreq(SameValueBB); |
| 546 | |
| 547 | return PredFreq.getFrequency() <= |
| 548 | BBFreq.getFrequency() * FreqRatioToSkipMerge; |
| 549 | } |
| 550 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 551 | /// Return true if we can merge BB into DestBB if there is a single |
| 552 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 553 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 554 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 555 | const BasicBlock *DestBB) const { |
| 556 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 557 | // the successor. If there are more complex condition (e.g. preheaders), |
| 558 | // don't mess around with them. |
| 559 | BasicBlock::const_iterator BBI = BB->begin(); |
| 560 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 561 | for (const User *U : PN->users()) { |
| 562 | const Instruction *UI = cast<Instruction>(U); |
| 563 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 564 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 565 | // If User is inside DestBB block and it is a PHINode then check |
| 566 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 567 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 568 | if (UI->getParent() == DestBB) { |
| 569 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 570 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 571 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 572 | if (Insn && Insn->getParent() == BB && |
| 573 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 574 | return false; |
| 575 | } |
| 576 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 577 | } |
| 578 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 579 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 580 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 581 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 582 | // can't merge the block. |
| 583 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 584 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 585 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 586 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 587 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 588 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 589 | // It is faster to get preds from a PHI than with pred_iterator. |
| 590 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 591 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 592 | } else { |
| 593 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 594 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 595 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 596 | // Walk the preds of DestBB. |
| 597 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 598 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 599 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 600 | BBI = DestBB->begin(); |
| 601 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 602 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 603 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 604 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 605 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 606 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 607 | if (V2PN->getParent() == BB) |
| 608 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 609 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 610 | // If there is a conflict, bail out. |
| 611 | if (V1 != V2) return false; |
| 612 | } |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | return true; |
| 617 | } |
| 618 | |
| 619 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 620 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 621 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 622 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 623 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 624 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 625 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 626 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 627 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 628 | // If the destination block has a single pred, then this is a trivial edge, |
| 629 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 630 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 631 | if (SinglePred != DestBB) { |
| 632 | // Remember if SinglePred was the entry block of the function. If so, we |
| 633 | // will need to move BB back to the entry position. |
| 634 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 635 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 636 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 637 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 638 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 639 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 640 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 641 | return; |
| 642 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 643 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 644 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 645 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 646 | // to handle the new incoming edges it is about to have. |
| 647 | PHINode *PN; |
| 648 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 649 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 650 | // Remove the incoming value for BB, and remember it. |
| 651 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 652 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 653 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 654 | // value that dominates BB. |
| 655 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 656 | if (InValPhi && InValPhi->getParent() == BB) { |
| 657 | // Add all of the input values of the input PHI as inputs of this phi. |
| 658 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 659 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 660 | InValPhi->getIncomingBlock(i)); |
| 661 | } else { |
| 662 | // Otherwise, add one instance of the dominating value for each edge that |
| 663 | // we will be adding. |
| 664 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 665 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 666 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 667 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 668 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 669 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 670 | } |
| 671 | } |
| 672 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 673 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 674 | // The PHIs are now updated, change everything that refers to BB to use |
| 675 | // DestBB and remove BB. |
| 676 | BB->replaceAllUsesWith(DestBB); |
| 677 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 678 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 679 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 680 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 681 | } |
| 682 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 683 | // Computes a map of base pointer relocation instructions to corresponding |
| 684 | // derived pointer relocation instructions given a vector of all relocate calls |
| 685 | static void computeBaseDerivedRelocateMap( |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 686 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, |
| 687 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> |
| 688 | &RelocateInstMap) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 689 | // Collect information in two maps: one primarily for locating the base object |
| 690 | // while filling the second map; the second map is the final structure holding |
| 691 | // a mapping between Base and corresponding Derived relocate calls |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 692 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; |
| 693 | for (auto *ThisRelocate : AllRelocateCalls) { |
| 694 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), |
| 695 | ThisRelocate->getDerivedPtrIndex()); |
| 696 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 697 | } |
| 698 | for (auto &Item : RelocateIdxMap) { |
| 699 | std::pair<unsigned, unsigned> Key = Item.first; |
| 700 | if (Key.first == Key.second) |
| 701 | // Base relocation: nothing to insert |
| 702 | continue; |
| 703 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 704 | GCRelocateInst *I = Item.second; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 705 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 706 | |
| 707 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 708 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 709 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 710 | // TODO: We might want to insert a new base object relocate and gep off |
| 711 | // that, if there are enough derived object relocates. |
| 712 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 713 | |
| 714 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 715 | } |
| 716 | } |
| 717 | |
| 718 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 719 | // small integer constants |
| 720 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 721 | SmallVectorImpl<Value *> &OffsetV) { |
| 722 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 723 | // Only accept small constant integer operands |
| 724 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 725 | if (!Op || Op->getZExtValue() > 20) |
| 726 | return false; |
| 727 | } |
| 728 | |
| 729 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 730 | OffsetV.push_back(GEP->getOperand(i)); |
| 731 | return true; |
| 732 | } |
| 733 | |
| 734 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 735 | // replace, computes a replacement, and affects it. |
| 736 | static bool |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 737 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, |
| 738 | const SmallVectorImpl<GCRelocateInst *> &Targets) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 739 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 740 | for (GCRelocateInst *ToReplace : Targets) { |
| 741 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 742 | "Not relocating a derived object of the original base object"); |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 743 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 744 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 745 | continue; |
| 746 | } |
| 747 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 748 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 749 | // Base and derived relocates are in different basic blocks. |
| 750 | // In this case transform is only valid when base dominates derived |
| 751 | // relocate. However it would be too expensive to check dominance |
| 752 | // for each such relocate, so we skip the whole transformation. |
| 753 | continue; |
| 754 | } |
| 755 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 756 | Value *Base = ToReplace->getBasePtr(); |
| 757 | auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 758 | if (!Derived || Derived->getPointerOperand() != Base) |
| 759 | continue; |
| 760 | |
| 761 | SmallVector<Value *, 2> OffsetV; |
| 762 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 763 | continue; |
| 764 | |
| 765 | // Create a Builder and replace the target callsite with a gep |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 766 | assert(RelocatedBase->getNextNode() && |
| 767 | "Should always have one since it's not a terminator"); |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 768 | |
| 769 | // Insert after RelocatedBase |
| 770 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 771 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 772 | |
| 773 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 774 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 775 | // match, and we should reuse it to get the derived pointer. But it could be |
| 776 | // cases like this: |
| 777 | // bb1: |
| 778 | // ... |
| 779 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 780 | // br label %merge |
| 781 | // |
| 782 | // bb2: |
| 783 | // ... |
| 784 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 785 | // br label %merge |
| 786 | // |
| 787 | // merge: |
| 788 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 789 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 790 | // |
| 791 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 792 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 793 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 794 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 795 | if (RelocatedBase->getType() != Base->getType()) { |
| 796 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 797 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 798 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 799 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 800 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 801 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 802 | // If the newly generated derived pointer's type does not match the original derived |
| 803 | // 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] | 804 | Value *ActualReplacement = Replacement; |
| 805 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 806 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 807 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 808 | } |
| 809 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 810 | ToReplace->eraseFromParent(); |
| 811 | |
| 812 | MadeChange = true; |
| 813 | } |
| 814 | return MadeChange; |
| 815 | } |
| 816 | |
| 817 | // Turns this: |
| 818 | // |
| 819 | // %base = ... |
| 820 | // %ptr = gep %base + 15 |
| 821 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 822 | // %base' = relocate(%tok, i32 4, i32 4) |
| 823 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 824 | // %val = load %ptr' |
| 825 | // |
| 826 | // into this: |
| 827 | // |
| 828 | // %base = ... |
| 829 | // %ptr = gep %base + 15 |
| 830 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 831 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 832 | // %ptr' = gep %base' + 15 |
| 833 | // %val = load %ptr' |
| 834 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 835 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 836 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 837 | |
| 838 | for (auto *U : I.users()) |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 839 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 840 | // Collect all the relocate calls associated with a statepoint |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 841 | AllRelocateCalls.push_back(Relocate); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 842 | |
| 843 | // We need atleast one base pointer relocation + one derived pointer |
| 844 | // relocation to mangle |
| 845 | if (AllRelocateCalls.size() < 2) |
| 846 | return false; |
| 847 | |
| 848 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 849 | // corresponding derived relocate instructions |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 850 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 851 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 852 | if (RelocateInstMap.empty()) |
| 853 | return false; |
| 854 | |
| 855 | for (auto &Item : RelocateInstMap) |
| 856 | // Item.first is the RelocatedBase to offset against |
| 857 | // Item.second is the vector of Targets to replace |
| 858 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 859 | return MadeChange; |
| 860 | } |
| 861 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 862 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 863 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 864 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 865 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 866 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 867 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 868 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 869 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 870 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 871 | UI != E; ) { |
| 872 | Use &TheUse = UI.getUse(); |
| 873 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 874 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 875 | // Figure out which BB this cast is used in. For PHI's this is the |
| 876 | // appropriate predecessor block. |
| 877 | BasicBlock *UserBB = User->getParent(); |
| 878 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 879 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 880 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 881 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 882 | // Preincrement use iterator so we don't invalidate it. |
| 883 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 884 | |
David Majnemer | 0c80e2e | 2016-04-27 19:36:38 +0000 | [diff] [blame] | 885 | // The first insertion point of a block containing an EH pad is after the |
| 886 | // pad. If the pad is the user, we cannot sink the cast past the pad. |
| 887 | if (User->isEHPad()) |
| 888 | continue; |
| 889 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 890 | // If the block selected to receive the cast is an EH pad that does not |
| 891 | // allow non-PHI instructions before the terminator, we can't sink the |
| 892 | // cast. |
| 893 | if (UserBB->getTerminator()->isEHPad()) |
| 894 | continue; |
| 895 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 896 | // If this user is in the same block as the cast, don't change the cast. |
| 897 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 898 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 899 | // If we have already inserted a cast into this block, use it. |
| 900 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 901 | |
| 902 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 903 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 904 | assert(InsertPt != UserBB->end()); |
| 905 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 906 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 907 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 908 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 909 | // 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] | 910 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 911 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 912 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 913 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 914 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 915 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 916 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 917 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 918 | MadeChange = true; |
| 919 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 920 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 921 | return MadeChange; |
| 922 | } |
| 923 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 924 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 925 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 926 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 927 | /// |
| 928 | /// Return true if any changes are made. |
| 929 | /// |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 930 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 931 | const DataLayout &DL) { |
Justin Lebar | 3e50a5b | 2016-11-21 22:49:15 +0000 | [diff] [blame] | 932 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition |
| 933 | // than sinking only nop casts, but is helpful on some platforms. |
| 934 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { |
| 935 | if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(), |
| 936 | ASC->getDestAddressSpace())) |
| 937 | return false; |
| 938 | } |
| 939 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 940 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 941 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 942 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 943 | |
| 944 | // This is an fp<->int conversion? |
| 945 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 946 | return false; |
| 947 | |
| 948 | // If this is an extension, it will be a zero or sign extension, which |
| 949 | // isn't a noop. |
| 950 | if (SrcVT.bitsLT(DstVT)) return false; |
| 951 | |
| 952 | // If these values will be promoted, find out what they will be promoted |
| 953 | // to. This helps us consider truncates on PPC as noop copies when they |
| 954 | // are. |
| 955 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 956 | TargetLowering::TypePromoteInteger) |
| 957 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 958 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 959 | TargetLowering::TypePromoteInteger) |
| 960 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 961 | |
| 962 | // If, after promotion, these are the same types, this is a noop copy. |
| 963 | if (SrcVT != DstVT) |
| 964 | return false; |
| 965 | |
| 966 | return SinkCast(CI); |
| 967 | } |
| 968 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 969 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 970 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 971 | /// |
| 972 | /// Return true if any changes were made. |
| 973 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 974 | Value *A, *B; |
| 975 | Instruction *AddI; |
| 976 | if (!match(CI, |
| 977 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 978 | return false; |
| 979 | |
| 980 | Type *Ty = AddI->getType(); |
| 981 | if (!isa<IntegerType>(Ty)) |
| 982 | return false; |
| 983 | |
| 984 | // We don't want to move around uses of condition values this late, so we we |
| 985 | // check if it is legal to create the call to the intrinsic in the basic |
| 986 | // block containing the icmp: |
| 987 | |
| 988 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 989 | return false; |
| 990 | |
| 991 | #ifndef NDEBUG |
| 992 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 993 | // for now: |
| 994 | if (AddI->hasOneUse()) |
| 995 | assert(*AddI->user_begin() == CI && "expected!"); |
| 996 | #endif |
| 997 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 998 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 999 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 1000 | |
| 1001 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 1002 | |
| 1003 | auto *UAddWithOverflow = |
| 1004 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 1005 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 1006 | auto *Overflow = |
| 1007 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 1008 | |
| 1009 | CI->replaceAllUsesWith(Overflow); |
| 1010 | AddI->replaceAllUsesWith(UAdd); |
| 1011 | CI->eraseFromParent(); |
| 1012 | AddI->eraseFromParent(); |
| 1013 | return true; |
| 1014 | } |
| 1015 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1016 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 1017 | /// registers that must be created and coalesced. This is a clear win except on |
| 1018 | /// targets with multiple condition code registers (PowerPC), where it might |
| 1019 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1020 | /// |
| 1021 | /// Return true if any changes are made. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1022 | static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1023 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1024 | |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1025 | // Avoid sinking soft-FP comparisons, since this can move them into a loop. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1026 | if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI)) |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1027 | return false; |
| 1028 | |
| 1029 | // Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1030 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1031 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1032 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1033 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1034 | UI != E; ) { |
| 1035 | Use &TheUse = UI.getUse(); |
| 1036 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1037 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1038 | // Preincrement use iterator so we don't invalidate it. |
| 1039 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1040 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1041 | // Don't bother for PHI nodes. |
| 1042 | if (isa<PHINode>(User)) |
| 1043 | continue; |
| 1044 | |
| 1045 | // Figure out which BB this cmp is used in. |
| 1046 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1047 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1048 | // If this user is in the same block as the cmp, don't change the cmp. |
| 1049 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1050 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1051 | // If we have already inserted a cmp into this block, use it. |
| 1052 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 1053 | |
| 1054 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1055 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1056 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1057 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1058 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 1059 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Wolfgang Pieb | e51bede | 2016-10-06 21:43:45 +0000 | [diff] [blame] | 1060 | // Propagate the debug info. |
| 1061 | InsertedCmp->setDebugLoc(CI->getDebugLoc()); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1062 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1063 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1064 | // Replace a use of the cmp with a use of the new cmp. |
| 1065 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1066 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1067 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1068 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1069 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1070 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1071 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1072 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1073 | MadeChange = true; |
| 1074 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1075 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1076 | return MadeChange; |
| 1077 | } |
| 1078 | |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 1079 | static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1080 | if (SinkCmpExpression(CI, TLI)) |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1081 | return true; |
| 1082 | |
| 1083 | if (CombineUAddWithOverflow(CI)) |
| 1084 | return true; |
| 1085 | |
| 1086 | return false; |
| 1087 | } |
| 1088 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1089 | /// Check if the candidates could be combined with a shift instruction, which |
| 1090 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1091 | /// 1. Truncate instruction |
| 1092 | /// 2. And instruction and the imm is a mask of the low bits: |
| 1093 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 1094 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1095 | if (!isa<TruncInst>(User)) { |
| 1096 | if (User->getOpcode() != Instruction::And || |
| 1097 | !isa<ConstantInt>(User->getOperand(1))) |
| 1098 | return false; |
| 1099 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1100 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1101 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1102 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1103 | return false; |
| 1104 | } |
| 1105 | return true; |
| 1106 | } |
| 1107 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1108 | /// 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] | 1109 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1110 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 1111 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1112 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1113 | BasicBlock *UserBB = User->getParent(); |
| 1114 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 1115 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 1116 | bool MadeChange = false; |
| 1117 | |
| 1118 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 1119 | TruncE = TruncI->user_end(); |
| 1120 | TruncUI != TruncE;) { |
| 1121 | |
| 1122 | Use &TruncTheUse = TruncUI.getUse(); |
| 1123 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 1124 | // Preincrement use iterator so we don't invalidate it. |
| 1125 | |
| 1126 | ++TruncUI; |
| 1127 | |
| 1128 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 1129 | if (!ISDOpcode) |
| 1130 | continue; |
| 1131 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 1132 | // If the use is actually a legal node, there will not be an |
| 1133 | // implicit truncate. |
| 1134 | // FIXME: always querying the result type is just an |
| 1135 | // approximation; some nodes' legality is determined by the |
| 1136 | // 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] | 1137 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1138 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1139 | continue; |
| 1140 | |
| 1141 | // Don't bother for PHI nodes. |
| 1142 | if (isa<PHINode>(TruncUser)) |
| 1143 | continue; |
| 1144 | |
| 1145 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 1146 | |
| 1147 | if (UserBB == TruncUserBB) |
| 1148 | continue; |
| 1149 | |
| 1150 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 1151 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 1152 | |
| 1153 | if (!InsertedShift && !InsertedTrunc) { |
| 1154 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1155 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1156 | // Sink the shift |
| 1157 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1158 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1159 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1160 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1161 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1162 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1163 | |
| 1164 | // Sink the trunc |
| 1165 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 1166 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1167 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1168 | |
| 1169 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1170 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1171 | |
| 1172 | MadeChange = true; |
| 1173 | |
| 1174 | TruncTheUse = InsertedTrunc; |
| 1175 | } |
| 1176 | } |
| 1177 | return MadeChange; |
| 1178 | } |
| 1179 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1180 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1181 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1182 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1183 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1184 | /// BB1: |
| 1185 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1186 | /// BB2: |
| 1187 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1188 | /// ==> |
| 1189 | /// |
| 1190 | /// BB2: |
| 1191 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1192 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1193 | /// |
| 1194 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1195 | /// instruction. |
| 1196 | /// Return true if any changes are made. |
| 1197 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1198 | const TargetLowering &TLI, |
| 1199 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1200 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1201 | |
| 1202 | /// Only insert instructions in each block once. |
| 1203 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1204 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1205 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1206 | |
| 1207 | bool MadeChange = false; |
| 1208 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1209 | UI != E;) { |
| 1210 | Use &TheUse = UI.getUse(); |
| 1211 | Instruction *User = cast<Instruction>(*UI); |
| 1212 | // Preincrement use iterator so we don't invalidate it. |
| 1213 | ++UI; |
| 1214 | |
| 1215 | // Don't bother for PHI nodes. |
| 1216 | if (isa<PHINode>(User)) |
| 1217 | continue; |
| 1218 | |
| 1219 | if (!isExtractBitsCandidateUse(User)) |
| 1220 | continue; |
| 1221 | |
| 1222 | BasicBlock *UserBB = User->getParent(); |
| 1223 | |
| 1224 | if (UserBB == DefBB) { |
| 1225 | // If the shift and truncate instruction are in the same BB. The use of |
| 1226 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1227 | // legal. In this case, we would like to sink both shift and truncate |
| 1228 | // instruction to the BB of TruncUse. |
| 1229 | // for example: |
| 1230 | // BB1: |
| 1231 | // i64 shift.result = lshr i64 opnd, imm |
| 1232 | // trunc.result = trunc shift.result to i16 |
| 1233 | // |
| 1234 | // BB2: |
| 1235 | // ----> We will have an implicit truncate here if the architecture does |
| 1236 | // not have i16 compare. |
| 1237 | // cmp i16 trunc.result, opnd2 |
| 1238 | // |
| 1239 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1240 | // If the type of the truncate is legal, no trucate will be |
| 1241 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1242 | && |
| 1243 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1244 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1245 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1246 | |
| 1247 | continue; |
| 1248 | } |
| 1249 | // If we have already inserted a shift into this block, use it. |
| 1250 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1251 | |
| 1252 | if (!InsertedShift) { |
| 1253 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1254 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1255 | |
| 1256 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1257 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1258 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1259 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1260 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1261 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1262 | |
| 1263 | MadeChange = true; |
| 1264 | } |
| 1265 | |
| 1266 | // Replace a use of the shift with a use of the new shift. |
| 1267 | TheUse = InsertedShift; |
| 1268 | } |
| 1269 | |
| 1270 | // If we removed all uses, nuke the shift. |
| 1271 | if (ShiftI->use_empty()) |
| 1272 | ShiftI->eraseFromParent(); |
| 1273 | |
| 1274 | return MadeChange; |
| 1275 | } |
| 1276 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1277 | // Translate a masked load intrinsic like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1278 | // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, |
| 1279 | // <16 x i1> %mask, <16 x i32> %passthru) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1280 | // 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] | 1281 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1282 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1283 | // %1 = bitcast i8* %addr to i32* |
| 1284 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1285 | // %3 = icmp eq i1 %2, true |
| 1286 | // br i1 %3, label %cond.load, label %else |
| 1287 | // |
| 1288 | //cond.load: ; preds = %0 |
| 1289 | // %4 = getelementptr i32* %1, i32 0 |
| 1290 | // %5 = load i32* %4 |
| 1291 | // %6 = insertelement <16 x i32> undef, i32 %5, i32 0 |
| 1292 | // br label %else |
| 1293 | // |
| 1294 | //else: ; preds = %0, %cond.load |
| 1295 | // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] |
| 1296 | // %7 = extractelement <16 x i1> %mask, i32 1 |
| 1297 | // %8 = icmp eq i1 %7, true |
| 1298 | // br i1 %8, label %cond.load1, label %else2 |
| 1299 | // |
| 1300 | //cond.load1: ; preds = %else |
| 1301 | // %9 = getelementptr i32* %1, i32 1 |
| 1302 | // %10 = load i32* %9 |
| 1303 | // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 |
| 1304 | // br label %else2 |
| 1305 | // |
| 1306 | //else2: ; preds = %else, %cond.load1 |
| 1307 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1308 | // %12 = extractelement <16 x i1> %mask, i32 2 |
| 1309 | // %13 = icmp eq i1 %12, true |
| 1310 | // br i1 %13, label %cond.load4, label %else5 |
| 1311 | // |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1312 | static void scalarizeMaskedLoad(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1313 | Value *Ptr = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1314 | Value *Alignment = CI->getArgOperand(1); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1315 | Value *Mask = CI->getArgOperand(2); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1316 | Value *Src0 = CI->getArgOperand(3); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1317 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1318 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1319 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1320 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1321 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1322 | Type *EltTy = CI->getType()->getVectorElementType(); |
| 1323 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1324 | IRBuilder<> Builder(CI->getContext()); |
| 1325 | Instruction *InsertPt = CI; |
| 1326 | BasicBlock *IfBlock = CI->getParent(); |
| 1327 | BasicBlock *CondBlock = nullptr; |
| 1328 | BasicBlock *PrevIfBlock = CI->getParent(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1329 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1330 | Builder.SetInsertPoint(InsertPt); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1331 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1332 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1333 | // Short-cut if the mask is all-true. |
| 1334 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1335 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1336 | |
| 1337 | if (IsAllOnesMask) { |
| 1338 | Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); |
| 1339 | CI->replaceAllUsesWith(NewI); |
| 1340 | CI->eraseFromParent(); |
| 1341 | return; |
| 1342 | } |
| 1343 | |
| 1344 | // Adjust alignment for the scalar instruction. |
| 1345 | AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1346 | // Bitcast %addr fron i8* to EltTy* |
| 1347 | Type *NewPtrType = |
| 1348 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1349 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1350 | unsigned VectorWidth = VecType->getNumElements(); |
| 1351 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1352 | Value *UndefVal = UndefValue::get(VecType); |
| 1353 | |
| 1354 | // The result vector |
| 1355 | Value *VResult = UndefVal; |
| 1356 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1357 | if (isa<ConstantVector>(Mask)) { |
| 1358 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1359 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1360 | continue; |
| 1361 | Value *Gep = |
| 1362 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1363 | LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
| 1364 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1365 | Builder.getInt32(Idx)); |
| 1366 | } |
| 1367 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1368 | CI->replaceAllUsesWith(NewI); |
| 1369 | CI->eraseFromParent(); |
| 1370 | return; |
| 1371 | } |
| 1372 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1373 | PHINode *Phi = nullptr; |
| 1374 | Value *PrevPhi = UndefVal; |
| 1375 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1376 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1377 | |
| 1378 | // Fill the "else" block, created in the previous iteration |
| 1379 | // |
| 1380 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1381 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1382 | // %to_load = icmp eq i1 %mask_1, true |
| 1383 | // br i1 %to_load, label %cond.load, label %else |
| 1384 | // |
| 1385 | if (Idx > 0) { |
| 1386 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1387 | Phi->addIncoming(VResult, CondBlock); |
| 1388 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1389 | PrevPhi = Phi; |
| 1390 | VResult = Phi; |
| 1391 | } |
| 1392 | |
| 1393 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1394 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1395 | ConstantInt::get(Predicate->getType(), 1)); |
| 1396 | |
| 1397 | // Create "cond" block |
| 1398 | // |
| 1399 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1400 | // %Elt = load i32* %EltAddr |
| 1401 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1402 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1403 | CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1404 | Builder.SetInsertPoint(InsertPt); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1405 | |
| 1406 | Value *Gep = |
| 1407 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1408 | LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1409 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); |
| 1410 | |
| 1411 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1412 | BasicBlock *NewIfBlock = |
| 1413 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1414 | Builder.SetInsertPoint(InsertPt); |
| 1415 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1416 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1417 | OldBr->eraseFromParent(); |
| 1418 | PrevIfBlock = IfBlock; |
| 1419 | IfBlock = NewIfBlock; |
| 1420 | } |
| 1421 | |
| 1422 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1423 | Phi->addIncoming(VResult, CondBlock); |
| 1424 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1425 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1426 | CI->replaceAllUsesWith(NewI); |
| 1427 | CI->eraseFromParent(); |
| 1428 | } |
| 1429 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1430 | // Translate a masked store intrinsic, like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1431 | // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, |
| 1432 | // <16 x i1> %mask) |
| 1433 | // to a chain of basic blocks, that stores element one-by-one if |
| 1434 | // the appropriate mask bit is set |
| 1435 | // |
| 1436 | // %1 = bitcast i8* %addr to i32* |
| 1437 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1438 | // %3 = icmp eq i1 %2, true |
| 1439 | // br i1 %3, label %cond.store, label %else |
| 1440 | // |
| 1441 | // cond.store: ; preds = %0 |
| 1442 | // %4 = extractelement <16 x i32> %val, i32 0 |
| 1443 | // %5 = getelementptr i32* %1, i32 0 |
| 1444 | // store i32 %4, i32* %5 |
| 1445 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1446 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1447 | // else: ; preds = %0, %cond.store |
| 1448 | // %6 = extractelement <16 x i1> %mask, i32 1 |
| 1449 | // %7 = icmp eq i1 %6, true |
| 1450 | // br i1 %7, label %cond.store1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1451 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1452 | // cond.store1: ; preds = %else |
| 1453 | // %8 = extractelement <16 x i32> %val, i32 1 |
| 1454 | // %9 = getelementptr i32* %1, i32 1 |
| 1455 | // store i32 %8, i32* %9 |
| 1456 | // br label %else2 |
| 1457 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1458 | static void scalarizeMaskedStore(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1459 | Value *Src = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1460 | Value *Ptr = CI->getArgOperand(1); |
| 1461 | Value *Alignment = CI->getArgOperand(2); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1462 | Value *Mask = CI->getArgOperand(3); |
| 1463 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1464 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1465 | VectorType *VecType = dyn_cast<VectorType>(Src->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1466 | assert(VecType && "Unexpected data type in masked store intrinsic"); |
| 1467 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1468 | Type *EltTy = VecType->getElementType(); |
| 1469 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1470 | IRBuilder<> Builder(CI->getContext()); |
| 1471 | Instruction *InsertPt = CI; |
| 1472 | BasicBlock *IfBlock = CI->getParent(); |
| 1473 | Builder.SetInsertPoint(InsertPt); |
| 1474 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1475 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1476 | // Short-cut if the mask is all-true. |
| 1477 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1478 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1479 | |
| 1480 | if (IsAllOnesMask) { |
| 1481 | Builder.CreateAlignedStore(Src, Ptr, AlignVal); |
| 1482 | CI->eraseFromParent(); |
| 1483 | return; |
| 1484 | } |
| 1485 | |
| 1486 | // Adjust alignment for the scalar instruction. |
| 1487 | AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1488 | // Bitcast %addr fron i8* to EltTy* |
| 1489 | Type *NewPtrType = |
| 1490 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1491 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1492 | unsigned VectorWidth = VecType->getNumElements(); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1493 | |
| 1494 | if (isa<ConstantVector>(Mask)) { |
| 1495 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1496 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1497 | continue; |
| 1498 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
| 1499 | Value *Gep = |
| 1500 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1501 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
| 1502 | } |
| 1503 | CI->eraseFromParent(); |
| 1504 | return; |
| 1505 | } |
| 1506 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1507 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1508 | |
| 1509 | // Fill the "else" block, created in the previous iteration |
| 1510 | // |
| 1511 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1512 | // %to_store = icmp eq i1 %mask_1, true |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1513 | // br i1 %to_store, label %cond.store, label %else |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1514 | // |
| 1515 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1516 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1517 | ConstantInt::get(Predicate->getType(), 1)); |
| 1518 | |
| 1519 | // Create "cond" block |
| 1520 | // |
| 1521 | // %OneElt = extractelement <16 x i32> %Src, i32 Idx |
| 1522 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1523 | // %store i32 %OneElt, i32* %EltAddr |
| 1524 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1525 | BasicBlock *CondBlock = |
| 1526 | IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1527 | Builder.SetInsertPoint(InsertPt); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1528 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1529 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1530 | Value *Gep = |
| 1531 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1532 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1533 | |
| 1534 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1535 | BasicBlock *NewIfBlock = |
| 1536 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1537 | Builder.SetInsertPoint(InsertPt); |
| 1538 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1539 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1540 | OldBr->eraseFromParent(); |
| 1541 | IfBlock = NewIfBlock; |
| 1542 | } |
| 1543 | CI->eraseFromParent(); |
| 1544 | } |
| 1545 | |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1546 | // Translate a masked gather intrinsic like |
| 1547 | // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, |
| 1548 | // <16 x i1> %Mask, <16 x i32> %Src) |
| 1549 | // to a chain of basic blocks, with loading element one-by-one if |
| 1550 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1551 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1552 | // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind |
| 1553 | // % Mask0 = extractelement <16 x i1> %Mask, i32 0 |
| 1554 | // % ToLoad0 = icmp eq i1 % Mask0, true |
| 1555 | // br i1 % ToLoad0, label %cond.load, label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1556 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1557 | // cond.load: |
| 1558 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1559 | // % Load0 = load i32, i32* % Ptr0, align 4 |
| 1560 | // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 |
| 1561 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1562 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1563 | // else: |
| 1564 | // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] |
| 1565 | // % Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1566 | // % ToLoad1 = icmp eq i1 % Mask1, true |
| 1567 | // br i1 % ToLoad1, label %cond.load1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1568 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1569 | // cond.load1: |
| 1570 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1571 | // % Load1 = load i32, i32* % Ptr1, align 4 |
| 1572 | // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 |
| 1573 | // br label %else2 |
| 1574 | // . . . |
| 1575 | // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src |
| 1576 | // ret <16 x i32> %Result |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1577 | static void scalarizeMaskedGather(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1578 | Value *Ptrs = CI->getArgOperand(0); |
| 1579 | Value *Alignment = CI->getArgOperand(1); |
| 1580 | Value *Mask = CI->getArgOperand(2); |
| 1581 | Value *Src0 = CI->getArgOperand(3); |
| 1582 | |
| 1583 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
| 1584 | |
| 1585 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1586 | |
| 1587 | IRBuilder<> Builder(CI->getContext()); |
| 1588 | Instruction *InsertPt = CI; |
| 1589 | BasicBlock *IfBlock = CI->getParent(); |
| 1590 | BasicBlock *CondBlock = nullptr; |
| 1591 | BasicBlock *PrevIfBlock = CI->getParent(); |
| 1592 | Builder.SetInsertPoint(InsertPt); |
| 1593 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1594 | |
| 1595 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1596 | |
| 1597 | Value *UndefVal = UndefValue::get(VecType); |
| 1598 | |
| 1599 | // The result vector |
| 1600 | Value *VResult = UndefVal; |
| 1601 | unsigned VectorWidth = VecType->getNumElements(); |
| 1602 | |
| 1603 | // Shorten the way if the mask is a vector of constants. |
| 1604 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1605 | |
| 1606 | if (IsConstMask) { |
| 1607 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1608 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1609 | continue; |
| 1610 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1611 | "Ptr" + Twine(Idx)); |
| 1612 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1613 | "Load" + Twine(Idx)); |
| 1614 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1615 | Builder.getInt32(Idx), |
| 1616 | "Res" + Twine(Idx)); |
| 1617 | } |
| 1618 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1619 | CI->replaceAllUsesWith(NewI); |
| 1620 | CI->eraseFromParent(); |
| 1621 | return; |
| 1622 | } |
| 1623 | |
| 1624 | PHINode *Phi = nullptr; |
| 1625 | Value *PrevPhi = UndefVal; |
| 1626 | |
| 1627 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1628 | |
| 1629 | // Fill the "else" block, created in the previous iteration |
| 1630 | // |
| 1631 | // %Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1632 | // %ToLoad1 = icmp eq i1 %Mask1, true |
| 1633 | // br i1 %ToLoad1, label %cond.load, label %else |
| 1634 | // |
| 1635 | if (Idx > 0) { |
| 1636 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1637 | Phi->addIncoming(VResult, CondBlock); |
| 1638 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1639 | PrevPhi = Phi; |
| 1640 | VResult = Phi; |
| 1641 | } |
| 1642 | |
| 1643 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1644 | Builder.getInt32(Idx), |
| 1645 | "Mask" + Twine(Idx)); |
| 1646 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1647 | ConstantInt::get(Predicate->getType(), 1), |
| 1648 | "ToLoad" + Twine(Idx)); |
| 1649 | |
| 1650 | // Create "cond" block |
| 1651 | // |
| 1652 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1653 | // %Elt = load i32* %EltAddr |
| 1654 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1655 | // |
| 1656 | CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); |
| 1657 | Builder.SetInsertPoint(InsertPt); |
| 1658 | |
| 1659 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1660 | "Ptr" + Twine(Idx)); |
| 1661 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1662 | "Load" + Twine(Idx)); |
| 1663 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), |
| 1664 | "Res" + Twine(Idx)); |
| 1665 | |
| 1666 | // Create "else" block, fill it in the next iteration |
| 1667 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1668 | Builder.SetInsertPoint(InsertPt); |
| 1669 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1670 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1671 | OldBr->eraseFromParent(); |
| 1672 | PrevIfBlock = IfBlock; |
| 1673 | IfBlock = NewIfBlock; |
| 1674 | } |
| 1675 | |
| 1676 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1677 | Phi->addIncoming(VResult, CondBlock); |
| 1678 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1679 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1680 | CI->replaceAllUsesWith(NewI); |
| 1681 | CI->eraseFromParent(); |
| 1682 | } |
| 1683 | |
| 1684 | // Translate a masked scatter intrinsic, like |
| 1685 | // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, |
| 1686 | // <16 x i1> %Mask) |
| 1687 | // to a chain of basic blocks, that stores element one-by-one if |
| 1688 | // the appropriate mask bit is set. |
| 1689 | // |
| 1690 | // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind |
| 1691 | // % Mask0 = extractelement <16 x i1> % Mask, i32 0 |
| 1692 | // % ToStore0 = icmp eq i1 % Mask0, true |
| 1693 | // br i1 %ToStore0, label %cond.store, label %else |
| 1694 | // |
| 1695 | // cond.store: |
| 1696 | // % Elt0 = extractelement <16 x i32> %Src, i32 0 |
| 1697 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1698 | // store i32 %Elt0, i32* % Ptr0, align 4 |
| 1699 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1700 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1701 | // else: |
| 1702 | // % Mask1 = extractelement <16 x i1> % Mask, i32 1 |
| 1703 | // % ToStore1 = icmp eq i1 % Mask1, true |
| 1704 | // br i1 % ToStore1, label %cond.store1, label %else2 |
| 1705 | // |
| 1706 | // cond.store1: |
| 1707 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1708 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1709 | // store i32 % Elt1, i32* % Ptr1, align 4 |
| 1710 | // br label %else2 |
| 1711 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1712 | static void scalarizeMaskedScatter(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1713 | Value *Src = CI->getArgOperand(0); |
| 1714 | Value *Ptrs = CI->getArgOperand(1); |
| 1715 | Value *Alignment = CI->getArgOperand(2); |
| 1716 | Value *Mask = CI->getArgOperand(3); |
| 1717 | |
| 1718 | assert(isa<VectorType>(Src->getType()) && |
| 1719 | "Unexpected data type in masked scatter intrinsic"); |
| 1720 | assert(isa<VectorType>(Ptrs->getType()) && |
| 1721 | isa<PointerType>(Ptrs->getType()->getVectorElementType()) && |
| 1722 | "Vector of pointers is expected in masked scatter intrinsic"); |
| 1723 | |
| 1724 | IRBuilder<> Builder(CI->getContext()); |
| 1725 | Instruction *InsertPt = CI; |
| 1726 | BasicBlock *IfBlock = CI->getParent(); |
| 1727 | Builder.SetInsertPoint(InsertPt); |
| 1728 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1729 | |
| 1730 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1731 | unsigned VectorWidth = Src->getType()->getVectorNumElements(); |
| 1732 | |
| 1733 | // Shorten the way if the mask is a vector of constants. |
| 1734 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1735 | |
| 1736 | if (IsConstMask) { |
| 1737 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1738 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1739 | continue; |
| 1740 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1741 | "Elt" + Twine(Idx)); |
| 1742 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1743 | "Ptr" + Twine(Idx)); |
| 1744 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1745 | } |
| 1746 | CI->eraseFromParent(); |
| 1747 | return; |
| 1748 | } |
| 1749 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1750 | // Fill the "else" block, created in the previous iteration |
| 1751 | // |
| 1752 | // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx |
| 1753 | // % ToStore = icmp eq i1 % Mask1, true |
| 1754 | // br i1 % ToStore, label %cond.store, label %else |
| 1755 | // |
| 1756 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1757 | Builder.getInt32(Idx), |
| 1758 | "Mask" + Twine(Idx)); |
| 1759 | Value *Cmp = |
| 1760 | Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1761 | ConstantInt::get(Predicate->getType(), 1), |
| 1762 | "ToStore" + Twine(Idx)); |
| 1763 | |
| 1764 | // Create "cond" block |
| 1765 | // |
| 1766 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1767 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1768 | // %store i32 % Elt1, i32* % Ptr1 |
| 1769 | // |
| 1770 | BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); |
| 1771 | Builder.SetInsertPoint(InsertPt); |
| 1772 | |
| 1773 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1774 | "Elt" + Twine(Idx)); |
| 1775 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1776 | "Ptr" + Twine(Idx)); |
| 1777 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1778 | |
| 1779 | // Create "else" block, fill it in the next iteration |
| 1780 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1781 | Builder.SetInsertPoint(InsertPt); |
| 1782 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1783 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1784 | OldBr->eraseFromParent(); |
| 1785 | IfBlock = NewIfBlock; |
| 1786 | } |
| 1787 | CI->eraseFromParent(); |
| 1788 | } |
| 1789 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1790 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 1791 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 1792 | /// |
| 1793 | /// We want to transform: |
| 1794 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 1795 | /// |
| 1796 | /// into: |
| 1797 | /// entry: |
| 1798 | /// %cmpz = icmp eq i64 %A, 0 |
| 1799 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 1800 | /// cond.false: |
| 1801 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 1802 | /// br label %cond.end |
| 1803 | /// cond.end: |
| 1804 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 1805 | /// |
| 1806 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 1807 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 1808 | const TargetLowering *TLI, |
| 1809 | const DataLayout *DL, |
| 1810 | bool &ModifiedDT) { |
| 1811 | if (!TLI || !DL) |
| 1812 | return false; |
| 1813 | |
| 1814 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 1815 | if (match(CountZeros->getOperand(1), m_One())) |
| 1816 | return false; |
| 1817 | |
| 1818 | // If it's cheap to speculate, there's nothing to do. |
| 1819 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 1820 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 1821 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 1822 | return false; |
| 1823 | |
| 1824 | // Only handle legal scalar cases. Anything else requires too much work. |
| 1825 | Type *Ty = CountZeros->getType(); |
| 1826 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 1827 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1828 | return false; |
| 1829 | |
| 1830 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 1831 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 1832 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 1833 | |
| 1834 | // Create another block after the count zero intrinsic. A PHI will be added |
| 1835 | // in this block to select the result of the intrinsic or the bit-width |
| 1836 | // constant if the input to the intrinsic is zero. |
| 1837 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 1838 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 1839 | |
| 1840 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 1841 | IRBuilder<> Builder(CountZeros->getContext()); |
| 1842 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 1843 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 1844 | |
| 1845 | // Replace the unconditional branch that was created by the first split with |
| 1846 | // a compare against zero and a conditional branch. |
| 1847 | Value *Zero = Constant::getNullValue(Ty); |
| 1848 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 1849 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 1850 | StartBlock->getTerminator()->eraseFromParent(); |
| 1851 | |
| 1852 | // Create a PHI in the end block to select either the output of the intrinsic |
| 1853 | // or the bit width of the operand. |
| 1854 | Builder.SetInsertPoint(&EndBlock->front()); |
| 1855 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 1856 | CountZeros->replaceAllUsesWith(PN); |
| 1857 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 1858 | PN->addIncoming(BitWidth, StartBlock); |
| 1859 | PN->addIncoming(CountZeros, CallBlock); |
| 1860 | |
| 1861 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 1862 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 1863 | // intrinsic; we only despeculate when a zero input is defined. |
| 1864 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 1865 | ModifiedDT = true; |
| 1866 | return true; |
| 1867 | } |
| 1868 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1869 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1870 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1871 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1872 | // Lower inline assembly if we can. |
| 1873 | // If we found an inline asm expession, and if the target knows how to |
| 1874 | // lower it to normal LLVM code, do so now. |
| 1875 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 1876 | if (TLI->ExpandInlineAsm(CI)) { |
| 1877 | // Avoid invalidating the iterator. |
| 1878 | CurInstIterator = BB->begin(); |
| 1879 | // Avoid processing instructions out of order, which could cause |
| 1880 | // reuse before a value is defined. |
| 1881 | SunkAddrs.clear(); |
| 1882 | return true; |
| 1883 | } |
| 1884 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1885 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1886 | return true; |
| 1887 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1888 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1889 | // Align the pointer arguments to this call if the target thinks it's a good |
| 1890 | // idea |
| 1891 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1892 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1893 | for (auto &Arg : CI->arg_operands()) { |
| 1894 | // We want to align both objects whose address is used directly and |
| 1895 | // objects whose address is used in casts and GEPs, though it only makes |
| 1896 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 1897 | // if size - offset meets the size threshold. |
| 1898 | if (!Arg->getType()->isPointerTy()) |
| 1899 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1900 | APInt Offset(DL->getPointerSizeInBits( |
| 1901 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 1902 | 0); |
| 1903 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1904 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1905 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 1906 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1907 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1908 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 1909 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1910 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1911 | // Global variables can only be aligned if they are defined in this |
| 1912 | // object (i.e. they are uniquely initialized in this object), and |
| 1913 | // over-aligning global variables that have an explicit section is |
| 1914 | // forbidden. |
| 1915 | GlobalVariable *GV; |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 1916 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && |
Tim Northover | 918f050 | 2016-07-18 18:28:52 +0000 | [diff] [blame] | 1917 | GV->getPointerAlignment(*DL) < PrefAlign && |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 1918 | DL->getTypeAllocSize(GV->getValueType()) >= |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1919 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1920 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1921 | } |
| 1922 | // If this is a memcpy (or similar) then we may be able to improve the |
| 1923 | // alignment |
| 1924 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1925 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1926 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1927 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1928 | if (Align > MI->getAlignment()) |
| 1929 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1930 | } |
| 1931 | } |
| 1932 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 1933 | // If we have a cold call site, try to sink addressing computation into the |
| 1934 | // cold block. This interacts with our handling for loads and stores to |
| 1935 | // ensure that we can fold all uses of a potential addressing computation |
| 1936 | // into their uses. TODO: generalize this to work over profiling data |
| 1937 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 1938 | for (auto &Arg : CI->arg_operands()) { |
| 1939 | if (!Arg->getType()->isPointerTy()) |
| 1940 | continue; |
| 1941 | unsigned AS = Arg->getType()->getPointerAddressSpace(); |
| 1942 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); |
| 1943 | } |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 1944 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1945 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1946 | if (II) { |
| 1947 | switch (II->getIntrinsicID()) { |
| 1948 | default: break; |
| 1949 | case Intrinsic::objectsize: { |
| 1950 | // Lower all uses of llvm.objectsize.* |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 1951 | uint64_t Size; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1952 | Type *ReturnTy = CI->getType(); |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 1953 | Constant *RetVal = nullptr; |
| 1954 | ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1)); |
| 1955 | ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min; |
| 1956 | if (getObjectSize(II->getArgOperand(0), |
| 1957 | Size, *DL, TLInfo, false, Mode)) { |
| 1958 | RetVal = ConstantInt::get(ReturnTy, Size); |
| 1959 | } else { |
| 1960 | RetVal = ConstantInt::get(ReturnTy, |
| 1961 | Mode == ObjSizeMode::Min ? 0 : -1ULL); |
| 1962 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1963 | // Substituting this can cause recursive simplifications, which can |
| 1964 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 1965 | // happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1966 | Value *CurValue = &*CurInstIterator; |
| 1967 | WeakVH IterHandle(CurValue); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1968 | |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 1969 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1970 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1971 | // If the iterator instruction was recursively deleted, start over at the |
| 1972 | // start of the block. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1973 | if (IterHandle != CurValue) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1974 | CurInstIterator = BB->begin(); |
| 1975 | SunkAddrs.clear(); |
| 1976 | } |
| 1977 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 1978 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1979 | case Intrinsic::masked_load: { |
| 1980 | // Scalarize unsupported vector masked load |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1981 | if (!TTI->isLegalMaskedLoad(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1982 | scalarizeMaskedLoad(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1983 | ModifiedDT = true; |
| 1984 | return true; |
| 1985 | } |
| 1986 | return false; |
| 1987 | } |
| 1988 | case Intrinsic::masked_store: { |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1989 | if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1990 | scalarizeMaskedStore(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1991 | ModifiedDT = true; |
| 1992 | return true; |
| 1993 | } |
| 1994 | return false; |
| 1995 | } |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1996 | case Intrinsic::masked_gather: { |
| 1997 | if (!TTI->isLegalMaskedGather(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1998 | scalarizeMaskedGather(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1999 | ModifiedDT = true; |
| 2000 | return true; |
| 2001 | } |
| 2002 | return false; |
| 2003 | } |
| 2004 | case Intrinsic::masked_scatter: { |
| 2005 | if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2006 | scalarizeMaskedScatter(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 2007 | ModifiedDT = true; |
| 2008 | return true; |
| 2009 | } |
| 2010 | return false; |
| 2011 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2012 | case Intrinsic::aarch64_stlxr: |
| 2013 | case Intrinsic::aarch64_stxr: { |
| 2014 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 2015 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 2016 | ExtVal->getParent() == CI->getParent()) |
| 2017 | return false; |
| 2018 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 2019 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2020 | // Mark this instruction as "inserted by CGP", so that other |
| 2021 | // optimizations don't touch it. |
| 2022 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2023 | return true; |
| 2024 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 2025 | case Intrinsic::invariant_group_barrier: |
| 2026 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 2027 | II->eraseFromParent(); |
| 2028 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2029 | |
| 2030 | case Intrinsic::cttz: |
| 2031 | case Intrinsic::ctlz: |
| 2032 | // If counting zeros is expensive, try to avoid it. |
| 2033 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2034 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2035 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2036 | if (TLI) { |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2037 | // Unknown address space. |
| 2038 | // TODO: Target hook to pick which address space the intrinsic cares |
| 2039 | // about? |
| 2040 | unsigned AddrSpace = ~0u; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2041 | SmallVector<Value*, 2> PtrOps; |
| 2042 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2043 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2044 | while (!PtrOps.empty()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2045 | if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2046 | return true; |
| 2047 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 2048 | } |
| 2049 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2050 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2051 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 2052 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 2053 | // Lower all default uses of _chk calls. This is very similar |
| 2054 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2055 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 2056 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2057 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2058 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 2059 | CI->replaceAllUsesWith(V); |
| 2060 | CI->eraseFromParent(); |
| 2061 | return true; |
| 2062 | } |
| 2063 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2064 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 2065 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2066 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 2067 | /// 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] | 2068 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2069 | /// bb0: |
| 2070 | /// %tmp0 = tail call i32 @f0() |
| 2071 | /// br label %return |
| 2072 | /// bb1: |
| 2073 | /// %tmp1 = tail call i32 @f1() |
| 2074 | /// br label %return |
| 2075 | /// bb2: |
| 2076 | /// %tmp2 = tail call i32 @f2() |
| 2077 | /// br label %return |
| 2078 | /// return: |
| 2079 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 2080 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2081 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2082 | /// |
| 2083 | /// => |
| 2084 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2085 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2086 | /// bb0: |
| 2087 | /// %tmp0 = tail call i32 @f0() |
| 2088 | /// ret i32 %tmp0 |
| 2089 | /// bb1: |
| 2090 | /// %tmp1 = tail call i32 @f1() |
| 2091 | /// ret i32 %tmp1 |
| 2092 | /// bb2: |
| 2093 | /// %tmp2 = tail call i32 @f2() |
| 2094 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2095 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2096 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 2097 | if (!TLI) |
| 2098 | return false; |
| 2099 | |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2100 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 2101 | if (!RetI) |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 2102 | return false; |
| 2103 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2104 | PHINode *PN = nullptr; |
| 2105 | BitCastInst *BCI = nullptr; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2106 | Value *V = RetI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2107 | if (V) { |
| 2108 | BCI = dyn_cast<BitCastInst>(V); |
| 2109 | if (BCI) |
| 2110 | V = BCI->getOperand(0); |
| 2111 | |
| 2112 | PN = dyn_cast<PHINode>(V); |
| 2113 | if (!PN) |
| 2114 | return false; |
| 2115 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2116 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2117 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2118 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2119 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2120 | // Make sure there are no instructions between the PHI and return, or that the |
| 2121 | // return is the first instruction in the block. |
| 2122 | if (PN) { |
| 2123 | BasicBlock::iterator BI = BB->begin(); |
| 2124 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2125 | if (&*BI == BCI) |
| 2126 | // Also skip over the bitcast. |
| 2127 | ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2128 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2129 | return false; |
| 2130 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2131 | BasicBlock::iterator BI = BB->begin(); |
| 2132 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2133 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2134 | return false; |
| 2135 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2136 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2137 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 2138 | /// call. |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2139 | const Function *F = BB->getParent(); |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2140 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2141 | if (PN) { |
| 2142 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 2143 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 2144 | // Make sure the phi value is indeed produced by the tail call. |
| 2145 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2146 | TLI->mayBeEmittedAsTailCall(CI) && |
| 2147 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2148 | TailCalls.push_back(CI); |
| 2149 | } |
| 2150 | } else { |
| 2151 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2152 | 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] | 2153 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2154 | continue; |
| 2155 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2156 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2157 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 2158 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2159 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 2160 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2161 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2162 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2163 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2164 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && |
| 2165 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2166 | TailCalls.push_back(CI); |
| 2167 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2168 | } |
| 2169 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2170 | bool Changed = false; |
| 2171 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 2172 | CallInst *CI = TailCalls[i]; |
| 2173 | CallSite CS(CI); |
| 2174 | |
| 2175 | // Conservatively require the attributes of the call to match those of the |
| 2176 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 2177 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 2178 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 2179 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 2180 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 2181 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2182 | continue; |
| 2183 | |
| 2184 | // Make sure the call instruction is followed by an unconditional branch to |
| 2185 | // the return block. |
| 2186 | BasicBlock *CallBB = CI->getParent(); |
| 2187 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 2188 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 2189 | continue; |
| 2190 | |
| 2191 | // Duplicate the return into CallBB. |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2192 | (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 2193 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2194 | ++NumRetsDup; |
| 2195 | } |
| 2196 | |
| 2197 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 2198 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2199 | BB->eraseFromParent(); |
| 2200 | |
| 2201 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2202 | } |
| 2203 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2204 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2205 | // Memory Optimization |
| 2206 | //===----------------------------------------------------------------------===// |
| 2207 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2208 | namespace { |
| 2209 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2210 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2211 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 2212 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2213 | Value *BaseReg; |
| 2214 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2215 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2216 | void print(raw_ostream &OS) const; |
| 2217 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2218 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2219 | bool operator==(const ExtAddrMode& O) const { |
| 2220 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 2221 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 2222 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 2223 | } |
| 2224 | }; |
| 2225 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2226 | #ifndef NDEBUG |
| 2227 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2228 | AM.print(OS); |
| 2229 | return OS; |
| 2230 | } |
| 2231 | #endif |
| 2232 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2233 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2234 | bool NeedPlus = false; |
| 2235 | OS << "["; |
| 2236 | if (BaseGV) { |
| 2237 | OS << (NeedPlus ? " + " : "") |
| 2238 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2239 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2240 | NeedPlus = true; |
| 2241 | } |
| 2242 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2243 | if (BaseOffs) { |
| 2244 | OS << (NeedPlus ? " + " : "") |
| 2245 | << BaseOffs; |
| 2246 | NeedPlus = true; |
| 2247 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2248 | |
| 2249 | if (BaseReg) { |
| 2250 | OS << (NeedPlus ? " + " : "") |
| 2251 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2252 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2253 | NeedPlus = true; |
| 2254 | } |
| 2255 | if (Scale) { |
| 2256 | OS << (NeedPlus ? " + " : "") |
| 2257 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2258 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2259 | } |
| 2260 | |
| 2261 | OS << ']'; |
| 2262 | } |
| 2263 | |
| 2264 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Yaron Keren | eb2a254 | 2016-01-29 20:50:44 +0000 | [diff] [blame] | 2265 | LLVM_DUMP_METHOD void ExtAddrMode::dump() const { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2266 | print(dbgs()); |
| 2267 | dbgs() << '\n'; |
| 2268 | } |
| 2269 | #endif |
| 2270 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2271 | /// \brief This class provides transaction based operation on the IR. |
| 2272 | /// Every change made through this class is recorded in the internal state and |
| 2273 | /// can be undone (rollback) until commit is called. |
| 2274 | class TypePromotionTransaction { |
| 2275 | |
| 2276 | /// \brief This represents the common interface of the individual transaction. |
| 2277 | /// Each class implements the logic for doing one specific modification on |
| 2278 | /// the IR via the TypePromotionTransaction. |
| 2279 | class TypePromotionAction { |
| 2280 | protected: |
| 2281 | /// The Instruction modified. |
| 2282 | Instruction *Inst; |
| 2283 | |
| 2284 | public: |
| 2285 | /// \brief Constructor of the action. |
| 2286 | /// The constructor performs the related action on the IR. |
| 2287 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2288 | |
| 2289 | virtual ~TypePromotionAction() {} |
| 2290 | |
| 2291 | /// \brief Undo the modification done by this action. |
| 2292 | /// When this method is called, the IR must be in the same state as it was |
| 2293 | /// before this action was applied. |
| 2294 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2295 | /// state as it was directly after this action was applied. |
| 2296 | virtual void undo() = 0; |
| 2297 | |
| 2298 | /// \brief Advocate every change made by this action. |
| 2299 | /// When the results on the IR of the action are to be kept, it is important |
| 2300 | /// to call this function, otherwise hidden information may be kept forever. |
| 2301 | virtual void commit() { |
| 2302 | // Nothing to be done, this action is not doing anything. |
| 2303 | } |
| 2304 | }; |
| 2305 | |
| 2306 | /// \brief Utility to remember the position of an instruction. |
| 2307 | class InsertionHandler { |
| 2308 | /// Position of an instruction. |
| 2309 | /// Either an instruction: |
| 2310 | /// - Is the first in a basic block: BB is used. |
| 2311 | /// - Has a previous instructon: PrevInst is used. |
| 2312 | union { |
| 2313 | Instruction *PrevInst; |
| 2314 | BasicBlock *BB; |
| 2315 | } Point; |
| 2316 | /// Remember whether or not the instruction had a previous instruction. |
| 2317 | bool HasPrevInstruction; |
| 2318 | |
| 2319 | public: |
| 2320 | /// \brief Record the position of \p Inst. |
| 2321 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2322 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2323 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2324 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2325 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2326 | else |
| 2327 | Point.BB = Inst->getParent(); |
| 2328 | } |
| 2329 | |
| 2330 | /// \brief Insert \p Inst at the recorded position. |
| 2331 | void insert(Instruction *Inst) { |
| 2332 | if (HasPrevInstruction) { |
| 2333 | if (Inst->getParent()) |
| 2334 | Inst->removeFromParent(); |
| 2335 | Inst->insertAfter(Point.PrevInst); |
| 2336 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2337 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2338 | if (Inst->getParent()) |
| 2339 | Inst->moveBefore(Position); |
| 2340 | else |
| 2341 | Inst->insertBefore(Position); |
| 2342 | } |
| 2343 | } |
| 2344 | }; |
| 2345 | |
| 2346 | /// \brief Move an instruction before another. |
| 2347 | class InstructionMoveBefore : public TypePromotionAction { |
| 2348 | /// Original position of the instruction. |
| 2349 | InsertionHandler Position; |
| 2350 | |
| 2351 | public: |
| 2352 | /// \brief Move \p Inst before \p Before. |
| 2353 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2354 | : TypePromotionAction(Inst), Position(Inst) { |
| 2355 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2356 | Inst->moveBefore(Before); |
| 2357 | } |
| 2358 | |
| 2359 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2360 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2361 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2362 | Position.insert(Inst); |
| 2363 | } |
| 2364 | }; |
| 2365 | |
| 2366 | /// \brief Set the operand of an instruction with a new value. |
| 2367 | class OperandSetter : public TypePromotionAction { |
| 2368 | /// Original operand of the instruction. |
| 2369 | Value *Origin; |
| 2370 | /// Index of the modified instruction. |
| 2371 | unsigned Idx; |
| 2372 | |
| 2373 | public: |
| 2374 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2375 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2376 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2377 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2378 | << "for:" << *Inst << "\n" |
| 2379 | << "with:" << *NewVal << "\n"); |
| 2380 | Origin = Inst->getOperand(Idx); |
| 2381 | Inst->setOperand(Idx, NewVal); |
| 2382 | } |
| 2383 | |
| 2384 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2385 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2386 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2387 | << "for: " << *Inst << "\n" |
| 2388 | << "with: " << *Origin << "\n"); |
| 2389 | Inst->setOperand(Idx, Origin); |
| 2390 | } |
| 2391 | }; |
| 2392 | |
| 2393 | /// \brief Hide the operands of an instruction. |
| 2394 | /// Do as if this instruction was not using any of its operands. |
| 2395 | class OperandsHider : public TypePromotionAction { |
| 2396 | /// The list of original operands. |
| 2397 | SmallVector<Value *, 4> OriginalValues; |
| 2398 | |
| 2399 | public: |
| 2400 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2401 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2402 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2403 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2404 | OriginalValues.reserve(NumOpnds); |
| 2405 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2406 | // Save the current operand. |
| 2407 | Value *Val = Inst->getOperand(It); |
| 2408 | OriginalValues.push_back(Val); |
| 2409 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2410 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2411 | // that we are not willing to pay. |
| 2412 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2413 | } |
| 2414 | } |
| 2415 | |
| 2416 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2417 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2418 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2419 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2420 | Inst->setOperand(It, OriginalValues[It]); |
| 2421 | } |
| 2422 | }; |
| 2423 | |
| 2424 | /// \brief Build a truncate instruction. |
| 2425 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2426 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2427 | public: |
| 2428 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2429 | /// result. |
| 2430 | /// trunc Opnd to Ty. |
| 2431 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2432 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2433 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2434 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2435 | } |
| 2436 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2437 | /// \brief Get the built value. |
| 2438 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2439 | |
| 2440 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2441 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2442 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2443 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2444 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2445 | } |
| 2446 | }; |
| 2447 | |
| 2448 | /// \brief Build a sign extension instruction. |
| 2449 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2450 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2451 | public: |
| 2452 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2453 | /// result. |
| 2454 | /// sext Opnd to Ty. |
| 2455 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2456 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2457 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2458 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2459 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2460 | } |
| 2461 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2462 | /// \brief Get the built value. |
| 2463 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2464 | |
| 2465 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2466 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2467 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2468 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2469 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2470 | } |
| 2471 | }; |
| 2472 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2473 | /// \brief Build a zero extension instruction. |
| 2474 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2475 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2476 | public: |
| 2477 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2478 | /// result. |
| 2479 | /// zext Opnd to Ty. |
| 2480 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2481 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2482 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2483 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2484 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2485 | } |
| 2486 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2487 | /// \brief Get the built value. |
| 2488 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2489 | |
| 2490 | /// \brief Remove the built instruction. |
| 2491 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2492 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2493 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2494 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2495 | } |
| 2496 | }; |
| 2497 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2498 | /// \brief Mutate an instruction to another type. |
| 2499 | class TypeMutator : public TypePromotionAction { |
| 2500 | /// Record the original type. |
| 2501 | Type *OrigTy; |
| 2502 | |
| 2503 | public: |
| 2504 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2505 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2506 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2507 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2508 | << "\n"); |
| 2509 | Inst->mutateType(NewTy); |
| 2510 | } |
| 2511 | |
| 2512 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2513 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2514 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2515 | << "\n"); |
| 2516 | Inst->mutateType(OrigTy); |
| 2517 | } |
| 2518 | }; |
| 2519 | |
| 2520 | /// \brief Replace the uses of an instruction by another instruction. |
| 2521 | class UsesReplacer : public TypePromotionAction { |
| 2522 | /// Helper structure to keep track of the replaced uses. |
| 2523 | struct InstructionAndIdx { |
| 2524 | /// The instruction using the instruction. |
| 2525 | Instruction *Inst; |
| 2526 | /// The index where this instruction is used for Inst. |
| 2527 | unsigned Idx; |
| 2528 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2529 | : Inst(Inst), Idx(Idx) {} |
| 2530 | }; |
| 2531 | |
| 2532 | /// Keep track of the original uses (pair Instruction, Index). |
| 2533 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 2534 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 2535 | |
| 2536 | public: |
| 2537 | /// \brief Replace all the use of \p Inst by \p New. |
| 2538 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2539 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2540 | << "\n"); |
| 2541 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2542 | for (Use &U : Inst->uses()) { |
| 2543 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2544 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2545 | } |
| 2546 | // Now, we can replace the uses. |
| 2547 | Inst->replaceAllUsesWith(New); |
| 2548 | } |
| 2549 | |
| 2550 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2551 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2552 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2553 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2554 | EndIt = OriginalUses.end(); |
| 2555 | UseIt != EndIt; ++UseIt) { |
| 2556 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2557 | } |
| 2558 | } |
| 2559 | }; |
| 2560 | |
| 2561 | /// \brief Remove an instruction from the IR. |
| 2562 | class InstructionRemover : public TypePromotionAction { |
| 2563 | /// Original position of the instruction. |
| 2564 | InsertionHandler Inserter; |
| 2565 | /// Helper structure to hide all the link to the instruction. In other |
| 2566 | /// words, this helps to do as if the instruction was removed. |
| 2567 | OperandsHider Hider; |
| 2568 | /// Keep track of the uses replaced, if any. |
| 2569 | UsesReplacer *Replacer; |
| 2570 | |
| 2571 | public: |
| 2572 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2573 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2574 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 2575 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2576 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2577 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2578 | if (New) |
| 2579 | Replacer = new UsesReplacer(Inst, New); |
| 2580 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 2581 | Inst->removeFromParent(); |
| 2582 | } |
| 2583 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2584 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2585 | |
| 2586 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2587 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2588 | |
| 2589 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2590 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2591 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2592 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2593 | Inserter.insert(Inst); |
| 2594 | if (Replacer) |
| 2595 | Replacer->undo(); |
| 2596 | Hider.undo(); |
| 2597 | } |
| 2598 | }; |
| 2599 | |
| 2600 | public: |
| 2601 | /// Restoration point. |
| 2602 | /// The restoration point is a pointer to an action instead of an iterator |
| 2603 | /// because the iterator may be invalidated but not the pointer. |
| 2604 | typedef const TypePromotionAction *ConstRestorationPt; |
| 2605 | /// Advocate every changes made in that transaction. |
| 2606 | void commit(); |
| 2607 | /// Undo all the changes made after the given point. |
| 2608 | void rollback(ConstRestorationPt Point); |
| 2609 | /// Get the current restoration point. |
| 2610 | ConstRestorationPt getRestorationPoint() const; |
| 2611 | |
| 2612 | /// \name API for IR modification with state keeping to support rollback. |
| 2613 | /// @{ |
| 2614 | /// Same as Instruction::setOperand. |
| 2615 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2616 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2617 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2618 | /// Same as Value::replaceAllUsesWith. |
| 2619 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2620 | /// Same as Value::mutateType. |
| 2621 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2622 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2623 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2624 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2625 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2626 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2627 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2628 | /// Same as Instruction::moveBefore. |
| 2629 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2630 | /// @} |
| 2631 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2632 | private: |
| 2633 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2634 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2635 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2636 | }; |
| 2637 | |
| 2638 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2639 | Value *NewVal) { |
| 2640 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2641 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2642 | } |
| 2643 | |
| 2644 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2645 | Value *NewVal) { |
| 2646 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2647 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2648 | } |
| 2649 | |
| 2650 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2651 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2652 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2653 | } |
| 2654 | |
| 2655 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2656 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2657 | } |
| 2658 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2659 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2660 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2661 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2662 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2663 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2664 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2665 | } |
| 2666 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2667 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2668 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2669 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2670 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2671 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2672 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2673 | } |
| 2674 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2675 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2676 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2677 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2678 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2679 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2680 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2681 | } |
| 2682 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2683 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2684 | Instruction *Before) { |
| 2685 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2686 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2687 | } |
| 2688 | |
| 2689 | TypePromotionTransaction::ConstRestorationPt |
| 2690 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2691 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2692 | } |
| 2693 | |
| 2694 | void TypePromotionTransaction::commit() { |
| 2695 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2696 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2697 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2698 | Actions.clear(); |
| 2699 | } |
| 2700 | |
| 2701 | void TypePromotionTransaction::rollback( |
| 2702 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2703 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2704 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2705 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2706 | } |
| 2707 | } |
| 2708 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2709 | /// \brief A helper class for matching addressing modes. |
| 2710 | /// |
| 2711 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2712 | class AddressingModeMatcher { |
| 2713 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2714 | const TargetMachine &TM; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2715 | const TargetLowering &TLI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2716 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2717 | |
| 2718 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2719 | /// the memory instruction that we're computing this address for. |
| 2720 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2721 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2722 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2723 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2724 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2725 | /// part of the return value of this addressing mode matching stuff. |
| 2726 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2727 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2728 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2729 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2730 | /// A map from the instructions to their type before promotion. |
| 2731 | InstrToOrigTy &PromotedInsts; |
| 2732 | /// The ongoing transaction where every action should be registered. |
| 2733 | TypePromotionTransaction &TPT; |
| 2734 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2735 | /// This is set to true when we should not do profitability checks. |
| 2736 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2737 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2738 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2739 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2740 | const TargetMachine &TM, Type *AT, unsigned AS, |
| 2741 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2742 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2743 | InstrToOrigTy &PromotedInsts, |
| 2744 | TypePromotionTransaction &TPT) |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2745 | : AddrModeInsts(AMI), TM(TM), |
| 2746 | TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent()) |
| 2747 | ->getTargetLowering()), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2748 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 2749 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 2750 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2751 | IgnoreProfitability = false; |
| 2752 | } |
| 2753 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2754 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2755 | /// 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] | 2756 | /// give an access type of AccessTy. This returns a list of involved |
| 2757 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2758 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2759 | /// optimizations. |
| 2760 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2761 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2762 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2763 | Instruction *MemoryInst, |
| 2764 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2765 | const TargetMachine &TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2766 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2767 | InstrToOrigTy &PromotedInsts, |
| 2768 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2769 | ExtAddrMode Result; |
| 2770 | |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2771 | bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2772 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2773 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2774 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2775 | return Result; |
| 2776 | } |
| 2777 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2778 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 2779 | bool matchAddr(Value *V, unsigned Depth); |
| 2780 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2781 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2782 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2783 | ExtAddrMode &AMBefore, |
| 2784 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2785 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 2786 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2787 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2788 | }; |
| 2789 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2790 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2791 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 2792 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2793 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2794 | unsigned Depth) { |
| 2795 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 2796 | // mode. Just process that directly. |
| 2797 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2798 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2799 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2800 | // If the scale is 0, it takes nothing to add this. |
| 2801 | if (Scale == 0) |
| 2802 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2803 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2804 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 2805 | // need an available scale field. |
| 2806 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 2807 | return false; |
| 2808 | |
| 2809 | ExtAddrMode TestAddrMode = AddrMode; |
| 2810 | |
| 2811 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 2812 | // [A+B + A*7] -> [B+A*8]. |
| 2813 | TestAddrMode.Scale += Scale; |
| 2814 | TestAddrMode.ScaledReg = ScaleReg; |
| 2815 | |
| 2816 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2817 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2818 | return false; |
| 2819 | |
| 2820 | // It was legal, so commit it. |
| 2821 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2822 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2823 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 2824 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 2825 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2826 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2827 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 2828 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 2829 | TestAddrMode.ScaledReg = AddLHS; |
| 2830 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2831 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2832 | // If this addressing mode is legal, commit it and remember that we folded |
| 2833 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2834 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2835 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 2836 | AddrMode = TestAddrMode; |
| 2837 | return true; |
| 2838 | } |
| 2839 | } |
| 2840 | |
| 2841 | // Otherwise, not (x+c)*scale, just return what we have. |
| 2842 | return true; |
| 2843 | } |
| 2844 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2845 | /// This is a little filter, which returns true if an addressing computation |
| 2846 | /// involving I might be folded into a load/store accessing it. |
| 2847 | /// 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] | 2848 | /// the set of instructions that MatchOperationAddr can. |
| 2849 | static bool MightBeFoldableInst(Instruction *I) { |
| 2850 | switch (I->getOpcode()) { |
| 2851 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 2852 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2853 | // Don't touch identity bitcasts. |
| 2854 | if (I->getType() == I->getOperand(0)->getType()) |
| 2855 | return false; |
| 2856 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 2857 | case Instruction::PtrToInt: |
| 2858 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2859 | return true; |
| 2860 | case Instruction::IntToPtr: |
| 2861 | // We know the input is intptr_t, so this is foldable. |
| 2862 | return true; |
| 2863 | case Instruction::Add: |
| 2864 | return true; |
| 2865 | case Instruction::Mul: |
| 2866 | case Instruction::Shl: |
| 2867 | // Can only handle X*C and X << C. |
| 2868 | return isa<ConstantInt>(I->getOperand(1)); |
| 2869 | case Instruction::GetElementPtr: |
| 2870 | return true; |
| 2871 | default: |
| 2872 | return false; |
| 2873 | } |
| 2874 | } |
| 2875 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2876 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 2877 | /// \note \p Val is assumed to be the product of some type promotion. |
| 2878 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 2879 | /// 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] | 2880 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 2881 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2882 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 2883 | if (!PromotedInst) |
| 2884 | return false; |
| 2885 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 2886 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 2887 | if (!ISDOpcode) |
| 2888 | return true; |
| 2889 | // Otherwise, check if the promoted instruction is legal or not. |
| 2890 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2891 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2892 | } |
| 2893 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2894 | /// \brief Hepler class to perform type promotion. |
| 2895 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2896 | /// \brief Utility function to check whether or not a sign or zero extension |
| 2897 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 2898 | /// either using the operands of \p Inst or promoting \p Inst. |
| 2899 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2900 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2901 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2902 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2903 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2904 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2905 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2906 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2907 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 2908 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2909 | |
| 2910 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 2911 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2912 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 2913 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2914 | } |
| 2915 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2916 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2917 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2918 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2919 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2920 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2921 | /// Newly added extensions are inserted in \p Exts. |
| 2922 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2923 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2924 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2925 | static Value *promoteOperandForTruncAndAnyExt( |
| 2926 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2927 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2928 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2929 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2930 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2931 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2932 | /// operand is promotable and is not a supported trunc or sext. |
| 2933 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2934 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2935 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2936 | /// Newly added extensions are inserted in \p Exts. |
| 2937 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2938 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2939 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2940 | static Value *promoteOperandForOther(Instruction *Ext, |
| 2941 | TypePromotionTransaction &TPT, |
| 2942 | InstrToOrigTy &PromotedInsts, |
| 2943 | unsigned &CreatedInstsCost, |
| 2944 | SmallVectorImpl<Instruction *> *Exts, |
| 2945 | SmallVectorImpl<Instruction *> *Truncs, |
| 2946 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2947 | |
| 2948 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2949 | static Value *signExtendOperandForOther( |
| 2950 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2951 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2952 | SmallVectorImpl<Instruction *> *Exts, |
| 2953 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2954 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2955 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2956 | } |
| 2957 | |
| 2958 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2959 | static Value *zeroExtendOperandForOther( |
| 2960 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2961 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2962 | SmallVectorImpl<Instruction *> *Exts, |
| 2963 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2964 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2965 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2966 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2967 | |
| 2968 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2969 | /// Type for the utility function that promotes the operand of Ext. |
| 2970 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2971 | InstrToOrigTy &PromotedInsts, |
| 2972 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2973 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2974 | SmallVectorImpl<Instruction *> *Truncs, |
| 2975 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2976 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 2977 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2978 | /// \return NULL if no promotable action is possible with the current |
| 2979 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2980 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 2981 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2982 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 2983 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 2984 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2985 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2986 | const TargetLowering &TLI, |
| 2987 | const InstrToOrigTy &PromotedInsts); |
| 2988 | }; |
| 2989 | |
| 2990 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2991 | Type *ConsideredExtType, |
| 2992 | const InstrToOrigTy &PromotedInsts, |
| 2993 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2994 | // The promotion helper does not know how to deal with vector types yet. |
| 2995 | // To be able to fix that, we would need to fix the places where we |
| 2996 | // statically extend, e.g., constants and such. |
| 2997 | if (Inst->getType()->isVectorTy()) |
| 2998 | return false; |
| 2999 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3000 | // We can always get through zext. |
| 3001 | if (isa<ZExtInst>(Inst)) |
| 3002 | return true; |
| 3003 | |
| 3004 | // sext(sext) is ok too. |
| 3005 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3006 | return true; |
| 3007 | |
| 3008 | // We can get through binary operator, if it is legal. In other words, the |
| 3009 | // binary operator must have a nuw or nsw flag. |
| 3010 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 3011 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3012 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 3013 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3014 | return true; |
| 3015 | |
| 3016 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3017 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3018 | if (!isa<TruncInst>(Inst)) |
| 3019 | return false; |
| 3020 | |
| 3021 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3022 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3023 | // 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] | 3024 | if (!OpndVal->getType()->isIntegerTy() || |
| 3025 | OpndVal->getType()->getIntegerBitWidth() > |
| 3026 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3027 | return false; |
| 3028 | |
| 3029 | // If the operand of the truncate is not an instruction, we will not have |
| 3030 | // any information on the dropped bits. |
| 3031 | // (Actually we could for constant but it is not worth the extra logic). |
| 3032 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 3033 | if (!Opnd) |
| 3034 | return false; |
| 3035 | |
| 3036 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3037 | // I.e., check that trunc just drops extended bits of the same kind of |
| 3038 | // the extension. |
| 3039 | // #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] | 3040 | const Type *OpndType; |
| 3041 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 3042 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 3043 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3044 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 3045 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3046 | else |
| 3047 | return false; |
| 3048 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3049 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3050 | return Inst->getType()->getIntegerBitWidth() >= |
| 3051 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3052 | } |
| 3053 | |
| 3054 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3055 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3056 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3057 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 3058 | "Unexpected instruction type"); |
| 3059 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 3060 | Type *ExtTy = Ext->getType(); |
| 3061 | bool IsSExt = isa<SExtInst>(Ext); |
| 3062 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3063 | // get through. |
| 3064 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3065 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3066 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3067 | |
| 3068 | // Do not promote if the operand has been added by codegenprepare. |
| 3069 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 3070 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3071 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3072 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3073 | |
| 3074 | // SExt or Trunc instructions. |
| 3075 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3076 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 3077 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3078 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3079 | |
| 3080 | // Regular instruction. |
| 3081 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3082 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3083 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3084 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3085 | } |
| 3086 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3087 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3088 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3089 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3090 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3091 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3092 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 3093 | // get through it and this method should not be called. |
| 3094 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3095 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3096 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3097 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3098 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3099 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3100 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3101 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3102 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 3103 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 3104 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3105 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3106 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3107 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 3108 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3109 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 3110 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3111 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3112 | |
| 3113 | // Remove dead code. |
| 3114 | if (SExtOpnd->use_empty()) |
| 3115 | TPT.eraseInstruction(SExtOpnd); |
| 3116 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3117 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3118 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3119 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3120 | if (ExtInst) { |
| 3121 | if (Exts) |
| 3122 | Exts->push_back(ExtInst); |
| 3123 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 3124 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3125 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3126 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3127 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3128 | // At this point we have: ext ty opnd to ty. |
| 3129 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 3130 | Value *NextVal = ExtInst->getOperand(0); |
| 3131 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3132 | return NextVal; |
| 3133 | } |
| 3134 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3135 | Value *TypePromotionHelper::promoteOperandForOther( |
| 3136 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3137 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3138 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3139 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 3140 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3141 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3142 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3143 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3144 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3145 | if (!ExtOpnd->hasOneUse()) { |
| 3146 | // ExtOpnd will be promoted. |
| 3147 | // 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] | 3148 | // promoted version. |
| 3149 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3150 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3151 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 3152 | ITrunc->removeFromParent(); |
| 3153 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3154 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3155 | if (Truncs) |
| 3156 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3157 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3158 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3159 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3160 | // 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] | 3161 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3162 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3163 | } |
| 3164 | |
| 3165 | // Get through the Instruction: |
| 3166 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3167 | // 2. Replace the uses of Ext by Inst. |
| 3168 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3169 | |
| 3170 | // Remember the original type of the instruction before promotion. |
| 3171 | // 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] | 3172 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 3173 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3174 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3175 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3176 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3177 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3178 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3179 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3180 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3181 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 3182 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3183 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3184 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 3185 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 3186 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3187 | DEBUG(dbgs() << "No need to propagate\n"); |
| 3188 | continue; |
| 3189 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3190 | // Check if we can statically extend the operand. |
| 3191 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3192 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3193 | DEBUG(dbgs() << "Statically extend\n"); |
| 3194 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3195 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3196 | : Cst->getValue().zext(BitWidth); |
| 3197 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3198 | continue; |
| 3199 | } |
| 3200 | // UndefValue are typed, so we have to statically sign extend them. |
| 3201 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3202 | DEBUG(dbgs() << "Statically extend\n"); |
| 3203 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3204 | continue; |
| 3205 | } |
| 3206 | |
| 3207 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3208 | // Check if Ext was reused to extend an operand. |
| 3209 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3210 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3211 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3212 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3213 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3214 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3215 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3216 | continue; |
| 3217 | } |
| 3218 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3219 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3220 | if (Exts) |
| 3221 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3222 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3223 | |
| 3224 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3225 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3226 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3227 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3228 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3229 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3230 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3231 | if (ExtForOpnd == Ext) { |
| 3232 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 3233 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3234 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3235 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3236 | } |
| 3237 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3238 | /// 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] | 3239 | /// \p NewCost gives the cost of extension instructions created by the |
| 3240 | /// promotion. |
| 3241 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3242 | /// plus the number of instructions that have been |
| 3243 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3244 | /// \p PromotedOperand is the value that has been promoted. |
| 3245 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3246 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3247 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 3248 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 3249 | // The cost of the new extensions is greater than the cost of the |
| 3250 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3251 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3252 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3253 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3254 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3255 | return true; |
| 3256 | // The promotion is neutral but it may help folding the sign extension in |
| 3257 | // loads for instance. |
| 3258 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3259 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3260 | } |
| 3261 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3262 | /// 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] | 3263 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3264 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3265 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3266 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3267 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3268 | /// because it has been moved away. |
| 3269 | /// Thus AddrInst must not be added in the matched instructions. |
| 3270 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3271 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3272 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3273 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3274 | unsigned Depth, |
| 3275 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3276 | // Avoid exponential behavior on extremely deep expression trees. |
| 3277 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3278 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3279 | // By default, all matched instructions stay in place. |
| 3280 | if (MovedAway) |
| 3281 | *MovedAway = false; |
| 3282 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3283 | switch (Opcode) { |
| 3284 | case Instruction::PtrToInt: |
| 3285 | // 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] | 3286 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3287 | case Instruction::IntToPtr: { |
| 3288 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3289 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3290 | // 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] | 3291 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3292 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3293 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3294 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3295 | case Instruction::BitCast: |
| 3296 | // BitCast is always a noop, and we can handle it as long as it is |
| 3297 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3298 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3299 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3300 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3301 | // and we don't want to mess around with them. Assume it knows what it |
| 3302 | // is doing. |
| 3303 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3304 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3305 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3306 | case Instruction::AddrSpaceCast: { |
| 3307 | unsigned SrcAS |
| 3308 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3309 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3310 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3311 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3312 | return false; |
| 3313 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3314 | case Instruction::Add: { |
| 3315 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3316 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3317 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3318 | // Start a transaction at this point. |
| 3319 | // The LHS may match but not the RHS. |
| 3320 | // Therefore, we need a higher level restoration point to undo partially |
| 3321 | // matched operation. |
| 3322 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3323 | TPT.getRestorationPoint(); |
| 3324 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3325 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3326 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3327 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3328 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3329 | // Restore the old addr mode info. |
| 3330 | AddrMode = BackupAddrMode; |
| 3331 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3332 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3333 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3334 | // 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] | 3335 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3336 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3337 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3338 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3339 | // Otherwise we definitely can't merge the ADD in. |
| 3340 | AddrMode = BackupAddrMode; |
| 3341 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3342 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3343 | break; |
| 3344 | } |
| 3345 | //case Instruction::Or: |
| 3346 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3347 | //break; |
| 3348 | case Instruction::Mul: |
| 3349 | case Instruction::Shl: { |
| 3350 | // Can only handle X*C and X << C. |
| 3351 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3352 | if (!RHS) |
| 3353 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3354 | int64_t Scale = RHS->getSExtValue(); |
| 3355 | if (Opcode == Instruction::Shl) |
| 3356 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3357 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3358 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3359 | } |
| 3360 | case Instruction::GetElementPtr: { |
| 3361 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3362 | // one variable offset. |
| 3363 | int VariableOperand = -1; |
| 3364 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3365 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3366 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3367 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3368 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 3369 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3370 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3371 | unsigned Idx = |
| 3372 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3373 | ConstantOffset += SL->getElementOffset(Idx); |
| 3374 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3375 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3376 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3377 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3378 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3379 | // We only allow one variable index at the moment. |
| 3380 | if (VariableOperand != -1) |
| 3381 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3382 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3383 | // Remember the variable index. |
| 3384 | VariableOperand = i; |
| 3385 | VariableScale = TypeSize; |
| 3386 | } |
| 3387 | } |
| 3388 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3389 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3390 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3391 | // just add it to the disp field and check validity. |
| 3392 | if (VariableOperand == -1) { |
| 3393 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3394 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3395 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3396 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3397 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3398 | return true; |
| 3399 | } |
| 3400 | AddrMode.BaseOffs -= ConstantOffset; |
| 3401 | return false; |
| 3402 | } |
| 3403 | |
| 3404 | // Save the valid addressing mode in case we can't match. |
| 3405 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3406 | unsigned OldSize = AddrModeInsts.size(); |
| 3407 | |
| 3408 | // See if the scale and offset amount is valid for this target. |
| 3409 | AddrMode.BaseOffs += ConstantOffset; |
| 3410 | |
| 3411 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3412 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3413 | // If it couldn't be matched, just stuff the value in a register. |
| 3414 | if (AddrMode.HasBaseReg) { |
| 3415 | AddrMode = BackupAddrMode; |
| 3416 | AddrModeInsts.resize(OldSize); |
| 3417 | return false; |
| 3418 | } |
| 3419 | AddrMode.HasBaseReg = true; |
| 3420 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3421 | } |
| 3422 | |
| 3423 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3424 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3425 | Depth)) { |
| 3426 | // If it couldn't be matched, try stuffing the base into a register |
| 3427 | // instead of matching it, and retrying the match of the scale. |
| 3428 | AddrMode = BackupAddrMode; |
| 3429 | AddrModeInsts.resize(OldSize); |
| 3430 | if (AddrMode.HasBaseReg) |
| 3431 | return false; |
| 3432 | AddrMode.HasBaseReg = true; |
| 3433 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3434 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3435 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3436 | VariableScale, Depth)) { |
| 3437 | // If even that didn't work, bail. |
| 3438 | AddrMode = BackupAddrMode; |
| 3439 | AddrModeInsts.resize(OldSize); |
| 3440 | return false; |
| 3441 | } |
| 3442 | } |
| 3443 | |
| 3444 | return true; |
| 3445 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3446 | case Instruction::SExt: |
| 3447 | case Instruction::ZExt: { |
| 3448 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3449 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3450 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3451 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3452 | // 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] | 3453 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3454 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3455 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3456 | if (!TPH) |
| 3457 | return false; |
| 3458 | |
| 3459 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3460 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3461 | unsigned CreatedInstsCost = 0; |
| 3462 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3463 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3464 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3465 | // SExt has been moved away. |
| 3466 | // Thus either it will be rematched later in the recursive calls or it is |
| 3467 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3468 | // E.g., |
| 3469 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3470 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3471 | // addr = gep base, idx |
| 3472 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3473 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3474 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3475 | // addr = gep base, op <- match |
| 3476 | if (MovedAway) |
| 3477 | *MovedAway = true; |
| 3478 | |
| 3479 | assert(PromotedOperand && |
| 3480 | "TypePromotionHelper should have filtered out those cases"); |
| 3481 | |
| 3482 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3483 | unsigned OldSize = AddrModeInsts.size(); |
| 3484 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3485 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3486 | // 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] | 3487 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3488 | // 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] | 3489 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3490 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3491 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3492 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3493 | AddrMode = BackupAddrMode; |
| 3494 | AddrModeInsts.resize(OldSize); |
| 3495 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3496 | TPT.rollback(LastKnownGood); |
| 3497 | return false; |
| 3498 | } |
| 3499 | return true; |
| 3500 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3501 | } |
| 3502 | return false; |
| 3503 | } |
| 3504 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3505 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3506 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3507 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3508 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3509 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3510 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3511 | // Start a transaction at this point that we will rollback if the matching |
| 3512 | // fails. |
| 3513 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3514 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3515 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 3516 | // Fold in immediates if legal for the target. |
| 3517 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3518 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3519 | return true; |
| 3520 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 3521 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 3522 | // 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] | 3523 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3524 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3525 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3526 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3527 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3528 | } |
| 3529 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 3530 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3531 | unsigned OldSize = AddrModeInsts.size(); |
| 3532 | |
| 3533 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3534 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3535 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3536 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3537 | // to check here. |
| 3538 | if (MovedAway) |
| 3539 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3540 | // Okay, it's possible to fold this. Check to see if it is actually |
| 3541 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 3542 | // register pressure too much. |
| 3543 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3544 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3545 | AddrModeInsts.push_back(I); |
| 3546 | return true; |
| 3547 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3548 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3549 | // It isn't profitable to do this, roll back. |
| 3550 | //cerr << "NOT FOLDING: " << *I; |
| 3551 | AddrMode = BackupAddrMode; |
| 3552 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3553 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3554 | } |
| 3555 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3556 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3557 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3558 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3559 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 3560 | // Null pointer gets folded without affecting the addressing mode. |
| 3561 | return true; |
| 3562 | } |
| 3563 | |
| 3564 | // Worse case, the target should support [reg] addressing modes. :) |
| 3565 | if (!AddrMode.HasBaseReg) { |
| 3566 | AddrMode.HasBaseReg = true; |
| 3567 | AddrMode.BaseReg = Addr; |
| 3568 | // 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] | 3569 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3570 | return true; |
| 3571 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3572 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3573 | } |
| 3574 | |
| 3575 | // If the base register is already taken, see if we can do [r+r]. |
| 3576 | if (AddrMode.Scale == 0) { |
| 3577 | AddrMode.Scale = 1; |
| 3578 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3579 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3580 | return true; |
| 3581 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3582 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3583 | } |
| 3584 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3585 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3586 | return false; |
| 3587 | } |
| 3588 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3589 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 3590 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3591 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3592 | const TargetMachine &TM) { |
| 3593 | const Function *F = CI->getParent()->getParent(); |
| 3594 | const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering(); |
| 3595 | const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3596 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3597 | TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI, |
| 3598 | ImmutableCallSite(CI)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3599 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3600 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
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 | // Compute the constraint code and ConstraintType to use. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3603 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3604 | |
| 3605 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 3606 | // operand, we can't fold it! |
| 3607 | if (OpInfo.CallOperandVal == OpVal && |
| 3608 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 3609 | !OpInfo.isIndirect)) |
| 3610 | return false; |
| 3611 | } |
| 3612 | |
| 3613 | return true; |
| 3614 | } |
| 3615 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3616 | /// Recursively walk all the uses of I until we find a memory use. |
| 3617 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3618 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3619 | static bool FindAllMemoryUses( |
| 3620 | Instruction *I, |
| 3621 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
| 3622 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3623 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3624 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3625 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3626 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3627 | // If this is an obviously unfoldable instruction, bail out. |
| 3628 | if (!MightBeFoldableInst(I)) |
| 3629 | return true; |
| 3630 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3631 | const bool OptSize = I->getFunction()->optForSize(); |
| 3632 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3633 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3634 | for (Use &U : I->uses()) { |
| 3635 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3636 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3637 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3638 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3639 | continue; |
| 3640 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3641 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3642 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3643 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3644 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 3645 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3646 | continue; |
| 3647 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3648 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3649 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3650 | // If this is a cold call, we can sink the addressing calculation into |
| 3651 | // the cold path. See optimizeCallInst |
| 3652 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 3653 | continue; |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 3654 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3655 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 3656 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3657 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3658 | // If this is a memory operand, we're cool, otherwise bail out. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3659 | if (!IsOperandAMemoryOperand(CI, IA, I, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3660 | return true; |
| 3661 | continue; |
| 3662 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3663 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3664 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3665 | return true; |
| 3666 | } |
| 3667 | |
| 3668 | return false; |
| 3669 | } |
| 3670 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3671 | /// Return true if Val is already known to be live at the use site that we're |
| 3672 | /// folding it into. If so, there is no cost to include it in the addressing |
| 3673 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 3674 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3675 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3676 | Value *KnownLive2) { |
| 3677 | // 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] | 3678 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3679 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3680 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3681 | // All values other than instructions and arguments (e.g. constants) are live. |
| 3682 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3683 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3684 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 3685 | // true because it is just a reference to the stack/frame pointer, which is |
| 3686 | // live for the whole function. |
| 3687 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 3688 | if (AI->isStaticAlloca()) |
| 3689 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3690 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3691 | // Check to see if this value is already used in the memory instruction's |
| 3692 | // block. If so, it's already live into the block at the very least, so we |
| 3693 | // can reasonably fold it. |
| 3694 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 3695 | } |
| 3696 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3697 | /// It is possible for the addressing mode of the machine to fold the specified |
| 3698 | /// instruction into a load or store that ultimately uses it. |
| 3699 | /// However, the specified instruction has multiple uses. |
| 3700 | /// Given this, it may actually increase register pressure to fold it |
| 3701 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3702 | /// |
| 3703 | /// X = ... |
| 3704 | /// Y = X+1 |
| 3705 | /// use(Y) -> nonload/store |
| 3706 | /// Z = Y+1 |
| 3707 | /// load Z |
| 3708 | /// |
| 3709 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 3710 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 3711 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 3712 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 3713 | /// number of computations either. |
| 3714 | /// |
| 3715 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 3716 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 3717 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 3718 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3719 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3720 | ExtAddrMode &AMAfter) { |
| 3721 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3722 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3723 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 3724 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 3725 | // the set of registers referenced by AMAfter and subtract out those |
| 3726 | // referenced by AMBefore: this is the set of values which folding in this |
| 3727 | // address extends the lifetime of. |
| 3728 | // |
| 3729 | // Note that there are only two potential values being referenced here, |
| 3730 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 3731 | // folded immediates). |
| 3732 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3733 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3734 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 3735 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3736 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3737 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3738 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3739 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3740 | |
| 3741 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 3742 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3743 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3744 | return true; |
| 3745 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3746 | // If all uses of this instruction can have the address mode sunk into them, |
| 3747 | // we can remove the addressing mode and effectively trade one live register |
| 3748 | // for another (at worst.) In this context, folding an addressing mode into |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 3749 | // the use is just a particularly nice way of sinking it. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3750 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 3751 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3752 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3753 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3754 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3755 | // Now that we know that all uses of this instruction are part of a chain of |
| 3756 | // computation involving only operations that could theoretically be folded |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3757 | // into a memory use, loop over each of these memory operation uses and see |
| 3758 | // if they could *actually* fold the instruction. The assumption is that |
| 3759 | // addressing modes are cheap and that duplicating the computation involved |
| 3760 | // many times is worthwhile, even on a fastpath. For sinking candidates |
| 3761 | // (i.e. cold call sites), this serves as a way to prevent excessive code |
| 3762 | // growth since most architectures have some reasonable small and fast way to |
| 3763 | // compute an effective address. (i.e LEA on x86) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3764 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 3765 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 3766 | Instruction *User = MemoryUses[i].first; |
| 3767 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3768 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3769 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 3770 | // know what it accesses. |
| 3771 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3772 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 3773 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3774 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3775 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 3776 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3777 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3778 | // Do a match against the root of this address, ignoring profitability. This |
| 3779 | // will tell us if the addressing mode for the memory operation will |
| 3780 | // *actually* cover the shared instruction. |
| 3781 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3782 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3783 | TPT.getRestorationPoint(); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3784 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3785 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3786 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3787 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3788 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3789 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3790 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3791 | // The match was to check the profitability, the changes made are not |
| 3792 | // part of the original matcher. Therefore, they should be dropped |
| 3793 | // otherwise the original matcher will not present the right state. |
| 3794 | TPT.rollback(LastKnownGood); |
| 3795 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3796 | // If the match didn't cover I, then it won't be shared by it. |
David Majnemer | 0d955d0 | 2016-08-11 22:21:41 +0000 | [diff] [blame] | 3797 | if (!is_contained(MatchedAddrModeInsts, I)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3798 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3799 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3800 | MatchedAddrModeInsts.clear(); |
| 3801 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3802 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3803 | return true; |
| 3804 | } |
| 3805 | |
| 3806 | } // end anonymous namespace |
| 3807 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3808 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3809 | /// different basic block than BB. |
| 3810 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 3811 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 3812 | return I->getParent() != BB; |
| 3813 | return false; |
| 3814 | } |
| 3815 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3816 | /// Sink addressing mode computation immediate before MemoryInst if doing so |
| 3817 | /// can be done without increasing register pressure. The need for the |
| 3818 | /// register pressure constraint means this can end up being an all or nothing |
| 3819 | /// decision for all uses of the same addressing computation. |
| 3820 | /// |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3821 | /// Load and Store Instructions often have addressing modes that can do |
| 3822 | /// significant amounts of computation. As such, instruction selection will try |
| 3823 | /// to get the load or store to do as much computation as possible for the |
| 3824 | /// program. The problem is that isel can only see within a single block. As |
| 3825 | /// 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] | 3826 | /// |
| 3827 | /// This method is used to optimize both load/store and inline asms with memory |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3828 | /// operands. It's also used to sink addressing computations feeding into cold |
| 3829 | /// call sites into their (cold) basic block. |
| 3830 | /// |
| 3831 | /// The motivation for handling sinking into cold blocks is that doing so can |
| 3832 | /// both enable other address mode sinking (by satisfying the register pressure |
| 3833 | /// constraint above), and reduce register pressure globally (by removing the |
| 3834 | /// addressing mode computation from the fast path entirely.). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3835 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3836 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3837 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3838 | |
| 3839 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3840 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 3841 | SmallVector<Value*, 8> worklist; |
| 3842 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3843 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3844 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3845 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 3846 | // the addressing mode obtained from the non-PHI roots of the graph |
| 3847 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3848 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3849 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3850 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3851 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 3852 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3853 | TypePromotionTransaction TPT; |
| 3854 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3855 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3856 | while (!worklist.empty()) { |
| 3857 | Value *V = worklist.back(); |
| 3858 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3859 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3860 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3861 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3862 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3863 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3864 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3865 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3866 | // For a PHI node, push all of its incoming values. |
| 3867 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 3868 | for (Value *IncValue : P->incoming_values()) |
| 3869 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3870 | continue; |
| 3871 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3872 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3873 | // For non-PHIs, determine the addressing mode being computed. Note that |
| 3874 | // the result may differ depending on what other uses our candidate |
| 3875 | // addressing instructions might have. |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3876 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3877 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3878 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3879 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3880 | |
| 3881 | // This check is broken into two cases with very similar code to avoid using |
| 3882 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 3883 | // calling getNumUses() unconditionally caused a significant compile-time |
| 3884 | // regression. |
| 3885 | if (!Consensus) { |
| 3886 | Consensus = V; |
| 3887 | AddrMode = NewAddrMode; |
| 3888 | AddrModeInsts = NewAddrModeInsts; |
| 3889 | continue; |
| 3890 | } else if (NewAddrMode == AddrMode) { |
| 3891 | if (!IsNumUsesConsensusValid) { |
| 3892 | NumUsesConsensus = Consensus->getNumUses(); |
| 3893 | IsNumUsesConsensusValid = true; |
| 3894 | } |
| 3895 | |
| 3896 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 3897 | // for all other roots of the PHI traversal. Also, when choosing one |
| 3898 | // such root as representative, select the one with the most uses in order |
| 3899 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 3900 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3901 | unsigned NumUses = V->getNumUses(); |
| 3902 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3903 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3904 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3905 | AddrModeInsts = NewAddrModeInsts; |
| 3906 | } |
| 3907 | continue; |
| 3908 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3909 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3910 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3911 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3912 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3913 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3914 | // If the addressing mode couldn't be determined, or if multiple different |
| 3915 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3916 | if (!Consensus) { |
| 3917 | TPT.rollback(LastKnownGood); |
| 3918 | return false; |
| 3919 | } |
| 3920 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3921 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3922 | // If all the instructions matched are already in this BB, don't do anything. |
Justin Lebar | 838c7f5 | 2016-11-21 22:49:11 +0000 | [diff] [blame] | 3923 | if (none_of(AddrModeInsts, [&](Value *V) { |
| 3924 | return IsNonLocalValue(V, MemoryInst->getParent()); |
| 3925 | })) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3926 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3927 | return false; |
| 3928 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3929 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3930 | // Insert this computation right after this user. Since our caller is |
| 3931 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 3932 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3933 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3934 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3935 | // Now that we determined the addressing expression we want to use and know |
| 3936 | // that we have to sink it into this block. Check to see if we have already |
| 3937 | // done this for some other load/store instr in this block. If so, reuse the |
| 3938 | // computation. |
| 3939 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 3940 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3941 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3942 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3943 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 3944 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 3945 | } else if (AddrSinkUsingGEPs || |
| 3946 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Eric Christopher | 2c63549 | 2015-01-27 07:54:39 +0000 | [diff] [blame] | 3947 | TM->getSubtargetImpl(*MemoryInst->getParent()->getParent()) |
| 3948 | ->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3949 | // By default, we use the GEP-based method when AA is used later. This |
| 3950 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 3951 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3952 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3953 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3954 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3955 | |
| 3956 | // First, find the pointer. |
| 3957 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 3958 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3959 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3960 | } |
| 3961 | |
| 3962 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 3963 | // We can't add more than one pointer together, nor can we scale a |
| 3964 | // pointer (both of which seem meaningless). |
| 3965 | if (ResultPtr || AddrMode.Scale != 1) |
| 3966 | return false; |
| 3967 | |
| 3968 | ResultPtr = AddrMode.ScaledReg; |
| 3969 | AddrMode.Scale = 0; |
| 3970 | } |
| 3971 | |
| 3972 | if (AddrMode.BaseGV) { |
| 3973 | if (ResultPtr) |
| 3974 | return false; |
| 3975 | |
| 3976 | ResultPtr = AddrMode.BaseGV; |
| 3977 | } |
| 3978 | |
| 3979 | // If the real base value actually came from an inttoptr, then the matcher |
| 3980 | // will look through it and provide only the integer value. In that case, |
| 3981 | // use it here. |
| 3982 | if (!ResultPtr && AddrMode.BaseReg) { |
| 3983 | ResultPtr = |
| 3984 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3985 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3986 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 3987 | ResultPtr = |
| 3988 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 3989 | AddrMode.Scale = 0; |
| 3990 | } |
| 3991 | |
| 3992 | if (!ResultPtr && |
| 3993 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 3994 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 3995 | } else if (!ResultPtr) { |
| 3996 | return false; |
| 3997 | } else { |
| 3998 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3999 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 4000 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4001 | |
| 4002 | // Start with the base register. Do this first so that subsequent address |
| 4003 | // matching finds it last, which will prevent it from trying to match it |
| 4004 | // as the scaled value in case it happens to be a mul. That would be |
| 4005 | // problematic if we've sunk a different mul for the scale, because then |
| 4006 | // we'd end up sinking both muls. |
| 4007 | if (AddrMode.BaseReg) { |
| 4008 | Value *V = AddrMode.BaseReg; |
| 4009 | if (V->getType() != IntPtrTy) |
| 4010 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 4011 | |
| 4012 | ResultIndex = V; |
| 4013 | } |
| 4014 | |
| 4015 | // Add the scale value. |
| 4016 | if (AddrMode.Scale) { |
| 4017 | Value *V = AddrMode.ScaledReg; |
| 4018 | if (V->getType() == IntPtrTy) { |
| 4019 | // done. |
| 4020 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4021 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 4022 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 4023 | } else { |
| 4024 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4025 | // required to create it did not overflow before we extend it. Since |
| 4026 | // the original IR value was tossed in favor of a constant back when |
| 4027 | // the AddrMode was created we need to bail out gracefully if widths |
| 4028 | // do not match instead of extending it. |
| 4029 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 4030 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 4031 | I->eraseFromParent(); |
| 4032 | return false; |
| 4033 | } |
| 4034 | |
| 4035 | if (AddrMode.Scale != 1) |
| 4036 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4037 | "sunkaddr"); |
| 4038 | if (ResultIndex) |
| 4039 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 4040 | else |
| 4041 | ResultIndex = V; |
| 4042 | } |
| 4043 | |
| 4044 | // Add in the Base Offset if present. |
| 4045 | if (AddrMode.BaseOffs) { |
| 4046 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 4047 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 4048 | // We need to add this separately from the scale above to help with |
| 4049 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4050 | if (ResultPtr->getType() != I8PtrTy) |
| 4051 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4052 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4053 | } |
| 4054 | |
| 4055 | ResultIndex = V; |
| 4056 | } |
| 4057 | |
| 4058 | if (!ResultIndex) { |
| 4059 | SunkAddr = ResultPtr; |
| 4060 | } else { |
| 4061 | if (ResultPtr->getType() != I8PtrTy) |
| 4062 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4063 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4064 | } |
| 4065 | |
| 4066 | if (SunkAddr->getType() != Addr->getType()) |
| 4067 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 4068 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4069 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4070 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4071 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4072 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4073 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4074 | |
| 4075 | // Start with the base register. Do this first so that subsequent address |
| 4076 | // matching finds it last, which will prevent it from trying to match it |
| 4077 | // as the scaled value in case it happens to be a mul. That would be |
| 4078 | // problematic if we've sunk a different mul for the scale, because then |
| 4079 | // we'd end up sinking both muls. |
| 4080 | if (AddrMode.BaseReg) { |
| 4081 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4082 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4083 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4084 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4085 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4086 | Result = V; |
| 4087 | } |
| 4088 | |
| 4089 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4090 | if (AddrMode.Scale) { |
| 4091 | Value *V = AddrMode.ScaledReg; |
| 4092 | if (V->getType() == IntPtrTy) { |
| 4093 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4094 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4095 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4096 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4097 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4098 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4099 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4100 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4101 | // required to create it did not overflow before we extend it. Since |
| 4102 | // the original IR value was tossed in favor of a constant back when |
| 4103 | // the AddrMode was created we need to bail out gracefully if widths |
| 4104 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 4105 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 4106 | if (I && (Result != AddrMode.BaseReg)) |
| 4107 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4108 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4109 | } |
| 4110 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4111 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4112 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4113 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4114 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4115 | else |
| 4116 | Result = V; |
| 4117 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4118 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4119 | // Add in the BaseGV if present. |
| 4120 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4121 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4122 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4123 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4124 | else |
| 4125 | Result = V; |
| 4126 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4127 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4128 | // Add in the Base Offset if present. |
| 4129 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4130 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4131 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4132 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4133 | else |
| 4134 | Result = V; |
| 4135 | } |
| 4136 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4137 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 4138 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4139 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4140 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4141 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4142 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4143 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4144 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4145 | // If we have no uses, recursively delete the value and all dead instructions |
| 4146 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4147 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4148 | // This can cause recursive deletion, which can invalidate our iterator. |
| 4149 | // Use a WeakVH to hold onto it in case this happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4150 | Value *CurValue = &*CurInstIterator; |
| 4151 | WeakVH IterHandle(CurValue); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4152 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4153 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 4154 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4155 | |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4156 | if (IterHandle != CurValue) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4157 | // If the iterator instruction was recursively deleted, start over at the |
| 4158 | // start of the block. |
| 4159 | CurInstIterator = BB->begin(); |
| 4160 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4161 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 4162 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4163 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4164 | return true; |
| 4165 | } |
| 4166 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4167 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 4168 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4169 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4170 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4171 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4172 | const TargetRegisterInfo *TRI = |
| 4173 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4174 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 4175 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4176 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 4177 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4178 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4179 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4180 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 4181 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4182 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 4183 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 4184 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4185 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4186 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4187 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 4188 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4189 | } |
| 4190 | |
| 4191 | return MadeChange; |
| 4192 | } |
| 4193 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4194 | /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or |
| 4195 | /// sign extensions. |
| 4196 | static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) { |
| 4197 | assert(!Inst->use_empty() && "Input must have at least one use"); |
| 4198 | const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin()); |
| 4199 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 4200 | Type *ExtTy = FirstUser->getType(); |
| 4201 | for (const User *U : Inst->users()) { |
| 4202 | const Instruction *UI = cast<Instruction>(U); |
| 4203 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4204 | return false; |
| 4205 | Type *CurTy = UI->getType(); |
| 4206 | // Same input and output types: Same instruction after CSE. |
| 4207 | if (CurTy == ExtTy) |
| 4208 | continue; |
| 4209 | |
| 4210 | // If IsSExt is true, we are in this situation: |
| 4211 | // a = Inst |
| 4212 | // b = sext ty1 a to ty2 |
| 4213 | // c = sext ty1 a to ty3 |
| 4214 | // Assuming ty2 is shorter than ty3, this could be turned into: |
| 4215 | // a = Inst |
| 4216 | // b = sext ty1 a to ty2 |
| 4217 | // c = sext ty2 b to ty3 |
| 4218 | // However, the last sext is not free. |
| 4219 | if (IsSExt) |
| 4220 | return false; |
| 4221 | |
| 4222 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4223 | // In that case, we would not account for a different use. |
| 4224 | Type *NarrowTy; |
| 4225 | Type *LargeTy; |
| 4226 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4227 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4228 | NarrowTy = CurTy; |
| 4229 | LargeTy = ExtTy; |
| 4230 | } else { |
| 4231 | NarrowTy = ExtTy; |
| 4232 | LargeTy = CurTy; |
| 4233 | } |
| 4234 | |
| 4235 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4236 | return false; |
| 4237 | } |
| 4238 | // All uses are the same or can be derived from one another for free. |
| 4239 | return true; |
| 4240 | } |
| 4241 | |
| 4242 | /// \brief Try to form ExtLd by promoting \p Exts until they reach a |
| 4243 | /// load instruction. |
| 4244 | /// If an ext(load) can be formed, it is returned via \p LI for the load |
| 4245 | /// and \p Inst for the extension. |
| 4246 | /// Otherwise LI == nullptr and Inst == nullptr. |
| 4247 | /// When some promotion happened, \p TPT contains the proper state to |
| 4248 | /// revert them. |
| 4249 | /// |
| 4250 | /// \return true when promoting was necessary to expose the ext(load) |
| 4251 | /// opportunity, false otherwise. |
| 4252 | /// |
| 4253 | /// Example: |
| 4254 | /// \code |
| 4255 | /// %ld = load i32* %addr |
| 4256 | /// %add = add nuw i32 %ld, 4 |
| 4257 | /// %zext = zext i32 %add to i64 |
| 4258 | /// \endcode |
| 4259 | /// => |
| 4260 | /// \code |
| 4261 | /// %ld = load i32* %addr |
| 4262 | /// %zext = zext i32 %ld to i64 |
| 4263 | /// %add = add nuw i64 %zext, 4 |
| 4264 | /// \encode |
| 4265 | /// Thanks to the promotion, we can match zext(load i32*) to i64. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4266 | bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4267 | LoadInst *&LI, Instruction *&Inst, |
| 4268 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4269 | unsigned CreatedInstsCost = 0) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4270 | // Iterate over all the extensions to see if one form an ext(load). |
| 4271 | for (auto I : Exts) { |
| 4272 | // Check if we directly have ext(load). |
| 4273 | if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) { |
| 4274 | Inst = I; |
| 4275 | // No promotion happened here. |
| 4276 | return false; |
| 4277 | } |
| 4278 | // Check whether or not we want to do any promotion. |
| 4279 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
| 4280 | continue; |
| 4281 | // Get the action to perform the promotion. |
| 4282 | TypePromotionHelper::Action TPH = TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4283 | I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4284 | // Check if we can promote. |
| 4285 | if (!TPH) |
| 4286 | continue; |
| 4287 | // Save the current state. |
| 4288 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4289 | TPT.getRestorationPoint(); |
| 4290 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4291 | unsigned NewCreatedInstsCost = 0; |
| 4292 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4293 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4294 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4295 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4296 | assert(PromotedVal && |
| 4297 | "TypePromotionHelper should have filtered out those cases"); |
| 4298 | |
| 4299 | // We would be able to merge only one extension in a load. |
| 4300 | // Therefore, if we have more than 1 new extension we heuristically |
| 4301 | // cut this search path, because it means we degrade the code quality. |
| 4302 | // With exactly 2, the transformation is neutral, because we will merge |
| 4303 | // one extension but leave one. However, we optimistically keep going, |
| 4304 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4305 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
| 4306 | TotalCreatedInstsCost -= ExtCost; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4307 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4308 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4309 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4310 | // The promotion is not profitable, rollback to the previous state. |
| 4311 | TPT.rollback(LastKnownGood); |
| 4312 | continue; |
| 4313 | } |
| 4314 | // The promotion is profitable. |
| 4315 | // Check if it exposes an ext(load). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4316 | (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4317 | if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4318 | // If we have created a new extension, i.e., now we have two |
| 4319 | // extensions. We must make sure one of them is merged with |
| 4320 | // the load, otherwise we may degrade the code quality. |
| 4321 | (LI->hasOneUse() || hasSameExtUse(LI, *TLI)))) |
| 4322 | // Promotion happened. |
| 4323 | return true; |
| 4324 | // If this does not help to expose an ext(load) then, rollback. |
| 4325 | TPT.rollback(LastKnownGood); |
| 4326 | } |
| 4327 | // None of the extension can form an ext(load). |
| 4328 | LI = nullptr; |
| 4329 | Inst = nullptr; |
| 4330 | return false; |
| 4331 | } |
| 4332 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4333 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4334 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4335 | /// extend into the load. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4336 | /// \p I[in/out] the extension may be modified during the process if some |
| 4337 | /// promotions apply. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4338 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4339 | bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) { |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 4340 | // ExtLoad formation infrastructure requires TLI to be effective. |
| 4341 | if (!TLI) |
| 4342 | return false; |
| 4343 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4344 | // Try to promote a chain of computation if it allows to form |
| 4345 | // an extended load. |
| 4346 | TypePromotionTransaction TPT; |
| 4347 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4348 | TPT.getRestorationPoint(); |
| 4349 | SmallVector<Instruction *, 1> Exts; |
| 4350 | Exts.push_back(I); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4351 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4352 | LoadInst *LI = nullptr; |
| 4353 | Instruction *OldExt = I; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4354 | bool HasPromoted = extLdPromotion(TPT, LI, I, Exts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4355 | if (!LI || !I) { |
| 4356 | assert(!HasPromoted && !LI && "If we did not match any load instruction " |
| 4357 | "the code must remain the same"); |
| 4358 | I = OldExt; |
| 4359 | return false; |
| 4360 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4361 | |
| 4362 | // 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] | 4363 | // Make the cheap checks first if we did not promote. |
| 4364 | // If we promoted, we need to check if it is indeed profitable. |
| 4365 | if (!HasPromoted && LI->getParent() == I->getParent()) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4366 | return false; |
| 4367 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4368 | EVT VT = TLI->getValueType(*DL, I->getType()); |
| 4369 | EVT LoadVT = TLI->getValueType(*DL, LI->getType()); |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4370 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4371 | // If the load has other users and the truncate is not free, this probably |
| 4372 | // isn't worthwhile. |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 4373 | if (!LI->hasOneUse() && |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4374 | (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4375 | !TLI->isTruncateFree(I->getType(), LI->getType())) { |
| 4376 | I = OldExt; |
| 4377 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4378 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4379 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4380 | |
| 4381 | // Check whether the target supports casts folded into loads. |
| 4382 | unsigned LType; |
| 4383 | if (isa<ZExtInst>(I)) |
| 4384 | LType = ISD::ZEXTLOAD; |
| 4385 | else { |
| 4386 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 4387 | LType = ISD::SEXTLOAD; |
| 4388 | } |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 4389 | if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4390 | I = OldExt; |
| 4391 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4392 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4393 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4394 | |
| 4395 | // Move the extend into the same block as the load, so that SelectionDAG |
| 4396 | // can fold it. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4397 | TPT.commit(); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4398 | I->removeFromParent(); |
| 4399 | I->insertAfter(LI); |
Andrea Di Biagio | fa90c69 | 2016-10-17 11:32:26 +0000 | [diff] [blame] | 4400 | // CGP does not check if the zext would be speculatively executed when moved |
| 4401 | // to the same basic block as the load. Preserving its original location would |
| 4402 | // pessimize the debugging experience, as well as negatively impact the |
| 4403 | // quality of sample pgo. We don't want to use "line 0" as that has a |
| 4404 | // size cost in the line-table section and logically the zext can be seen as |
| 4405 | // part of the load. Therefore we conservatively reuse the same debug location |
| 4406 | // for the load and the zext. |
| 4407 | I->setDebugLoc(LI->getDebugLoc()); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4408 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4409 | return true; |
| 4410 | } |
| 4411 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4412 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4413 | BasicBlock *DefBB = I->getParent(); |
| 4414 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 4415 | // 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] | 4416 | // other uses of the source with result of extension. |
| 4417 | Value *Src = I->getOperand(0); |
| 4418 | if (Src->hasOneUse()) |
| 4419 | return false; |
| 4420 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 4421 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 4422 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4423 | return false; |
| 4424 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4425 | // 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] | 4426 | // this block. |
| 4427 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4428 | return false; |
| 4429 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4430 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4431 | for (User *U : I->users()) { |
| 4432 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4433 | |
| 4434 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4435 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4436 | if (UserBB == DefBB) continue; |
| 4437 | DefIsLiveOut = true; |
| 4438 | break; |
| 4439 | } |
| 4440 | if (!DefIsLiveOut) |
| 4441 | return false; |
| 4442 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 4443 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4444 | for (User *U : Src->users()) { |
| 4445 | Instruction *UI = cast<Instruction>(U); |
| 4446 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4447 | if (UserBB == DefBB) continue; |
| 4448 | // Be conservative. We don't want this xform to end up introducing |
| 4449 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4450 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4451 | return false; |
| 4452 | } |
| 4453 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4454 | // InsertedTruncs - Only insert one trunc in each block once. |
| 4455 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 4456 | |
| 4457 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4458 | for (Use &U : Src->uses()) { |
| 4459 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4460 | |
| 4461 | // Figure out which BB this ext is used in. |
| 4462 | BasicBlock *UserBB = User->getParent(); |
| 4463 | if (UserBB == DefBB) continue; |
| 4464 | |
| 4465 | // Both src and def are live in this block. Rewrite the use. |
| 4466 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 4467 | |
| 4468 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 4469 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4470 | assert(InsertPt != UserBB->end()); |
| 4471 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4472 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4473 | } |
| 4474 | |
| 4475 | // 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] | 4476 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4477 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4478 | MadeChange = true; |
| 4479 | } |
| 4480 | |
| 4481 | return MadeChange; |
| 4482 | } |
| 4483 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 4484 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 4485 | // just after the load if the target can fold this into one extload instruction, |
| 4486 | // with the hope of eliminating some of the other later "and" instructions using |
| 4487 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 4488 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 4489 | // path from the load goes through a phi) are left for isel to potentially |
| 4490 | // remove. |
| 4491 | // |
| 4492 | // For example: |
| 4493 | // |
| 4494 | // b0: |
| 4495 | // x = load i32 |
| 4496 | // ... |
| 4497 | // b1: |
| 4498 | // y = and x, 0xff |
| 4499 | // z = use y |
| 4500 | // |
| 4501 | // becomes: |
| 4502 | // |
| 4503 | // b0: |
| 4504 | // x = load i32 |
| 4505 | // x' = and x, 0xff |
| 4506 | // ... |
| 4507 | // b1: |
| 4508 | // z = use x' |
| 4509 | // |
| 4510 | // whereas: |
| 4511 | // |
| 4512 | // b0: |
| 4513 | // x1 = load i32 |
| 4514 | // ... |
| 4515 | // b1: |
| 4516 | // x2 = load i32 |
| 4517 | // ... |
| 4518 | // b2: |
| 4519 | // x = phi x1, x2 |
| 4520 | // y = and x, 0xff |
| 4521 | // |
| 4522 | // becomes (after a call to optimizeLoadExt for each load): |
| 4523 | // |
| 4524 | // b0: |
| 4525 | // x1 = load i32 |
| 4526 | // x1' = and x1, 0xff |
| 4527 | // ... |
| 4528 | // b1: |
| 4529 | // x2 = load i32 |
| 4530 | // x2' = and x2, 0xff |
| 4531 | // ... |
| 4532 | // b2: |
| 4533 | // x = phi x1', x2' |
| 4534 | // y = and x, 0xff |
| 4535 | // |
| 4536 | |
| 4537 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
| 4538 | |
| 4539 | if (!Load->isSimple() || |
| 4540 | !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy())) |
| 4541 | return false; |
| 4542 | |
| 4543 | // Skip loads we've already transformed or have no reason to transform. |
| 4544 | if (Load->hasOneUse()) { |
| 4545 | User *LoadUser = *Load->user_begin(); |
| 4546 | if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() && |
| 4547 | !dyn_cast<PHINode>(LoadUser)) |
| 4548 | return false; |
| 4549 | } |
| 4550 | |
| 4551 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 4552 | // of the loaded value are needed. |
| 4553 | SmallVector<Instruction *, 8> WorkList; |
| 4554 | SmallPtrSet<Instruction *, 16> Visited; |
| 4555 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 4556 | for (auto *U : Load->users()) |
| 4557 | WorkList.push_back(cast<Instruction>(U)); |
| 4558 | |
| 4559 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 4560 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 4561 | APInt DemandBits(BitWidth, 0); |
| 4562 | APInt WidestAndBits(BitWidth, 0); |
| 4563 | |
| 4564 | while (!WorkList.empty()) { |
| 4565 | Instruction *I = WorkList.back(); |
| 4566 | WorkList.pop_back(); |
| 4567 | |
| 4568 | // Break use-def graph loops. |
| 4569 | if (!Visited.insert(I).second) |
| 4570 | continue; |
| 4571 | |
| 4572 | // For a PHI node, push all of its users. |
| 4573 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 4574 | for (auto *U : Phi->users()) |
| 4575 | WorkList.push_back(cast<Instruction>(U)); |
| 4576 | continue; |
| 4577 | } |
| 4578 | |
| 4579 | switch (I->getOpcode()) { |
| 4580 | case llvm::Instruction::And: { |
| 4581 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4582 | if (!AndC) |
| 4583 | return false; |
| 4584 | APInt AndBits = AndC->getValue(); |
| 4585 | DemandBits |= AndBits; |
| 4586 | // Keep track of the widest and mask we see. |
| 4587 | if (AndBits.ugt(WidestAndBits)) |
| 4588 | WidestAndBits = AndBits; |
| 4589 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 4590 | AndsToMaybeRemove.push_back(I); |
| 4591 | break; |
| 4592 | } |
| 4593 | |
| 4594 | case llvm::Instruction::Shl: { |
| 4595 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4596 | if (!ShlC) |
| 4597 | return false; |
| 4598 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
| 4599 | auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt); |
| 4600 | DemandBits |= ShlDemandBits; |
| 4601 | break; |
| 4602 | } |
| 4603 | |
| 4604 | case llvm::Instruction::Trunc: { |
| 4605 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 4606 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
| 4607 | auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth); |
| 4608 | DemandBits |= TruncBits; |
| 4609 | break; |
| 4610 | } |
| 4611 | |
| 4612 | default: |
| 4613 | return false; |
| 4614 | } |
| 4615 | } |
| 4616 | |
| 4617 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 4618 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 4619 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 4620 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 4621 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 4622 | // followed by an AND. |
| 4623 | // TODO: Look into removing this restriction by fixing backends to either |
| 4624 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 4625 | // a single instruction. |
| 4626 | // |
| 4627 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 4628 | // mask, since these are the only ands that will be removed by isel. |
| 4629 | if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) || |
| 4630 | WidestAndBits != DemandBits) |
| 4631 | return false; |
| 4632 | |
| 4633 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 4634 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 4635 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 4636 | |
| 4637 | // Reject cases that won't be matched as extloads. |
| 4638 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 4639 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 4640 | return false; |
| 4641 | |
| 4642 | IRBuilder<> Builder(Load->getNextNode()); |
| 4643 | auto *NewAnd = dyn_cast<Instruction>( |
| 4644 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
| 4645 | |
| 4646 | // Replace all uses of load with new and (except for the use of load in the |
| 4647 | // new and itself). |
| 4648 | Load->replaceAllUsesWith(NewAnd); |
| 4649 | NewAnd->setOperand(0, Load); |
| 4650 | |
| 4651 | // Remove any and instructions that are now redundant. |
| 4652 | for (auto *And : AndsToMaybeRemove) |
| 4653 | // Check that the and mask is the same as the one we decided to put on the |
| 4654 | // new and. |
| 4655 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 4656 | And->replaceAllUsesWith(NewAnd); |
| 4657 | if (&*CurInstIterator == And) |
| 4658 | CurInstIterator = std::next(And->getIterator()); |
| 4659 | And->eraseFromParent(); |
| 4660 | ++NumAndUses; |
| 4661 | } |
| 4662 | |
| 4663 | ++NumAndsAdded; |
| 4664 | return true; |
| 4665 | } |
| 4666 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4667 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 4668 | /// that is only used once. |
| 4669 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 4670 | auto *I = dyn_cast<Instruction>(V); |
| 4671 | // If it's safe to speculatively execute, then it should not have side |
| 4672 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 4673 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 4674 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4675 | } |
| 4676 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4677 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4678 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4679 | const TargetLowering *TLI, |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4680 | SelectInst *SI) { |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4681 | // If even a predictable select is cheap, then a branch can't be cheaper. |
| 4682 | if (!TLI->isPredictableSelectExpensive()) |
| 4683 | return false; |
| 4684 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4685 | // FIXME: This should use the same heuristics as IfConversion to determine |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4686 | // whether a select is better represented as a branch. |
| 4687 | |
| 4688 | // If metadata tells us that the select condition is obviously predictable, |
| 4689 | // then we want to replace the select with a branch. |
| 4690 | uint64_t TrueWeight, FalseWeight; |
| 4691 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { |
| 4692 | uint64_t Max = std::max(TrueWeight, FalseWeight); |
| 4693 | uint64_t Sum = TrueWeight + FalseWeight; |
Sanjay Patel | c7b91e6 | 2016-05-09 17:31:55 +0000 | [diff] [blame] | 4694 | if (Sum != 0) { |
| 4695 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); |
| 4696 | if (Probability > TLI->getPredictableBranchThreshold()) |
| 4697 | return true; |
| 4698 | } |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4699 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4700 | |
| 4701 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 4702 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 4703 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 4704 | // comparison condition. If the compare has more than one use, there's |
| 4705 | // 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] | 4706 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4707 | return false; |
| 4708 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4709 | // If either operand of the select is expensive and only needed on one side |
| 4710 | // of the select, we should form a branch. |
| 4711 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 4712 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 4713 | return true; |
| 4714 | |
| 4715 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4716 | } |
| 4717 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4718 | /// If \p isTrue is true, return the true value of \p SI, otherwise return |
| 4719 | /// false value of \p SI. If the true/false value of \p SI is defined by any |
| 4720 | /// select instructions in \p Selects, look through the defining select |
| 4721 | /// instruction until the true/false value is not defined in \p Selects. |
| 4722 | static Value *getTrueOrFalseValue( |
| 4723 | SelectInst *SI, bool isTrue, |
| 4724 | const SmallPtrSet<const Instruction *, 2> &Selects) { |
| 4725 | Value *V; |
| 4726 | |
| 4727 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); |
| 4728 | DefSI = dyn_cast<SelectInst>(V)) { |
Dehao Chen | c32d712 | 2016-09-12 20:29:54 +0000 | [diff] [blame] | 4729 | assert(DefSI->getCondition() == SI->getCondition() && |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4730 | "The condition of DefSI does not match with SI"); |
| 4731 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); |
| 4732 | } |
| 4733 | return V; |
| 4734 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4735 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4736 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 4737 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4738 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4739 | // Find all consecutive select instructions that share the same condition. |
| 4740 | SmallVector<SelectInst *, 2> ASI; |
| 4741 | ASI.push_back(SI); |
| 4742 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); |
| 4743 | It != SI->getParent()->end(); ++It) { |
| 4744 | SelectInst *I = dyn_cast<SelectInst>(&*It); |
| 4745 | if (I && SI->getCondition() == I->getCondition()) { |
| 4746 | ASI.push_back(I); |
| 4747 | } else { |
| 4748 | break; |
| 4749 | } |
| 4750 | } |
| 4751 | |
| 4752 | SelectInst *LastSI = ASI.back(); |
| 4753 | // Increment the current iterator to skip all the rest of select instructions |
| 4754 | // because they will be either "not lowered" or "all lowered" to branch. |
| 4755 | CurInstIterator = std::next(LastSI->getIterator()); |
| 4756 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4757 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 4758 | |
| 4759 | // Can we convert the 'select' to CF ? |
Sanjay Patel | a31b0c0 | 2016-04-26 00:47:39 +0000 | [diff] [blame] | 4760 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond || |
| 4761 | SI->getMetadata(LLVMContext::MD_unpredictable)) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4762 | return false; |
| 4763 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4764 | TargetLowering::SelectSupportKind SelectKind; |
| 4765 | if (VectorCond) |
| 4766 | SelectKind = TargetLowering::VectorMaskSelect; |
| 4767 | else if (SI->getType()->isVectorTy()) |
| 4768 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 4769 | else |
| 4770 | SelectKind = TargetLowering::ScalarValSelect; |
| 4771 | |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4772 | if (TLI->isSelectSupported(SelectKind) && |
| 4773 | !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) |
| 4774 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4775 | |
| 4776 | ModifiedDT = true; |
| 4777 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4778 | // Transform a sequence like this: |
| 4779 | // start: |
| 4780 | // %cmp = cmp uge i32 %a, %b |
| 4781 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 4782 | // |
| 4783 | // Into: |
| 4784 | // start: |
| 4785 | // %cmp = cmp uge i32 %a, %b |
| 4786 | // br i1 %cmp, label %select.true, label %select.false |
| 4787 | // select.true: |
| 4788 | // br label %select.end |
| 4789 | // select.false: |
| 4790 | // br label %select.end |
| 4791 | // select.end: |
| 4792 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 4793 | // |
| 4794 | // In addition, we may sink instructions that produce %c or %d from |
| 4795 | // the entry block into the destination(s) of the new branch. |
| 4796 | // If the true or false blocks do not contain a sunken instruction, that |
| 4797 | // block and its branch may be optimized away. In that case, one side of the |
| 4798 | // first branch will point directly to select.end, and the corresponding PHI |
| 4799 | // predecessor block will be the start block. |
| 4800 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4801 | // First, we split the block containing the select into 2 blocks. |
| 4802 | BasicBlock *StartBlock = SI->getParent(); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4803 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4804 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4805 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4806 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4807 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4808 | |
| 4809 | // These are the new basic blocks for the conditional branch. |
| 4810 | // At least one will become an actual new basic block. |
| 4811 | BasicBlock *TrueBlock = nullptr; |
| 4812 | BasicBlock *FalseBlock = nullptr; |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4813 | BranchInst *TrueBranch = nullptr; |
| 4814 | BranchInst *FalseBranch = nullptr; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4815 | |
| 4816 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 4817 | // them speculatively. |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4818 | for (SelectInst *SI : ASI) { |
| 4819 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 4820 | if (TrueBlock == nullptr) { |
| 4821 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 4822 | EndBlock->getParent(), EndBlock); |
| 4823 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 4824 | } |
| 4825 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 4826 | TrueInst->moveBefore(TrueBranch); |
| 4827 | } |
| 4828 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 4829 | if (FalseBlock == nullptr) { |
| 4830 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 4831 | EndBlock->getParent(), EndBlock); |
| 4832 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 4833 | } |
| 4834 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 4835 | FalseInst->moveBefore(FalseBranch); |
| 4836 | } |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4837 | } |
| 4838 | |
| 4839 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 4840 | // for a new input value to the PHI. |
| 4841 | if (TrueBlock == FalseBlock) { |
| 4842 | assert(TrueBlock == nullptr && |
| 4843 | "Unexpected basic block transform while optimizing select"); |
| 4844 | |
| 4845 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 4846 | EndBlock->getParent(), EndBlock); |
| 4847 | BranchInst::Create(EndBlock, FalseBlock); |
| 4848 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4849 | |
| 4850 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4851 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 4852 | // of the condition, it means that side of the branch goes to the end block |
| 4853 | // directly and the path originates from the start block from the point of |
| 4854 | // view of the new PHI. |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4855 | BasicBlock *TT, *FT; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4856 | if (TrueBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4857 | TT = EndBlock; |
| 4858 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4859 | TrueBlock = StartBlock; |
| 4860 | } else if (FalseBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4861 | TT = TrueBlock; |
| 4862 | FT = EndBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4863 | FalseBlock = StartBlock; |
| 4864 | } else { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4865 | TT = TrueBlock; |
| 4866 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4867 | } |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 4868 | IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4869 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4870 | SmallPtrSet<const Instruction *, 2> INS; |
| 4871 | INS.insert(ASI.begin(), ASI.end()); |
| 4872 | // Use reverse iterator because later select may use the value of the |
| 4873 | // earlier select, and we need to propagate value through earlier select |
| 4874 | // to get the PHI operand. |
| 4875 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { |
| 4876 | SelectInst *SI = *It; |
| 4877 | // The select itself is replaced with a PHI Node. |
| 4878 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
| 4879 | PN->takeName(SI); |
| 4880 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); |
| 4881 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4882 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 4883 | SI->replaceAllUsesWith(PN); |
| 4884 | SI->eraseFromParent(); |
| 4885 | INS.erase(SI); |
| 4886 | ++NumSelectsExpanded; |
| 4887 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4888 | |
| 4889 | // Instruct OptimizeBlock to skip to the next block. |
| 4890 | CurInstIterator = StartBlock->end(); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4891 | return true; |
| 4892 | } |
| 4893 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 4894 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4895 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 4896 | int SplatElem = -1; |
| 4897 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 4898 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 4899 | return false; |
| 4900 | SplatElem = Mask[i]; |
| 4901 | } |
| 4902 | |
| 4903 | return true; |
| 4904 | } |
| 4905 | |
| 4906 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 4907 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 4908 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 4909 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4910 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4911 | BasicBlock *DefBB = SVI->getParent(); |
| 4912 | |
| 4913 | // Only do this xform if variable vector shifts are particularly expensive. |
| 4914 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 4915 | return false; |
| 4916 | |
| 4917 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 4918 | // constant splat. |
| 4919 | if (!isBroadcastShuffle(SVI)) |
| 4920 | return false; |
| 4921 | |
| 4922 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 4923 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 4924 | |
| 4925 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4926 | for (User *U : SVI->users()) { |
| 4927 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4928 | |
| 4929 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4930 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4931 | if (UserBB == DefBB) continue; |
| 4932 | |
| 4933 | // 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] | 4934 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4935 | |
| 4936 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 4937 | // already have a copy. |
| 4938 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 4939 | |
| 4940 | if (!InsertedShuffle) { |
| 4941 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4942 | assert(InsertPt != UserBB->end()); |
| 4943 | InsertedShuffle = |
| 4944 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 4945 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4946 | } |
| 4947 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4948 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4949 | MadeChange = true; |
| 4950 | } |
| 4951 | |
| 4952 | // If we removed all uses, nuke the shuffle. |
| 4953 | if (SVI->use_empty()) { |
| 4954 | SVI->eraseFromParent(); |
| 4955 | MadeChange = true; |
| 4956 | } |
| 4957 | |
| 4958 | return MadeChange; |
| 4959 | } |
| 4960 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 4961 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 4962 | if (!TLI || !DL) |
| 4963 | return false; |
| 4964 | |
| 4965 | Value *Cond = SI->getCondition(); |
| 4966 | Type *OldType = Cond->getType(); |
| 4967 | LLVMContext &Context = Cond->getContext(); |
| 4968 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 4969 | unsigned RegWidth = RegType.getSizeInBits(); |
| 4970 | |
| 4971 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 4972 | return false; |
| 4973 | |
| 4974 | // If the register width is greater than the type width, expand the condition |
| 4975 | // of the switch instruction and each case constant to the width of the |
| 4976 | // register. By widening the type of the switch condition, subsequent |
| 4977 | // comparisons (for case comparisons) will not need to be extended to the |
| 4978 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 4979 | // where N is the number of cases in the switch. |
| 4980 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 4981 | |
| 4982 | // Zero-extend the switch condition and case constants unless the switch |
| 4983 | // condition is a function argument that is already being sign-extended. |
| 4984 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 4985 | // everything instead. |
| 4986 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 4987 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 4988 | if (Arg->hasSExtAttr()) |
| 4989 | ExtType = Instruction::SExt; |
| 4990 | |
| 4991 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 4992 | ExtInst->insertBefore(SI); |
| 4993 | SI->setCondition(ExtInst); |
| 4994 | for (SwitchInst::CaseIt Case : SI->cases()) { |
| 4995 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 4996 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 4997 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 4998 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 4999 | } |
| 5000 | |
| 5001 | return true; |
| 5002 | } |
| 5003 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5004 | namespace { |
| 5005 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 5006 | /// This class is used to move downward extractelement transition. |
| 5007 | /// E.g., |
| 5008 | /// a = vector_op <2 x i32> |
| 5009 | /// b = extractelement <2 x i32> a, i32 0 |
| 5010 | /// c = scalar_op b |
| 5011 | /// store c |
| 5012 | /// |
| 5013 | /// => |
| 5014 | /// a = vector_op <2 x i32> |
| 5015 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 5016 | /// * d = extractelement <2 x i32> c, i32 0 |
| 5017 | /// * store d |
| 5018 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 5019 | /// transition. |
| 5020 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5021 | /// DataLayout associated with the current module. |
| 5022 | const DataLayout &DL; |
| 5023 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5024 | /// Used to perform some checks on the legality of vector operations. |
| 5025 | const TargetLowering &TLI; |
| 5026 | |
| 5027 | /// Used to estimated the cost of the promoted chain. |
| 5028 | const TargetTransformInfo &TTI; |
| 5029 | |
| 5030 | /// The transition being moved downwards. |
| 5031 | Instruction *Transition; |
| 5032 | /// The sequence of instructions to be promoted. |
| 5033 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 5034 | /// Cost of combining a store and an extract. |
| 5035 | unsigned StoreExtractCombineCost; |
| 5036 | /// Instruction that will be combined with the transition. |
| 5037 | Instruction *CombineInst; |
| 5038 | |
| 5039 | /// \brief The instruction that represents the current end of the transition. |
| 5040 | /// Since we are faking the promotion until we reach the end of the chain |
| 5041 | /// of computation, we need a way to get the current end of the transition. |
| 5042 | Instruction *getEndOfTransition() const { |
| 5043 | if (InstsToBePromoted.empty()) |
| 5044 | return Transition; |
| 5045 | return InstsToBePromoted.back(); |
| 5046 | } |
| 5047 | |
| 5048 | /// \brief Return the index of the original value in the transition. |
| 5049 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 5050 | /// c, is at index 0. |
| 5051 | unsigned getTransitionOriginalValueIdx() const { |
| 5052 | assert(isa<ExtractElementInst>(Transition) && |
| 5053 | "Other kind of transitions are not supported yet"); |
| 5054 | return 0; |
| 5055 | } |
| 5056 | |
| 5057 | /// \brief Return the index of the index in the transition. |
| 5058 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 5059 | /// is at index 1. |
| 5060 | unsigned getTransitionIdx() const { |
| 5061 | assert(isa<ExtractElementInst>(Transition) && |
| 5062 | "Other kind of transitions are not supported yet"); |
| 5063 | return 1; |
| 5064 | } |
| 5065 | |
| 5066 | /// \brief Get the type of the transition. |
| 5067 | /// This is the type of the original value. |
| 5068 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 5069 | /// transition is <2 x i32>. |
| 5070 | Type *getTransitionType() const { |
| 5071 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 5072 | } |
| 5073 | |
| 5074 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 5075 | /// I.e., we have the following sequence: |
| 5076 | /// Def = Transition <ty1> a to <ty2> |
| 5077 | /// b = ToBePromoted <ty2> Def, ... |
| 5078 | /// => |
| 5079 | /// b = ToBePromoted <ty1> a, ... |
| 5080 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 5081 | void promoteImpl(Instruction *ToBePromoted); |
| 5082 | |
| 5083 | /// \brief Check whether or not it is profitable to promote all the |
| 5084 | /// instructions enqueued to be promoted. |
| 5085 | bool isProfitableToPromote() { |
| 5086 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5087 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 5088 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 5089 | : -1; |
| 5090 | Type *PromotedType = getTransitionType(); |
| 5091 | |
| 5092 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 5093 | unsigned AS = ST->getPointerAddressSpace(); |
| 5094 | unsigned Align = ST->getAlignment(); |
| 5095 | // Check if this store is supported. |
| 5096 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5097 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 5098 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5099 | // If this is not supported, there is no way we can combine |
| 5100 | // the extract with the store. |
| 5101 | return false; |
| 5102 | } |
| 5103 | |
| 5104 | // The scalar chain of computation has to pay for the transition |
| 5105 | // scalar to vector. |
| 5106 | // The vector chain has to account for the combining cost. |
| 5107 | uint64_t ScalarCost = |
| 5108 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 5109 | uint64_t VectorCost = StoreExtractCombineCost; |
| 5110 | for (const auto &Inst : InstsToBePromoted) { |
| 5111 | // Compute the cost. |
| 5112 | // By construction, all instructions being promoted are arithmetic ones. |
| 5113 | // Moreover, one argument is a constant that can be viewed as a splat |
| 5114 | // constant. |
| 5115 | Value *Arg0 = Inst->getOperand(0); |
| 5116 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 5117 | isa<ConstantFP>(Arg0); |
| 5118 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 5119 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5120 | : TargetTransformInfo::OK_AnyValue; |
| 5121 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 5122 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5123 | : TargetTransformInfo::OK_AnyValue; |
| 5124 | ScalarCost += TTI.getArithmeticInstrCost( |
| 5125 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 5126 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 5127 | Arg0OVK, Arg1OVK); |
| 5128 | } |
| 5129 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 5130 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 5131 | return ScalarCost > VectorCost; |
| 5132 | } |
| 5133 | |
| 5134 | /// \brief Generate a constant vector with \p Val with the same |
| 5135 | /// number of elements as the transition. |
| 5136 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 5137 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5138 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 5139 | /// otherwise we generate a vector with as many undef as possible: |
| 5140 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 5141 | /// used at the index of the extract. |
| 5142 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 5143 | unsigned ExtractIdx = UINT_MAX; |
| 5144 | if (!UseSplat) { |
| 5145 | // If we cannot determine where the constant must be, we have to |
| 5146 | // use a splat constant. |
| 5147 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 5148 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 5149 | ExtractIdx = CstVal->getSExtValue(); |
| 5150 | else |
| 5151 | UseSplat = true; |
| 5152 | } |
| 5153 | |
| 5154 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 5155 | if (UseSplat) |
| 5156 | return ConstantVector::getSplat(End, Val); |
| 5157 | |
| 5158 | SmallVector<Constant *, 4> ConstVec; |
| 5159 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 5160 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 5161 | if (Idx == ExtractIdx) |
| 5162 | ConstVec.push_back(Val); |
| 5163 | else |
| 5164 | ConstVec.push_back(UndefVal); |
| 5165 | } |
| 5166 | return ConstantVector::get(ConstVec); |
| 5167 | } |
| 5168 | |
| 5169 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 5170 | /// in \p Use can trigger undefined behavior. |
| 5171 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 5172 | unsigned OperandIdx) { |
| 5173 | // This is not safe to introduce undef when the operand is on |
| 5174 | // the right hand side of a division-like instruction. |
| 5175 | if (OperandIdx != 1) |
| 5176 | return false; |
| 5177 | switch (Use->getOpcode()) { |
| 5178 | default: |
| 5179 | return false; |
| 5180 | case Instruction::SDiv: |
| 5181 | case Instruction::UDiv: |
| 5182 | case Instruction::SRem: |
| 5183 | case Instruction::URem: |
| 5184 | return true; |
| 5185 | case Instruction::FDiv: |
| 5186 | case Instruction::FRem: |
| 5187 | return !Use->hasNoNaNs(); |
| 5188 | } |
| 5189 | llvm_unreachable(nullptr); |
| 5190 | } |
| 5191 | |
| 5192 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5193 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 5194 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 5195 | unsigned CombineCost) |
| 5196 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5197 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 5198 | assert(Transition && "Do not know how to promote null"); |
| 5199 | } |
| 5200 | |
| 5201 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 5202 | bool canPromote(const Instruction *ToBePromoted) const { |
| 5203 | // We could support CastInst too. |
| 5204 | return isa<BinaryOperator>(ToBePromoted); |
| 5205 | } |
| 5206 | |
| 5207 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 5208 | /// by moving downward the transition through. |
| 5209 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 5210 | // Promote only if all the operands can be statically expanded. |
| 5211 | // Indeed, we do not want to introduce any new kind of transitions. |
| 5212 | for (const Use &U : ToBePromoted->operands()) { |
| 5213 | const Value *Val = U.get(); |
| 5214 | if (Val == getEndOfTransition()) { |
| 5215 | // If the use is a division and the transition is on the rhs, |
| 5216 | // we cannot promote the operation, otherwise we may create a |
| 5217 | // division by zero. |
| 5218 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 5219 | return false; |
| 5220 | continue; |
| 5221 | } |
| 5222 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 5223 | !isa<ConstantFP>(Val)) |
| 5224 | return false; |
| 5225 | } |
| 5226 | // Check that the resulting operation is legal. |
| 5227 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 5228 | if (!ISDOpcode) |
| 5229 | return false; |
| 5230 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 5231 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5232 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5233 | } |
| 5234 | |
| 5235 | /// \brief Check whether or not \p Use can be combined |
| 5236 | /// with the transition. |
| 5237 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 5238 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 5239 | |
| 5240 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 5241 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 5242 | InstsToBePromoted.push_back(ToBePromoted); |
| 5243 | } |
| 5244 | |
| 5245 | /// \brief Set the instruction that will be combined with the transition. |
| 5246 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 5247 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 5248 | CombineInst = ToBeCombined; |
| 5249 | } |
| 5250 | |
| 5251 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 5252 | /// is profitable. |
| 5253 | /// \return True if the promotion happened, false otherwise. |
| 5254 | bool promote() { |
| 5255 | // Check if there is something to promote. |
| 5256 | // Right now, if we do not have anything to combine with, |
| 5257 | // we assume the promotion is not profitable. |
| 5258 | if (InstsToBePromoted.empty() || !CombineInst) |
| 5259 | return false; |
| 5260 | |
| 5261 | // Check cost. |
| 5262 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 5263 | return false; |
| 5264 | |
| 5265 | // Promote. |
| 5266 | for (auto &ToBePromoted : InstsToBePromoted) |
| 5267 | promoteImpl(ToBePromoted); |
| 5268 | InstsToBePromoted.clear(); |
| 5269 | return true; |
| 5270 | } |
| 5271 | }; |
| 5272 | } // End of anonymous namespace. |
| 5273 | |
| 5274 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 5275 | // At this point, we know that all the operands of ToBePromoted but Def |
| 5276 | // can be statically promoted. |
| 5277 | // For Def, we need to use its parameter in ToBePromoted: |
| 5278 | // b = ToBePromoted ty1 a |
| 5279 | // Def = Transition ty1 b to ty2 |
| 5280 | // Move the transition down. |
| 5281 | // 1. Replace all uses of the promoted operation by the transition. |
| 5282 | // = ... b => = ... Def. |
| 5283 | assert(ToBePromoted->getType() == Transition->getType() && |
| 5284 | "The type of the result of the transition does not match " |
| 5285 | "the final type"); |
| 5286 | ToBePromoted->replaceAllUsesWith(Transition); |
| 5287 | // 2. Update the type of the uses. |
| 5288 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 5289 | Type *TransitionTy = getTransitionType(); |
| 5290 | ToBePromoted->mutateType(TransitionTy); |
| 5291 | // 3. Update all the operands of the promoted operation with promoted |
| 5292 | // operands. |
| 5293 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 5294 | for (Use &U : ToBePromoted->operands()) { |
| 5295 | Value *Val = U.get(); |
| 5296 | Value *NewVal = nullptr; |
| 5297 | if (Val == Transition) |
| 5298 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5299 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 5300 | isa<ConstantFP>(Val)) { |
| 5301 | // Use a splat constant if it is not safe to use undef. |
| 5302 | NewVal = getConstantVector( |
| 5303 | cast<Constant>(Val), |
| 5304 | isa<UndefValue>(Val) || |
| 5305 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 5306 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 5307 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 5308 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5309 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 5310 | } |
| 5311 | Transition->removeFromParent(); |
| 5312 | Transition->insertAfter(ToBePromoted); |
| 5313 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 5314 | } |
| 5315 | |
| 5316 | /// Some targets can do store(extractelement) with one instruction. |
| 5317 | /// Try to push the extractelement towards the stores when the target |
| 5318 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5319 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5320 | unsigned CombineCost = UINT_MAX; |
| 5321 | if (DisableStoreExtract || !TLI || |
| 5322 | (!StressStoreExtract && |
| 5323 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 5324 | Inst->getOperand(1), CombineCost))) |
| 5325 | return false; |
| 5326 | |
| 5327 | // At this point we know that Inst is a vector to scalar transition. |
| 5328 | // Try to move it down the def-use chain, until: |
| 5329 | // - We can combine the transition with its single use |
| 5330 | // => we got rid of the transition. |
| 5331 | // - We escape the current basic block |
| 5332 | // => we would need to check that we are moving it at a cheaper place and |
| 5333 | // we do not do that for now. |
| 5334 | BasicBlock *Parent = Inst->getParent(); |
| 5335 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5336 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5337 | // If the transition has more than one use, assume this is not going to be |
| 5338 | // beneficial. |
| 5339 | while (Inst->hasOneUse()) { |
| 5340 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 5341 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 5342 | |
| 5343 | if (ToBePromoted->getParent() != Parent) { |
| 5344 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 5345 | << ToBePromoted->getParent()->getName() |
| 5346 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 5347 | return false; |
| 5348 | } |
| 5349 | |
| 5350 | if (VPH.canCombine(ToBePromoted)) { |
| 5351 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 5352 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 5353 | VPH.recordCombineInstruction(ToBePromoted); |
| 5354 | bool Changed = VPH.promote(); |
| 5355 | NumStoreExtractExposed += Changed; |
| 5356 | return Changed; |
| 5357 | } |
| 5358 | |
| 5359 | DEBUG(dbgs() << "Try promoting.\n"); |
| 5360 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 5361 | return false; |
| 5362 | |
| 5363 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 5364 | |
| 5365 | VPH.enqueueForPromotion(ToBePromoted); |
| 5366 | Inst = ToBePromoted; |
| 5367 | } |
| 5368 | return false; |
| 5369 | } |
| 5370 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5371 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5372 | // Bail out if we inserted the instruction to prevent optimizations from |
| 5373 | // stepping on each other's toes. |
| 5374 | if (InsertedInsts.count(I)) |
| 5375 | return false; |
| 5376 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5377 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 5378 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 5379 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 5380 | // trivial PHI, go ahead and zap it here. |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 5381 | if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5382 | P->replaceAllUsesWith(V); |
| 5383 | P->eraseFromParent(); |
| 5384 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5385 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5386 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5387 | return false; |
| 5388 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5389 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5390 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5391 | // If the source of the cast is a constant, then this should have |
| 5392 | // already been constant folded. The only reason NOT to constant fold |
| 5393 | // it is if something (e.g. LSR) was careful to place the constant |
| 5394 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 5395 | // the address of globals out of a loop). If this is the case, we don't |
| 5396 | // want to forward-subst the cast. |
| 5397 | if (isa<Constant>(CI->getOperand(0))) |
| 5398 | return false; |
| 5399 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5400 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5401 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5402 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5403 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5404 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 5405 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5406 | if (TLI && |
| 5407 | TLI->getTypeAction(CI->getContext(), |
| 5408 | TLI->getValueType(*DL, CI->getType())) == |
| 5409 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5410 | return SinkCast(CI); |
| 5411 | } else { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5412 | bool MadeChange = moveExtToFormExtLoad(I); |
| 5413 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5414 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5415 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5416 | return false; |
| 5417 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5418 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5419 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 5420 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 5421 | return OptimizeCmpExpression(CI, TLI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5422 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5423 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 5424 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5425 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5426 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5427 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5428 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 5429 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5430 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 5431 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5432 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5433 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5434 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 5435 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5436 | if (TLI) { |
| 5437 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5438 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5439 | SI->getOperand(0)->getType(), AS); |
| 5440 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5441 | return false; |
| 5442 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5443 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5444 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 5445 | |
| 5446 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 5447 | BinOp->getOpcode() == Instruction::LShr)) { |
| 5448 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 5449 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5450 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5451 | |
| 5452 | return false; |
| 5453 | } |
| 5454 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5455 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5456 | if (GEPI->hasAllZeroIndices()) { |
| 5457 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 5458 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 5459 | GEPI->getName(), GEPI); |
| 5460 | GEPI->replaceAllUsesWith(NC); |
| 5461 | GEPI->eraseFromParent(); |
| 5462 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5463 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5464 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5465 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5466 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5467 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5468 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5469 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5470 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5471 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5472 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5473 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5474 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5475 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5476 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5477 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5478 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 5479 | return optimizeSwitchInst(Switch); |
| 5480 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5481 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5482 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5483 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5484 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5485 | } |
| 5486 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5487 | /// Given an OR instruction, check to see if this is a bitreverse |
| 5488 | /// idiom. If so, insert the new intrinsic and return true. |
| 5489 | static bool makeBitReverse(Instruction &I, const DataLayout &DL, |
| 5490 | const TargetLowering &TLI) { |
| 5491 | if (!I.getType()->isIntegerTy() || |
| 5492 | !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, |
| 5493 | TLI.getValueType(DL, I.getType(), true))) |
| 5494 | return false; |
| 5495 | |
| 5496 | SmallVector<Instruction*, 4> Insts; |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 5497 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5498 | return false; |
| 5499 | Instruction *LastInst = Insts.back(); |
| 5500 | I.replaceAllUsesWith(LastInst); |
| 5501 | RecursivelyDeleteTriviallyDeadInstructions(&I); |
| 5502 | return true; |
| 5503 | } |
| 5504 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5505 | // In this pass we look for GEP and cast instructions that are used |
| 5506 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 5507 | // selection. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5508 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 5509 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 5510 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 5511 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 5512 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5513 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5514 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5515 | if (ModifiedDT) |
| 5516 | return true; |
| 5517 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 5518 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5519 | bool MadeBitReverse = true; |
| 5520 | while (TLI && MadeBitReverse) { |
| 5521 | MadeBitReverse = false; |
| 5522 | for (auto &I : reverse(BB)) { |
| 5523 | if (makeBitReverse(I, *DL, *TLI)) { |
| 5524 | MadeBitReverse = MadeChange = true; |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 5525 | ModifiedDT = true; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5526 | break; |
| 5527 | } |
| 5528 | } |
| 5529 | } |
James Molloy | 3ef84c4 | 2016-01-15 10:36:01 +0000 | [diff] [blame] | 5530 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Junmo Park | 7d6c5f1 | 2016-01-28 09:42:39 +0000 | [diff] [blame] | 5531 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5532 | return MadeChange; |
| 5533 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5534 | |
| 5535 | // 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] | 5536 | // 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] | 5537 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5538 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5539 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5540 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 5541 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5542 | 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] | 5543 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5544 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 5545 | // Leave dbg.values that refer to an alloca alone. These |
| 5546 | // instrinsics describe the address of a variable (= the alloca) |
| 5547 | // being taken. They should not be moved next to the alloca |
| 5548 | // (and to the beginning of the scope), but rather stay close to |
| 5549 | // where said address is used. |
| 5550 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5551 | PrevNonDbgInst = Insn; |
| 5552 | continue; |
| 5553 | } |
| 5554 | |
| 5555 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 5556 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 5557 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 5558 | // after it. |
| 5559 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 5560 | continue; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5561 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 5562 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 5563 | if (isa<PHINode>(VI)) |
| 5564 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 5565 | else |
| 5566 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5567 | MadeChange = true; |
| 5568 | ++NumDbgValueMoved; |
| 5569 | } |
| 5570 | } |
| 5571 | } |
| 5572 | return MadeChange; |
| 5573 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5574 | |
| 5575 | // If there is a sequence that branches based on comparing a single bit |
| 5576 | // against zero that can be combined into a single instruction, and the |
| 5577 | // target supports folding these into a single instruction, sink the |
| 5578 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 5579 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 5580 | // searched for. |
| 5581 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 5582 | if (!EnableAndCmpSinking) |
| 5583 | return false; |
| 5584 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 5585 | return false; |
| 5586 | bool MadeChange = false; |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5587 | for (BasicBlock &BB : F) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5588 | // Does this BB end with the following? |
| 5589 | // %andVal = and %val, #single-bit-set |
| 5590 | // %icmpVal = icmp %andResult, 0 |
| 5591 | // br i1 %cmpVal label %dest1, label %dest2" |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5592 | BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator()); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5593 | if (!Brcc || !Brcc->isConditional()) |
| 5594 | continue; |
| 5595 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5596 | if (!Cmp || Cmp->getParent() != &BB) |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5597 | continue; |
| 5598 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 5599 | if (!Zero || !Zero->isZero()) |
| 5600 | continue; |
| 5601 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5602 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB) |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5603 | continue; |
| 5604 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 5605 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 5606 | continue; |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5607 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump()); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5608 | |
| 5609 | // Push the "and; icmp" for any users that are conditional branches. |
| 5610 | // Since there can only be one branch use per BB, we don't need to keep |
| 5611 | // track of which BBs we insert into. |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5612 | for (Use &TheUse : Cmp->uses()) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5613 | // Find brcc use. |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5614 | BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5615 | if (!BrccUser || !BrccUser->isConditional()) |
| 5616 | continue; |
| 5617 | BasicBlock *UserBB = BrccUser->getParent(); |
Sanjay Patel | 892f167 | 2016-04-11 20:13:44 +0000 | [diff] [blame] | 5618 | if (UserBB == &BB) continue; |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5619 | DEBUG(dbgs() << "found Brcc use\n"); |
| 5620 | |
| 5621 | // Sink the "and; icmp" to use. |
| 5622 | MadeChange = true; |
| 5623 | BinaryOperator *NewAnd = |
| 5624 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 5625 | BrccUser); |
| 5626 | CmpInst *NewCmp = |
| 5627 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 5628 | "", BrccUser); |
| 5629 | TheUse = NewCmp; |
| 5630 | ++NumAndCmpsMoved; |
| 5631 | DEBUG(BrccUser->getParent()->dump()); |
| 5632 | } |
| 5633 | } |
| 5634 | return MadeChange; |
| 5635 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5636 | |
| 5637 | /// \brief Scale down both weights to fit into uint32_t. |
| 5638 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 5639 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 5640 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 5641 | NewTrue = NewTrue / Scale; |
| 5642 | NewFalse = NewFalse / Scale; |
| 5643 | } |
| 5644 | |
| 5645 | /// \brief Some targets prefer to split a conditional branch like: |
| 5646 | /// \code |
| 5647 | /// %0 = icmp ne i32 %a, 0 |
| 5648 | /// %1 = icmp ne i32 %b, 0 |
| 5649 | /// %or.cond = or i1 %0, %1 |
| 5650 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 5651 | /// \endcode |
| 5652 | /// into multiple branch instructions like: |
| 5653 | /// \code |
| 5654 | /// bb1: |
| 5655 | /// %0 = icmp ne i32 %a, 0 |
| 5656 | /// br i1 %0, label %TrueBB, label %bb2 |
| 5657 | /// bb2: |
| 5658 | /// %1 = icmp ne i32 %b, 0 |
| 5659 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 5660 | /// \endcode |
| 5661 | /// This usually allows instruction selection to do even further optimizations |
| 5662 | /// and combine the compare with the branch instruction. Currently this is |
| 5663 | /// applied for targets which have "cheap" jump instructions. |
| 5664 | /// |
| 5665 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 5666 | /// |
| 5667 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 5668 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5669 | return false; |
| 5670 | |
| 5671 | bool MadeChange = false; |
| 5672 | for (auto &BB : F) { |
| 5673 | // Does this BB end with the following? |
| 5674 | // %cond1 = icmp|fcmp|binary instruction ... |
| 5675 | // %cond2 = icmp|fcmp|binary instruction ... |
| 5676 | // %cond.or = or|and i1 %cond1, cond2 |
| 5677 | // br i1 %cond.or label %dest1, label %dest2" |
| 5678 | BinaryOperator *LogicOp; |
| 5679 | BasicBlock *TBB, *FBB; |
| 5680 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 5681 | continue; |
| 5682 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 5683 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 5684 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 5685 | continue; |
| 5686 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5687 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5688 | Value *Cond1, *Cond2; |
| 5689 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 5690 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5691 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5692 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 5693 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5694 | Opc = Instruction::Or; |
| 5695 | else |
| 5696 | continue; |
| 5697 | |
| 5698 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 5699 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 5700 | continue; |
| 5701 | |
| 5702 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 5703 | |
| 5704 | // Create a new BB. |
Duncan P. N. Exon Smith | a848c47 | 2016-02-21 19:52:15 +0000 | [diff] [blame] | 5705 | auto TmpBB = |
| 5706 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", |
| 5707 | BB.getParent(), BB.getNextNode()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5708 | |
| 5709 | // Update original basic block by using the first condition directly by the |
| 5710 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5711 | Br1->setCondition(Cond1); |
| 5712 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5713 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5714 | // Depending on the conditon we have to either replace the true or the false |
| 5715 | // successor of the original branch instruction. |
| 5716 | if (Opc == Instruction::And) |
| 5717 | Br1->setSuccessor(0, TmpBB); |
| 5718 | else |
| 5719 | Br1->setSuccessor(1, TmpBB); |
| 5720 | |
| 5721 | // Fill in the new basic block. |
| 5722 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5723 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 5724 | I->removeFromParent(); |
| 5725 | I->insertBefore(Br2); |
| 5726 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5727 | |
| 5728 | // Update PHI nodes in both successors. The original BB needs to be |
| 5729 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 5730 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 5731 | // incoming edge to the PHI nodes, because both branch instructions target |
| 5732 | // now the same successor. Depending on the original branch condition |
| 5733 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 5734 | // we perform the correct update for the PHI nodes. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5735 | // This doesn't change the successor order of the just created branch |
| 5736 | // instruction (or any other instruction). |
| 5737 | if (Opc == Instruction::Or) |
| 5738 | std::swap(TBB, FBB); |
| 5739 | |
| 5740 | // Replace the old BB with the new BB. |
| 5741 | for (auto &I : *TBB) { |
| 5742 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5743 | if (!PN) |
| 5744 | break; |
| 5745 | int i; |
| 5746 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 5747 | PN->setIncomingBlock(i, TmpBB); |
| 5748 | } |
| 5749 | |
| 5750 | // Add another incoming edge form the new BB. |
| 5751 | for (auto &I : *FBB) { |
| 5752 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5753 | if (!PN) |
| 5754 | break; |
| 5755 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 5756 | PN->addIncoming(Val, TmpBB); |
| 5757 | } |
| 5758 | |
| 5759 | // Update the branch weights (from SelectionDAGBuilder:: |
| 5760 | // FindMergedConditions). |
| 5761 | if (Opc == Instruction::Or) { |
| 5762 | // Codegen X | Y as: |
| 5763 | // BB1: |
| 5764 | // jmp_if_X TBB |
| 5765 | // jmp TmpBB |
| 5766 | // TmpBB: |
| 5767 | // jmp_if_Y TBB |
| 5768 | // jmp FBB |
| 5769 | // |
| 5770 | |
| 5771 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 5772 | // The requirement is that |
| 5773 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 5774 | // = TrueProb for orignal BB. |
| 5775 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5776 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 5777 | // assumes that |
| 5778 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 5779 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 5780 | // TmpBB, but the math is more complicated. |
| 5781 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 5782 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5783 | uint64_t NewTrueWeight = TrueWeight; |
| 5784 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 5785 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5786 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5787 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5788 | |
| 5789 | NewTrueWeight = TrueWeight; |
| 5790 | NewFalseWeight = 2 * FalseWeight; |
| 5791 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5792 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5793 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5794 | } |
| 5795 | } else { |
| 5796 | // Codegen X & Y as: |
| 5797 | // BB1: |
| 5798 | // jmp_if_X TmpBB |
| 5799 | // jmp FBB |
| 5800 | // TmpBB: |
| 5801 | // jmp_if_Y TBB |
| 5802 | // jmp FBB |
| 5803 | // |
| 5804 | // This requires creation of TmpBB after CurBB. |
| 5805 | |
| 5806 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 5807 | // The requirement is that |
| 5808 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 5809 | // = FalseProb for orignal BB. |
| 5810 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5811 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 5812 | // assumes that |
| 5813 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 5814 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 5815 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5816 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 5817 | uint64_t NewFalseWeight = FalseWeight; |
| 5818 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5819 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5820 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5821 | |
| 5822 | NewTrueWeight = 2 * TrueWeight; |
| 5823 | NewFalseWeight = FalseWeight; |
| 5824 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5825 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5826 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5827 | } |
| 5828 | } |
| 5829 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5830 | // 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] | 5831 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5832 | ModifiedDT = true; |
| 5833 | |
| 5834 | MadeChange = true; |
| 5835 | |
| 5836 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 5837 | TmpBB->dump()); |
| 5838 | } |
| 5839 | return MadeChange; |
| 5840 | } |