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" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/SmallSet.h" |
| 20 | #include "llvm/ADT/Statistic.h" |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 22 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/CFG.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/InstructionSimplify.h" |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/LoopInfo.h" |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/TargetTransformInfo.h" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/ValueTracking.h" |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 30 | #include "llvm/Analysis/MemoryBuiltins.h" |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 31 | #include "llvm/CodeGen/Analysis.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 32 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Constants.h" |
| 34 | #include "llvm/IR/DataLayout.h" |
| 35 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 36 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 38 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 39 | #include "llvm/IR/IRBuilder.h" |
| 40 | #include "llvm/IR/InlineAsm.h" |
| 41 | #include "llvm/IR/Instructions.h" |
| 42 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 43 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 44 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 45 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 46 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 47 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 48 | #include "llvm/Pass.h" |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 49 | #include "llvm/Support/BranchProbability.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 50 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 51 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 52 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 53 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 54 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 55 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 56 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 57 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 58 | #include "llvm/Transforms/Utils/Cloning.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 59 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 60 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 61 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 62 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 63 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 64 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 65 | #define DEBUG_TYPE "codegenprepare" |
| 66 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 67 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 68 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 69 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 70 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 71 | "sunken Cmps"); |
| 72 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 73 | "of sunken Casts"); |
| 74 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 75 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 76 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 77 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 78 | STATISTIC(NumAndsAdded, |
| 79 | "Number of and mask instructions added to form ext loads"); |
| 80 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 81 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 82 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 83 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 84 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 85 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 86 | static cl::opt<bool> DisableBranchOpts( |
| 87 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 88 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 89 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 90 | static cl::opt<bool> |
| 91 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 92 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 93 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 94 | static cl::opt<bool> DisableSelectToBranch( |
| 95 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 96 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 97 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 98 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 99 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 100 | cl::desc("Address sinking in CGP using GEPs.")); |
| 101 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 102 | static cl::opt<bool> EnableAndCmpSinking( |
| 103 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 104 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 105 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 106 | static cl::opt<bool> DisableStoreExtract( |
| 107 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 108 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 109 | |
| 110 | static cl::opt<bool> StressStoreExtract( |
| 111 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 112 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 113 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 114 | static cl::opt<bool> DisableExtLdPromotion( |
| 115 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 116 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 117 | "CodeGenPrepare")); |
| 118 | |
| 119 | static cl::opt<bool> StressExtLdPromotion( |
| 120 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 121 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 122 | "optimization in CodeGenPrepare")); |
| 123 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 124 | static cl::opt<bool> DisablePreheaderProtect( |
| 125 | "disable-preheader-prot", cl::Hidden, cl::init(false), |
| 126 | cl::desc("Disable protection against removing loop preheaders")); |
| 127 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 128 | static cl::opt<bool> ProfileGuidedSectionPrefix( |
| 129 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), |
| 130 | cl::desc("Use profile info to add section prefix for hot/cold functions")); |
| 131 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 132 | static cl::opt<unsigned> FreqRatioToSkipMerge( |
| 133 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), |
| 134 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " |
| 135 | "(frequency of destination block) is greater than this ratio")); |
| 136 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 137 | static cl::opt<bool> ForceSplitStore( |
| 138 | "force-split-store", cl::Hidden, cl::init(false), |
| 139 | cl::desc("Force store splitting no matter what the target query says.")); |
| 140 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 141 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 142 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 143 | typedef PointerIntPair<Type *, 1, bool> TypeIsSExt; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 144 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 145 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 146 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 147 | class CodeGenPrepare : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 148 | const TargetMachine *TM; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 149 | const TargetSubtargetInfo *SubtargetInfo; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 150 | const TargetLowering *TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 151 | const TargetRegisterInfo *TRI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 152 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 153 | const TargetLibraryInfo *TLInfo; |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 154 | const LoopInfo *LI; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 155 | std::unique_ptr<BlockFrequencyInfo> BFI; |
| 156 | std::unique_ptr<BranchProbabilityInfo> BPI; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 157 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 158 | /// As we scan instructions optimizing them, this is the next instruction |
| 159 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 160 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 161 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 162 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 163 | /// This allows us to avoid inserting duplicate code for blocks with |
| 164 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 165 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 166 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 167 | /// Keeps track of all instructions inserted for the current function. |
| 168 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 169 | /// Keeps track of the type of the related instruction before their |
| 170 | /// promotion for the current function. |
| 171 | InstrToOrigTy PromotedInsts; |
| 172 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 173 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 174 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 175 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 176 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 177 | bool OptSize; |
| 178 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 179 | /// DataLayout for the Function being processed. |
| 180 | const DataLayout *DL; |
| 181 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 182 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 183 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 184 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 185 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 186 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 187 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 188 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 189 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 190 | StringRef getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 191 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 192 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 193 | // FIXME: When we can selectively preserve passes, preserve the domtree. |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 194 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 195 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 196 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 197 | AU.addRequired<LoopInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 198 | } |
| 199 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 200 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 201 | bool eliminateFallThrough(Function &F); |
| 202 | bool eliminateMostlyEmptyBlocks(Function &F); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 203 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 204 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 205 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 206 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, |
| 207 | bool isPreheader); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 208 | bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 209 | bool optimizeInst(Instruction *I, bool& ModifiedDT); |
| 210 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 211 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 212 | bool optimizeInlineAsmInst(CallInst *CS); |
| 213 | bool optimizeCallInst(CallInst *CI, bool& ModifiedDT); |
| 214 | bool moveExtToFormExtLoad(Instruction *&I); |
| 215 | bool optimizeExtUses(Instruction *I); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 216 | bool optimizeLoadExt(LoadInst *I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 217 | bool optimizeSelectInst(SelectInst *SI); |
| 218 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 219 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 220 | bool optimizeExtractElementInst(Instruction *Inst); |
| 221 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 222 | bool placeDbgValues(Function &F); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 223 | bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, |
| 224 | LoadInst *&LI, Instruction *&Inst, bool HasPromoted); |
| 225 | bool tryToPromoteExts(TypePromotionTransaction &TPT, |
| 226 | const SmallVectorImpl<Instruction *> &Exts, |
| 227 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 228 | unsigned CreatedInstsCost = 0); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 229 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 230 | bool simplifyOffsetableRelocate(Instruction &I); |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 231 | bool splitIndirectCriticalEdges(Function &F); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 232 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 233 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 234 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 235 | char CodeGenPrepare::ID = 0; |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 236 | INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare", |
| 237 | "Optimize for code generation", false, false) |
| 238 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) |
| 239 | INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare", |
| 240 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 241 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 242 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 243 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 244 | } |
| 245 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 246 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 247 | if (skipFunction(F)) |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 248 | return false; |
| 249 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 250 | DL = &F.getParent()->getDataLayout(); |
| 251 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 252 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 253 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 254 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 255 | PromotedInsts.clear(); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 256 | BFI.reset(); |
| 257 | BPI.reset(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 258 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 259 | ModifiedDT = false; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 260 | if (TM) { |
| 261 | SubtargetInfo = TM->getSubtargetImpl(F); |
| 262 | TLI = SubtargetInfo->getTargetLowering(); |
| 263 | TRI = SubtargetInfo->getRegisterInfo(); |
| 264 | } |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 265 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 266 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 267 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 268 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 269 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 270 | if (ProfileGuidedSectionPrefix) { |
| 271 | ProfileSummaryInfo *PSI = |
| 272 | getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); |
| 273 | if (PSI->isFunctionEntryHot(&F)) |
| 274 | F.setSectionPrefix(".hot"); |
| 275 | else if (PSI->isFunctionEntryCold(&F)) |
| 276 | F.setSectionPrefix(".cold"); |
| 277 | } |
| 278 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 279 | /// This optimization identifies DIV instructions that can be |
| 280 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 281 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 282 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 283 | TLI->getBypassSlowDivWidths(); |
Eric Christopher | 49a7d6c | 2016-01-04 23:18:58 +0000 | [diff] [blame] | 284 | BasicBlock* BB = &*F.begin(); |
| 285 | while (BB != nullptr) { |
| 286 | // bypassSlowDivision may create new BBs, but we don't want to reapply the |
| 287 | // optimization to those blocks. |
| 288 | BasicBlock* Next = BB->getNextNode(); |
| 289 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); |
| 290 | BB = Next; |
| 291 | } |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 292 | } |
| 293 | |
| 294 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 295 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 296 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 297 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 298 | // 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] | 299 | // 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] | 300 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 301 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 302 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 303 | if (!DisableBranchOpts) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 304 | EverMadeChange |= splitBranchCondition(F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 305 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 306 | // Split some critical edges where one of the sources is an indirect branch, |
| 307 | // to help generate sane code for PHIs involving such edges. |
| 308 | EverMadeChange |= splitIndirectCriticalEdges(F); |
| 309 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 310 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 311 | while (MadeChange) { |
| 312 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 313 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 314 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 315 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 316 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 317 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 318 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 319 | if (ModifiedDTOnIteration) |
| 320 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 321 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 322 | EverMadeChange |= MadeChange; |
| 323 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 324 | |
| 325 | SunkAddrs.clear(); |
| 326 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 327 | if (!DisableBranchOpts) { |
| 328 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 329 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 330 | for (BasicBlock &BB : F) { |
| 331 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 332 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 333 | if (!MadeChange) continue; |
| 334 | |
| 335 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 336 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 337 | if (pred_begin(*II) == pred_end(*II)) |
| 338 | WorkList.insert(*II); |
| 339 | } |
| 340 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 341 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 342 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 343 | while (!WorkList.empty()) { |
| 344 | BasicBlock *BB = *WorkList.begin(); |
| 345 | WorkList.erase(BB); |
| 346 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 347 | |
| 348 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 349 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 350 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 351 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 352 | if (pred_begin(*II) == pred_end(*II)) |
| 353 | WorkList.insert(*II); |
| 354 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 355 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 356 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 357 | // a single edge. |
| 358 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 359 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 360 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 361 | EverMadeChange |= MadeChange; |
| 362 | } |
| 363 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 364 | if (!DisableGCOpts) { |
| 365 | SmallVector<Instruction *, 2> Statepoints; |
| 366 | for (BasicBlock &BB : F) |
| 367 | for (Instruction &I : BB) |
| 368 | if (isStatepoint(I)) |
| 369 | Statepoints.push_back(&I); |
| 370 | for (auto &I : Statepoints) |
| 371 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 372 | } |
| 373 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 374 | return EverMadeChange; |
| 375 | } |
| 376 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 377 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 378 | /// basic blocks has a single successor pointing to the other basic block, |
| 379 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 380 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 381 | bool Changed = false; |
| 382 | // 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] | 383 | 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] | 384 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 385 | // If the destination block has a single pred, then this is a trivial |
| 386 | // edge, just collapse it. |
| 387 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 388 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 389 | // Don't merge if BB's address is taken. |
| 390 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 391 | |
| 392 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 393 | if (Term && !Term->isConditional()) { |
| 394 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 395 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 396 | // Remember if SinglePred was the entry block of the function. |
| 397 | // If so, we will need to move BB back to the entry position. |
| 398 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 399 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 400 | |
| 401 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 402 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 403 | |
| 404 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 405 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 406 | } |
| 407 | } |
| 408 | return Changed; |
| 409 | } |
| 410 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 411 | /// Find a destination block from BB if BB is mergeable empty block. |
| 412 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { |
| 413 | // If this block doesn't end with an uncond branch, ignore it. |
| 414 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 415 | if (!BI || !BI->isUnconditional()) |
| 416 | return nullptr; |
| 417 | |
| 418 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 419 | // node, then other stuff is happening here. |
| 420 | BasicBlock::iterator BBI = BI->getIterator(); |
| 421 | if (BBI != BB->begin()) { |
| 422 | --BBI; |
| 423 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 424 | if (BBI == BB->begin()) |
| 425 | break; |
| 426 | --BBI; |
| 427 | } |
| 428 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 429 | return nullptr; |
| 430 | } |
| 431 | |
| 432 | // Do not break infinite loops. |
| 433 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 434 | if (DestBB == BB) |
| 435 | return nullptr; |
| 436 | |
| 437 | if (!canMergeBlocks(BB, DestBB)) |
| 438 | DestBB = nullptr; |
| 439 | |
| 440 | return DestBB; |
| 441 | } |
| 442 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 443 | // Return the unique indirectbr predecessor of a block. This may return null |
| 444 | // even if such a predecessor exists, if it's not useful for splitting. |
| 445 | // If a predecessor is found, OtherPreds will contain all other (non-indirectbr) |
| 446 | // predecessors of BB. |
| 447 | static BasicBlock * |
| 448 | findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) { |
| 449 | // If the block doesn't have any PHIs, we don't care about it, since there's |
| 450 | // no point in splitting it. |
| 451 | PHINode *PN = dyn_cast<PHINode>(BB->begin()); |
| 452 | if (!PN) |
| 453 | return nullptr; |
| 454 | |
| 455 | // Verify we have exactly one IBR predecessor. |
| 456 | // Conservatively bail out if one of the other predecessors is not a "regular" |
| 457 | // terminator (that is, not a switch or a br). |
| 458 | BasicBlock *IBB = nullptr; |
| 459 | for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) { |
| 460 | BasicBlock *PredBB = PN->getIncomingBlock(Pred); |
| 461 | TerminatorInst *PredTerm = PredBB->getTerminator(); |
| 462 | switch (PredTerm->getOpcode()) { |
| 463 | case Instruction::IndirectBr: |
| 464 | if (IBB) |
| 465 | return nullptr; |
| 466 | IBB = PredBB; |
| 467 | break; |
| 468 | case Instruction::Br: |
| 469 | case Instruction::Switch: |
| 470 | OtherPreds.push_back(PredBB); |
| 471 | continue; |
| 472 | default: |
| 473 | return nullptr; |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | return IBB; |
| 478 | } |
| 479 | |
| 480 | // Split critical edges where the source of the edge is an indirectbr |
| 481 | // instruction. This isn't always possible, but we can handle some easy cases. |
| 482 | // This is useful because MI is unable to split such critical edges, |
| 483 | // which means it will not be able to sink instructions along those edges. |
| 484 | // This is especially painful for indirect branches with many successors, where |
| 485 | // we end up having to prepare all outgoing values in the origin block. |
| 486 | // |
| 487 | // Our normal algorithm for splitting critical edges requires us to update |
| 488 | // the outgoing edges of the edge origin block, but for an indirectbr this |
| 489 | // is hard, since it would require finding and updating the block addresses |
| 490 | // the indirect branch uses. But if a block only has a single indirectbr |
| 491 | // predecessor, with the others being regular branches, we can do it in a |
| 492 | // different way. |
| 493 | // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr. |
| 494 | // We can split D into D0 and D1, where D0 contains only the PHIs from D, |
| 495 | // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and |
| 496 | // create the following structure: |
| 497 | // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1 |
| 498 | bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) { |
| 499 | // Check whether the function has any indirectbrs, and collect which blocks |
| 500 | // they may jump to. Since most functions don't have indirect branches, |
| 501 | // this lowers the common case's overhead to O(Blocks) instead of O(Edges). |
| 502 | SmallSetVector<BasicBlock *, 16> Targets; |
| 503 | for (auto &BB : F) { |
| 504 | auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator()); |
| 505 | if (!IBI) |
| 506 | continue; |
| 507 | |
| 508 | for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ) |
| 509 | Targets.insert(IBI->getSuccessor(Succ)); |
| 510 | } |
| 511 | |
| 512 | if (Targets.empty()) |
| 513 | return false; |
| 514 | |
| 515 | bool Changed = false; |
| 516 | for (BasicBlock *Target : Targets) { |
| 517 | SmallVector<BasicBlock *, 16> OtherPreds; |
| 518 | BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds); |
| 519 | // If we did not found an indirectbr, or the indirectbr is the only |
| 520 | // incoming edge, this isn't the kind of edge we're looking for. |
| 521 | if (!IBRPred || OtherPreds.empty()) |
| 522 | continue; |
| 523 | |
| 524 | // Don't even think about ehpads/landingpads. |
| 525 | Instruction *FirstNonPHI = Target->getFirstNonPHI(); |
| 526 | if (FirstNonPHI->isEHPad() || Target->isLandingPad()) |
| 527 | continue; |
| 528 | |
| 529 | BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split"); |
| 530 | // It's possible Target was its own successor through an indirectbr. |
| 531 | // In this case, the indirectbr now comes from BodyBlock. |
| 532 | if (IBRPred == Target) |
| 533 | IBRPred = BodyBlock; |
| 534 | |
| 535 | // At this point Target only has PHIs, and BodyBlock has the rest of the |
| 536 | // block's body. Create a copy of Target that will be used by the "direct" |
| 537 | // preds. |
| 538 | ValueToValueMapTy VMap; |
| 539 | BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F); |
| 540 | |
| 541 | for (BasicBlock *Pred : OtherPreds) |
| 542 | Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc); |
| 543 | |
| 544 | // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that |
| 545 | // they are clones, so the number of PHIs are the same. |
| 546 | // (a) Remove the edge coming from IBRPred from the "Direct" PHI |
| 547 | // (b) Leave that as the only edge in the "Indirect" PHI. |
| 548 | // (c) Merge the two in the body block. |
| 549 | BasicBlock::iterator Indirect = Target->begin(), |
| 550 | End = Target->getFirstNonPHI()->getIterator(); |
| 551 | BasicBlock::iterator Direct = DirectSucc->begin(); |
| 552 | BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt(); |
| 553 | |
| 554 | assert(&*End == Target->getTerminator() && |
| 555 | "Block was expected to only contain PHIs"); |
| 556 | |
| 557 | while (Indirect != End) { |
| 558 | PHINode *DirPHI = cast<PHINode>(Direct); |
| 559 | PHINode *IndPHI = cast<PHINode>(Indirect); |
| 560 | |
| 561 | // Now, clean up - the direct block shouldn't get the indirect value, |
| 562 | // and vice versa. |
| 563 | DirPHI->removeIncomingValue(IBRPred); |
| 564 | Direct++; |
| 565 | |
| 566 | // Advance the pointer here, to avoid invalidation issues when the old |
| 567 | // PHI is erased. |
| 568 | Indirect++; |
| 569 | |
| 570 | PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI); |
| 571 | NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred), |
| 572 | IBRPred); |
| 573 | |
| 574 | // Create a PHI in the body block, to merge the direct and indirect |
| 575 | // predecessors. |
| 576 | PHINode *MergePHI = |
| 577 | PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert); |
| 578 | MergePHI->addIncoming(NewIndPHI, Target); |
| 579 | MergePHI->addIncoming(DirPHI, DirectSucc); |
| 580 | |
| 581 | IndPHI->replaceAllUsesWith(MergePHI); |
| 582 | IndPHI->eraseFromParent(); |
| 583 | } |
| 584 | |
| 585 | Changed = true; |
| 586 | } |
| 587 | |
| 588 | return Changed; |
| 589 | } |
| 590 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 591 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 592 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 593 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 594 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 595 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 596 | SmallPtrSet<BasicBlock *, 16> Preheaders; |
| 597 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); |
| 598 | while (!LoopList.empty()) { |
| 599 | Loop *L = LoopList.pop_back_val(); |
| 600 | LoopList.insert(LoopList.end(), L->begin(), L->end()); |
| 601 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 602 | Preheaders.insert(Preheader); |
| 603 | } |
| 604 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 605 | bool MadeChange = false; |
| 606 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 607 | 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] | 608 | BasicBlock *BB = &*I++; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 609 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); |
| 610 | if (!DestBB || |
| 611 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 612 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 613 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 614 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 615 | MadeChange = true; |
| 616 | } |
| 617 | return MadeChange; |
| 618 | } |
| 619 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 620 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, |
| 621 | BasicBlock *DestBB, |
| 622 | bool isPreheader) { |
| 623 | // Do not delete loop preheaders if doing so would create a critical edge. |
| 624 | // Loop preheaders can be good locations to spill registers. If the |
| 625 | // preheader is deleted and we create a critical edge, registers may be |
| 626 | // spilled in the loop body instead. |
| 627 | if (!DisablePreheaderProtect && isPreheader && |
| 628 | !(BB->getSinglePredecessor() && |
| 629 | BB->getSinglePredecessor()->getSingleSuccessor())) |
| 630 | return false; |
| 631 | |
| 632 | // Try to skip merging if the unique predecessor of BB is terminated by a |
| 633 | // switch or indirect branch instruction, and BB is used as an incoming block |
| 634 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to |
| 635 | // add COPY instructions in the predecessor of BB instead of BB (if it is not |
| 636 | // merged). Note that the critical edge created by merging such blocks wont be |
| 637 | // split in MachineSink because the jump table is not analyzable. By keeping |
| 638 | // such empty block (BB), ISel will place COPY instructions in BB, not in the |
| 639 | // predecessor of BB. |
| 640 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 641 | if (!Pred || |
| 642 | !(isa<SwitchInst>(Pred->getTerminator()) || |
| 643 | isa<IndirectBrInst>(Pred->getTerminator()))) |
| 644 | return true; |
| 645 | |
| 646 | if (BB->getTerminator() != BB->getFirstNonPHI()) |
| 647 | return true; |
| 648 | |
| 649 | // We use a simple cost heuristic which determine skipping merging is |
| 650 | // profitable if the cost of skipping merging is less than the cost of |
| 651 | // merging : Cost(skipping merging) < Cost(merging BB), where the |
| 652 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and |
| 653 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). |
| 654 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : |
| 655 | // Freq(Pred) / Freq(BB) > 2. |
| 656 | // Note that if there are multiple empty blocks sharing the same incoming |
| 657 | // value for the PHIs in the DestBB, we consider them together. In such |
| 658 | // case, Cost(merging BB) will be the sum of their frequencies. |
| 659 | |
| 660 | if (!isa<PHINode>(DestBB->begin())) |
| 661 | return true; |
| 662 | |
| 663 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; |
| 664 | |
| 665 | // Find all other incoming blocks from which incoming values of all PHIs in |
| 666 | // DestBB are the same as the ones from BB. |
| 667 | for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; |
| 668 | ++PI) { |
| 669 | BasicBlock *DestBBPred = *PI; |
| 670 | if (DestBBPred == BB) |
| 671 | continue; |
| 672 | |
| 673 | bool HasAllSameValue = true; |
| 674 | BasicBlock::const_iterator DestBBI = DestBB->begin(); |
| 675 | while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) { |
| 676 | if (DestPN->getIncomingValueForBlock(BB) != |
| 677 | DestPN->getIncomingValueForBlock(DestBBPred)) { |
| 678 | HasAllSameValue = false; |
| 679 | break; |
| 680 | } |
| 681 | } |
| 682 | if (HasAllSameValue) |
| 683 | SameIncomingValueBBs.insert(DestBBPred); |
| 684 | } |
| 685 | |
| 686 | // See if all BB's incoming values are same as the value from Pred. In this |
| 687 | // case, no reason to skip merging because COPYs are expected to be place in |
| 688 | // Pred already. |
| 689 | if (SameIncomingValueBBs.count(Pred)) |
| 690 | return true; |
| 691 | |
| 692 | if (!BFI) { |
| 693 | Function &F = *BB->getParent(); |
| 694 | LoopInfo LI{DominatorTree(F)}; |
| 695 | BPI.reset(new BranchProbabilityInfo(F, LI)); |
| 696 | BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); |
| 697 | } |
| 698 | |
| 699 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); |
| 700 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); |
| 701 | |
| 702 | for (auto SameValueBB : SameIncomingValueBBs) |
| 703 | if (SameValueBB->getUniquePredecessor() == Pred && |
| 704 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) |
| 705 | BBFreq += BFI->getBlockFreq(SameValueBB); |
| 706 | |
| 707 | return PredFreq.getFrequency() <= |
| 708 | BBFreq.getFrequency() * FreqRatioToSkipMerge; |
| 709 | } |
| 710 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 711 | /// Return true if we can merge BB into DestBB if there is a single |
| 712 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 713 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 714 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 715 | const BasicBlock *DestBB) const { |
| 716 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 717 | // the successor. If there are more complex condition (e.g. preheaders), |
| 718 | // don't mess around with them. |
| 719 | BasicBlock::const_iterator BBI = BB->begin(); |
| 720 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 721 | for (const User *U : PN->users()) { |
| 722 | const Instruction *UI = cast<Instruction>(U); |
| 723 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 724 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 725 | // If User is inside DestBB block and it is a PHINode then check |
| 726 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 727 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 728 | if (UI->getParent() == DestBB) { |
| 729 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 730 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 731 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 732 | if (Insn && Insn->getParent() == BB && |
| 733 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 734 | return false; |
| 735 | } |
| 736 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 737 | } |
| 738 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 739 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 740 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 741 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 742 | // can't merge the block. |
| 743 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 744 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 745 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 746 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 747 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 748 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 749 | // It is faster to get preds from a PHI than with pred_iterator. |
| 750 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 751 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 752 | } else { |
| 753 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 754 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 755 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 756 | // Walk the preds of DestBB. |
| 757 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 758 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 759 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 760 | BBI = DestBB->begin(); |
| 761 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 762 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 763 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 764 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 765 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 766 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 767 | if (V2PN->getParent() == BB) |
| 768 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 769 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 770 | // If there is a conflict, bail out. |
| 771 | if (V1 != V2) return false; |
| 772 | } |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | return true; |
| 777 | } |
| 778 | |
| 779 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 780 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 781 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 782 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 783 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 784 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 785 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 786 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 787 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 788 | // If the destination block has a single pred, then this is a trivial edge, |
| 789 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 790 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 791 | if (SinglePred != DestBB) { |
| 792 | // Remember if SinglePred was the entry block of the function. If so, we |
| 793 | // will need to move BB back to the entry position. |
| 794 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 795 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 796 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 797 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 798 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 799 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 800 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 801 | return; |
| 802 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 803 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 804 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 805 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 806 | // to handle the new incoming edges it is about to have. |
| 807 | PHINode *PN; |
| 808 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 809 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 810 | // Remove the incoming value for BB, and remember it. |
| 811 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 812 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 813 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 814 | // value that dominates BB. |
| 815 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 816 | if (InValPhi && InValPhi->getParent() == BB) { |
| 817 | // Add all of the input values of the input PHI as inputs of this phi. |
| 818 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 819 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 820 | InValPhi->getIncomingBlock(i)); |
| 821 | } else { |
| 822 | // Otherwise, add one instance of the dominating value for each edge that |
| 823 | // we will be adding. |
| 824 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 825 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 826 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 827 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 828 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 829 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 830 | } |
| 831 | } |
| 832 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 833 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 834 | // The PHIs are now updated, change everything that refers to BB to use |
| 835 | // DestBB and remove BB. |
| 836 | BB->replaceAllUsesWith(DestBB); |
| 837 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 838 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 839 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 840 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 841 | } |
| 842 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 843 | // Computes a map of base pointer relocation instructions to corresponding |
| 844 | // derived pointer relocation instructions given a vector of all relocate calls |
| 845 | static void computeBaseDerivedRelocateMap( |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 846 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, |
| 847 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> |
| 848 | &RelocateInstMap) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 849 | // Collect information in two maps: one primarily for locating the base object |
| 850 | // while filling the second map; the second map is the final structure holding |
| 851 | // a mapping between Base and corresponding Derived relocate calls |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 852 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; |
| 853 | for (auto *ThisRelocate : AllRelocateCalls) { |
| 854 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), |
| 855 | ThisRelocate->getDerivedPtrIndex()); |
| 856 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 857 | } |
| 858 | for (auto &Item : RelocateIdxMap) { |
| 859 | std::pair<unsigned, unsigned> Key = Item.first; |
| 860 | if (Key.first == Key.second) |
| 861 | // Base relocation: nothing to insert |
| 862 | continue; |
| 863 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 864 | GCRelocateInst *I = Item.second; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 865 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 866 | |
| 867 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 868 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 869 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 870 | // TODO: We might want to insert a new base object relocate and gep off |
| 871 | // that, if there are enough derived object relocates. |
| 872 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 873 | |
| 874 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 875 | } |
| 876 | } |
| 877 | |
| 878 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 879 | // small integer constants |
| 880 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 881 | SmallVectorImpl<Value *> &OffsetV) { |
| 882 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 883 | // Only accept small constant integer operands |
| 884 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 885 | if (!Op || Op->getZExtValue() > 20) |
| 886 | return false; |
| 887 | } |
| 888 | |
| 889 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 890 | OffsetV.push_back(GEP->getOperand(i)); |
| 891 | return true; |
| 892 | } |
| 893 | |
| 894 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 895 | // replace, computes a replacement, and affects it. |
| 896 | static bool |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 897 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, |
| 898 | const SmallVectorImpl<GCRelocateInst *> &Targets) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 899 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 900 | for (GCRelocateInst *ToReplace : Targets) { |
| 901 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 902 | "Not relocating a derived object of the original base object"); |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 903 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 904 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 905 | continue; |
| 906 | } |
| 907 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 908 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 909 | // Base and derived relocates are in different basic blocks. |
| 910 | // In this case transform is only valid when base dominates derived |
| 911 | // relocate. However it would be too expensive to check dominance |
| 912 | // for each such relocate, so we skip the whole transformation. |
| 913 | continue; |
| 914 | } |
| 915 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 916 | Value *Base = ToReplace->getBasePtr(); |
| 917 | auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 918 | if (!Derived || Derived->getPointerOperand() != Base) |
| 919 | continue; |
| 920 | |
| 921 | SmallVector<Value *, 2> OffsetV; |
| 922 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 923 | continue; |
| 924 | |
| 925 | // Create a Builder and replace the target callsite with a gep |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 926 | assert(RelocatedBase->getNextNode() && |
| 927 | "Should always have one since it's not a terminator"); |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 928 | |
| 929 | // Insert after RelocatedBase |
| 930 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 931 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 932 | |
| 933 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 934 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 935 | // match, and we should reuse it to get the derived pointer. But it could be |
| 936 | // cases like this: |
| 937 | // bb1: |
| 938 | // ... |
| 939 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 940 | // br label %merge |
| 941 | // |
| 942 | // bb2: |
| 943 | // ... |
| 944 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 945 | // br label %merge |
| 946 | // |
| 947 | // merge: |
| 948 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 949 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 950 | // |
| 951 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 952 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 953 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 954 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 955 | if (RelocatedBase->getType() != Base->getType()) { |
| 956 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 957 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 958 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 959 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 960 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 961 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 962 | // If the newly generated derived pointer's type does not match the original derived |
| 963 | // 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] | 964 | Value *ActualReplacement = Replacement; |
| 965 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 966 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 967 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 968 | } |
| 969 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 970 | ToReplace->eraseFromParent(); |
| 971 | |
| 972 | MadeChange = true; |
| 973 | } |
| 974 | return MadeChange; |
| 975 | } |
| 976 | |
| 977 | // Turns this: |
| 978 | // |
| 979 | // %base = ... |
| 980 | // %ptr = gep %base + 15 |
| 981 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 982 | // %base' = relocate(%tok, i32 4, i32 4) |
| 983 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 984 | // %val = load %ptr' |
| 985 | // |
| 986 | // into this: |
| 987 | // |
| 988 | // %base = ... |
| 989 | // %ptr = gep %base + 15 |
| 990 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 991 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 992 | // %ptr' = gep %base' + 15 |
| 993 | // %val = load %ptr' |
| 994 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 995 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 996 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 997 | |
| 998 | for (auto *U : I.users()) |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 999 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1000 | // Collect all the relocate calls associated with a statepoint |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1001 | AllRelocateCalls.push_back(Relocate); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1002 | |
| 1003 | // We need atleast one base pointer relocation + one derived pointer |
| 1004 | // relocation to mangle |
| 1005 | if (AllRelocateCalls.size() < 2) |
| 1006 | return false; |
| 1007 | |
| 1008 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 1009 | // corresponding derived relocate instructions |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1010 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1011 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 1012 | if (RelocateInstMap.empty()) |
| 1013 | return false; |
| 1014 | |
| 1015 | for (auto &Item : RelocateInstMap) |
| 1016 | // Item.first is the RelocatedBase to offset against |
| 1017 | // Item.second is the vector of Targets to replace |
| 1018 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 1019 | return MadeChange; |
| 1020 | } |
| 1021 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1022 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 1023 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1024 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1025 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1026 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1027 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1028 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1029 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1030 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1031 | UI != E; ) { |
| 1032 | Use &TheUse = UI.getUse(); |
| 1033 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1034 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1035 | // Figure out which BB this cast is used in. For PHI's this is the |
| 1036 | // appropriate predecessor block. |
| 1037 | BasicBlock *UserBB = User->getParent(); |
| 1038 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1039 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1040 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1041 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1042 | // Preincrement use iterator so we don't invalidate it. |
| 1043 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1044 | |
David Majnemer | 0c80e2e | 2016-04-27 19:36:38 +0000 | [diff] [blame] | 1045 | // The first insertion point of a block containing an EH pad is after the |
| 1046 | // pad. If the pad is the user, we cannot sink the cast past the pad. |
| 1047 | if (User->isEHPad()) |
| 1048 | continue; |
| 1049 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 1050 | // If the block selected to receive the cast is an EH pad that does not |
| 1051 | // allow non-PHI instructions before the terminator, we can't sink the |
| 1052 | // cast. |
| 1053 | if (UserBB->getTerminator()->isEHPad()) |
| 1054 | continue; |
| 1055 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1056 | // If this user is in the same block as the cast, don't change the cast. |
| 1057 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1058 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1059 | // If we have already inserted a cast into this block, use it. |
| 1060 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 1061 | |
| 1062 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1063 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1064 | assert(InsertPt != UserBB->end()); |
| 1065 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 1066 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1067 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1068 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1069 | // 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] | 1070 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1071 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1072 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1073 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1074 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1075 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1076 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1077 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1078 | MadeChange = true; |
| 1079 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1080 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1081 | return MadeChange; |
| 1082 | } |
| 1083 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1084 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 1085 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 1086 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1087 | /// |
| 1088 | /// Return true if any changes are made. |
| 1089 | /// |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1090 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 1091 | const DataLayout &DL) { |
Justin Lebar | 3e50a5b | 2016-11-21 22:49:15 +0000 | [diff] [blame] | 1092 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition |
| 1093 | // than sinking only nop casts, but is helpful on some platforms. |
| 1094 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { |
| 1095 | if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(), |
| 1096 | ASC->getDestAddressSpace())) |
| 1097 | return false; |
| 1098 | } |
| 1099 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1100 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1101 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 1102 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1103 | |
| 1104 | // This is an fp<->int conversion? |
| 1105 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 1106 | return false; |
| 1107 | |
| 1108 | // If this is an extension, it will be a zero or sign extension, which |
| 1109 | // isn't a noop. |
| 1110 | if (SrcVT.bitsLT(DstVT)) return false; |
| 1111 | |
| 1112 | // If these values will be promoted, find out what they will be promoted |
| 1113 | // to. This helps us consider truncates on PPC as noop copies when they |
| 1114 | // are. |
| 1115 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 1116 | TargetLowering::TypePromoteInteger) |
| 1117 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 1118 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 1119 | TargetLowering::TypePromoteInteger) |
| 1120 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 1121 | |
| 1122 | // If, after promotion, these are the same types, this is a noop copy. |
| 1123 | if (SrcVT != DstVT) |
| 1124 | return false; |
| 1125 | |
| 1126 | return SinkCast(CI); |
| 1127 | } |
| 1128 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1129 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 1130 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1131 | /// |
| 1132 | /// Return true if any changes were made. |
| 1133 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 1134 | Value *A, *B; |
| 1135 | Instruction *AddI; |
| 1136 | if (!match(CI, |
| 1137 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 1138 | return false; |
| 1139 | |
| 1140 | Type *Ty = AddI->getType(); |
| 1141 | if (!isa<IntegerType>(Ty)) |
| 1142 | return false; |
| 1143 | |
| 1144 | // We don't want to move around uses of condition values this late, so we we |
| 1145 | // check if it is legal to create the call to the intrinsic in the basic |
| 1146 | // block containing the icmp: |
| 1147 | |
| 1148 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 1149 | return false; |
| 1150 | |
| 1151 | #ifndef NDEBUG |
| 1152 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 1153 | // for now: |
| 1154 | if (AddI->hasOneUse()) |
| 1155 | assert(*AddI->user_begin() == CI && "expected!"); |
| 1156 | #endif |
| 1157 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 1158 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1159 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 1160 | |
| 1161 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 1162 | |
| 1163 | auto *UAddWithOverflow = |
| 1164 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 1165 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 1166 | auto *Overflow = |
| 1167 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 1168 | |
| 1169 | CI->replaceAllUsesWith(Overflow); |
| 1170 | AddI->replaceAllUsesWith(UAdd); |
| 1171 | CI->eraseFromParent(); |
| 1172 | AddI->eraseFromParent(); |
| 1173 | return true; |
| 1174 | } |
| 1175 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1176 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 1177 | /// registers that must be created and coalesced. This is a clear win except on |
| 1178 | /// targets with multiple condition code registers (PowerPC), where it might |
| 1179 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1180 | /// |
| 1181 | /// Return true if any changes are made. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1182 | static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1183 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1184 | |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1185 | // 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] | 1186 | if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI)) |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1187 | return false; |
| 1188 | |
| 1189 | // Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1190 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1191 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1192 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1193 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1194 | UI != E; ) { |
| 1195 | Use &TheUse = UI.getUse(); |
| 1196 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1197 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1198 | // Preincrement use iterator so we don't invalidate it. |
| 1199 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1200 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1201 | // Don't bother for PHI nodes. |
| 1202 | if (isa<PHINode>(User)) |
| 1203 | continue; |
| 1204 | |
| 1205 | // Figure out which BB this cmp is used in. |
| 1206 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1207 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1208 | // If this user is in the same block as the cmp, don't change the cmp. |
| 1209 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1210 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1211 | // If we have already inserted a cmp into this block, use it. |
| 1212 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 1213 | |
| 1214 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1215 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1216 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1217 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1218 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 1219 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Wolfgang Pieb | e51bede | 2016-10-06 21:43:45 +0000 | [diff] [blame] | 1220 | // Propagate the debug info. |
| 1221 | InsertedCmp->setDebugLoc(CI->getDebugLoc()); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1222 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1223 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1224 | // Replace a use of the cmp with a use of the new cmp. |
| 1225 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1226 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1227 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1228 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1229 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1230 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1231 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1232 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1233 | MadeChange = true; |
| 1234 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1235 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1236 | return MadeChange; |
| 1237 | } |
| 1238 | |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 1239 | static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1240 | if (SinkCmpExpression(CI, TLI)) |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1241 | return true; |
| 1242 | |
| 1243 | if (CombineUAddWithOverflow(CI)) |
| 1244 | return true; |
| 1245 | |
| 1246 | return false; |
| 1247 | } |
| 1248 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1249 | /// Duplicate and sink the given 'and' instruction into user blocks where it is |
| 1250 | /// used in a compare to allow isel to generate better code for targets where |
| 1251 | /// this operation can be combined. |
| 1252 | /// |
| 1253 | /// Return true if any changes are made. |
| 1254 | static bool sinkAndCmp0Expression(Instruction *AndI, |
| 1255 | const TargetLowering &TLI, |
| 1256 | SetOfInstrs &InsertedInsts) { |
| 1257 | // Double-check that we're not trying to optimize an instruction that was |
| 1258 | // already optimized by some other part of this pass. |
| 1259 | assert(!InsertedInsts.count(AndI) && |
| 1260 | "Attempting to optimize already optimized and instruction"); |
| 1261 | (void) InsertedInsts; |
| 1262 | |
| 1263 | // Nothing to do for single use in same basic block. |
| 1264 | if (AndI->hasOneUse() && |
| 1265 | AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) |
| 1266 | return false; |
| 1267 | |
| 1268 | // Try to avoid cases where sinking/duplicating is likely to increase register |
| 1269 | // pressure. |
| 1270 | if (!isa<ConstantInt>(AndI->getOperand(0)) && |
| 1271 | !isa<ConstantInt>(AndI->getOperand(1)) && |
| 1272 | AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) |
| 1273 | return false; |
| 1274 | |
| 1275 | for (auto *U : AndI->users()) { |
| 1276 | Instruction *User = cast<Instruction>(U); |
| 1277 | |
| 1278 | // Only sink for and mask feeding icmp with 0. |
| 1279 | if (!isa<ICmpInst>(User)) |
| 1280 | return false; |
| 1281 | |
| 1282 | auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); |
| 1283 | if (!CmpC || !CmpC->isZero()) |
| 1284 | return false; |
| 1285 | } |
| 1286 | |
| 1287 | if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) |
| 1288 | return false; |
| 1289 | |
| 1290 | DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n"); |
| 1291 | DEBUG(AndI->getParent()->dump()); |
| 1292 | |
| 1293 | // Push the 'and' into the same block as the icmp 0. There should only be |
| 1294 | // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any |
| 1295 | // others, so we don't need to keep track of which BBs we insert into. |
| 1296 | for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); |
| 1297 | UI != E; ) { |
| 1298 | Use &TheUse = UI.getUse(); |
| 1299 | Instruction *User = cast<Instruction>(*UI); |
| 1300 | |
| 1301 | // Preincrement use iterator so we don't invalidate it. |
| 1302 | ++UI; |
| 1303 | |
| 1304 | DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n"); |
| 1305 | |
| 1306 | // Keep the 'and' in the same place if the use is already in the same block. |
| 1307 | Instruction *InsertPt = |
| 1308 | User->getParent() == AndI->getParent() ? AndI : User; |
| 1309 | Instruction *InsertedAnd = |
| 1310 | BinaryOperator::Create(Instruction::And, AndI->getOperand(0), |
| 1311 | AndI->getOperand(1), "", InsertPt); |
| 1312 | // Propagate the debug info. |
| 1313 | InsertedAnd->setDebugLoc(AndI->getDebugLoc()); |
| 1314 | |
| 1315 | // Replace a use of the 'and' with a use of the new 'and'. |
| 1316 | TheUse = InsertedAnd; |
| 1317 | ++NumAndUses; |
| 1318 | DEBUG(User->getParent()->dump()); |
| 1319 | } |
| 1320 | |
| 1321 | // We removed all uses, nuke the and. |
| 1322 | AndI->eraseFromParent(); |
| 1323 | return true; |
| 1324 | } |
| 1325 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1326 | /// Check if the candidates could be combined with a shift instruction, which |
| 1327 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1328 | /// 1. Truncate instruction |
| 1329 | /// 2. And instruction and the imm is a mask of the low bits: |
| 1330 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 1331 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1332 | if (!isa<TruncInst>(User)) { |
| 1333 | if (User->getOpcode() != Instruction::And || |
| 1334 | !isa<ConstantInt>(User->getOperand(1))) |
| 1335 | return false; |
| 1336 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1337 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1338 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1339 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1340 | return false; |
| 1341 | } |
| 1342 | return true; |
| 1343 | } |
| 1344 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1345 | /// 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] | 1346 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1347 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 1348 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1349 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1350 | BasicBlock *UserBB = User->getParent(); |
| 1351 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 1352 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 1353 | bool MadeChange = false; |
| 1354 | |
| 1355 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 1356 | TruncE = TruncI->user_end(); |
| 1357 | TruncUI != TruncE;) { |
| 1358 | |
| 1359 | Use &TruncTheUse = TruncUI.getUse(); |
| 1360 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 1361 | // Preincrement use iterator so we don't invalidate it. |
| 1362 | |
| 1363 | ++TruncUI; |
| 1364 | |
| 1365 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 1366 | if (!ISDOpcode) |
| 1367 | continue; |
| 1368 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 1369 | // If the use is actually a legal node, there will not be an |
| 1370 | // implicit truncate. |
| 1371 | // FIXME: always querying the result type is just an |
| 1372 | // approximation; some nodes' legality is determined by the |
| 1373 | // 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] | 1374 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1375 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1376 | continue; |
| 1377 | |
| 1378 | // Don't bother for PHI nodes. |
| 1379 | if (isa<PHINode>(TruncUser)) |
| 1380 | continue; |
| 1381 | |
| 1382 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 1383 | |
| 1384 | if (UserBB == TruncUserBB) |
| 1385 | continue; |
| 1386 | |
| 1387 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 1388 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 1389 | |
| 1390 | if (!InsertedShift && !InsertedTrunc) { |
| 1391 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1392 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1393 | // Sink the shift |
| 1394 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1395 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1396 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1397 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1398 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1399 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1400 | |
| 1401 | // Sink the trunc |
| 1402 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 1403 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1404 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1405 | |
| 1406 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1407 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1408 | |
| 1409 | MadeChange = true; |
| 1410 | |
| 1411 | TruncTheUse = InsertedTrunc; |
| 1412 | } |
| 1413 | } |
| 1414 | return MadeChange; |
| 1415 | } |
| 1416 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1417 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1418 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1419 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1420 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1421 | /// BB1: |
| 1422 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1423 | /// BB2: |
| 1424 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1425 | /// ==> |
| 1426 | /// |
| 1427 | /// BB2: |
| 1428 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1429 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1430 | /// |
| 1431 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1432 | /// instruction. |
| 1433 | /// Return true if any changes are made. |
| 1434 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1435 | const TargetLowering &TLI, |
| 1436 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1437 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1438 | |
| 1439 | /// Only insert instructions in each block once. |
| 1440 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1441 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1442 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1443 | |
| 1444 | bool MadeChange = false; |
| 1445 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1446 | UI != E;) { |
| 1447 | Use &TheUse = UI.getUse(); |
| 1448 | Instruction *User = cast<Instruction>(*UI); |
| 1449 | // Preincrement use iterator so we don't invalidate it. |
| 1450 | ++UI; |
| 1451 | |
| 1452 | // Don't bother for PHI nodes. |
| 1453 | if (isa<PHINode>(User)) |
| 1454 | continue; |
| 1455 | |
| 1456 | if (!isExtractBitsCandidateUse(User)) |
| 1457 | continue; |
| 1458 | |
| 1459 | BasicBlock *UserBB = User->getParent(); |
| 1460 | |
| 1461 | if (UserBB == DefBB) { |
| 1462 | // If the shift and truncate instruction are in the same BB. The use of |
| 1463 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1464 | // legal. In this case, we would like to sink both shift and truncate |
| 1465 | // instruction to the BB of TruncUse. |
| 1466 | // for example: |
| 1467 | // BB1: |
| 1468 | // i64 shift.result = lshr i64 opnd, imm |
| 1469 | // trunc.result = trunc shift.result to i16 |
| 1470 | // |
| 1471 | // BB2: |
| 1472 | // ----> We will have an implicit truncate here if the architecture does |
| 1473 | // not have i16 compare. |
| 1474 | // cmp i16 trunc.result, opnd2 |
| 1475 | // |
| 1476 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1477 | // If the type of the truncate is legal, no trucate will be |
| 1478 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1479 | && |
| 1480 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1481 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1482 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1483 | |
| 1484 | continue; |
| 1485 | } |
| 1486 | // If we have already inserted a shift into this block, use it. |
| 1487 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1488 | |
| 1489 | if (!InsertedShift) { |
| 1490 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1491 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1492 | |
| 1493 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1494 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1495 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1496 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1497 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1498 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1499 | |
| 1500 | MadeChange = true; |
| 1501 | } |
| 1502 | |
| 1503 | // Replace a use of the shift with a use of the new shift. |
| 1504 | TheUse = InsertedShift; |
| 1505 | } |
| 1506 | |
| 1507 | // If we removed all uses, nuke the shift. |
| 1508 | if (ShiftI->use_empty()) |
| 1509 | ShiftI->eraseFromParent(); |
| 1510 | |
| 1511 | return MadeChange; |
| 1512 | } |
| 1513 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1514 | // Translate a masked load intrinsic like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1515 | // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, |
| 1516 | // <16 x i1> %mask, <16 x i32> %passthru) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1517 | // 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] | 1518 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1519 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1520 | // %1 = bitcast i8* %addr to i32* |
| 1521 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1522 | // %3 = icmp eq i1 %2, true |
| 1523 | // br i1 %3, label %cond.load, label %else |
| 1524 | // |
| 1525 | //cond.load: ; preds = %0 |
| 1526 | // %4 = getelementptr i32* %1, i32 0 |
| 1527 | // %5 = load i32* %4 |
| 1528 | // %6 = insertelement <16 x i32> undef, i32 %5, i32 0 |
| 1529 | // br label %else |
| 1530 | // |
| 1531 | //else: ; preds = %0, %cond.load |
| 1532 | // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] |
| 1533 | // %7 = extractelement <16 x i1> %mask, i32 1 |
| 1534 | // %8 = icmp eq i1 %7, true |
| 1535 | // br i1 %8, label %cond.load1, label %else2 |
| 1536 | // |
| 1537 | //cond.load1: ; preds = %else |
| 1538 | // %9 = getelementptr i32* %1, i32 1 |
| 1539 | // %10 = load i32* %9 |
| 1540 | // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 |
| 1541 | // br label %else2 |
| 1542 | // |
| 1543 | //else2: ; preds = %else, %cond.load1 |
| 1544 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1545 | // %12 = extractelement <16 x i1> %mask, i32 2 |
| 1546 | // %13 = icmp eq i1 %12, true |
| 1547 | // br i1 %13, label %cond.load4, label %else5 |
| 1548 | // |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1549 | static void scalarizeMaskedLoad(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1550 | Value *Ptr = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1551 | Value *Alignment = CI->getArgOperand(1); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1552 | Value *Mask = CI->getArgOperand(2); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1553 | Value *Src0 = CI->getArgOperand(3); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1554 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1555 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1556 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1557 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1558 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1559 | Type *EltTy = CI->getType()->getVectorElementType(); |
| 1560 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1561 | IRBuilder<> Builder(CI->getContext()); |
| 1562 | Instruction *InsertPt = CI; |
| 1563 | BasicBlock *IfBlock = CI->getParent(); |
| 1564 | BasicBlock *CondBlock = nullptr; |
| 1565 | BasicBlock *PrevIfBlock = CI->getParent(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1566 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1567 | Builder.SetInsertPoint(InsertPt); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1568 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1569 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1570 | // Short-cut if the mask is all-true. |
| 1571 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1572 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1573 | |
| 1574 | if (IsAllOnesMask) { |
| 1575 | Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); |
| 1576 | CI->replaceAllUsesWith(NewI); |
| 1577 | CI->eraseFromParent(); |
| 1578 | return; |
| 1579 | } |
| 1580 | |
| 1581 | // Adjust alignment for the scalar instruction. |
| 1582 | AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1583 | // Bitcast %addr fron i8* to EltTy* |
| 1584 | Type *NewPtrType = |
| 1585 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1586 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1587 | unsigned VectorWidth = VecType->getNumElements(); |
| 1588 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1589 | Value *UndefVal = UndefValue::get(VecType); |
| 1590 | |
| 1591 | // The result vector |
| 1592 | Value *VResult = UndefVal; |
| 1593 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1594 | if (isa<ConstantVector>(Mask)) { |
| 1595 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1596 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1597 | continue; |
| 1598 | Value *Gep = |
| 1599 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1600 | LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
| 1601 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1602 | Builder.getInt32(Idx)); |
| 1603 | } |
| 1604 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1605 | CI->replaceAllUsesWith(NewI); |
| 1606 | CI->eraseFromParent(); |
| 1607 | return; |
| 1608 | } |
| 1609 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1610 | PHINode *Phi = nullptr; |
| 1611 | Value *PrevPhi = UndefVal; |
| 1612 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1613 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1614 | |
| 1615 | // Fill the "else" block, created in the previous iteration |
| 1616 | // |
| 1617 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1618 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1619 | // %to_load = icmp eq i1 %mask_1, true |
| 1620 | // br i1 %to_load, label %cond.load, label %else |
| 1621 | // |
| 1622 | if (Idx > 0) { |
| 1623 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1624 | Phi->addIncoming(VResult, CondBlock); |
| 1625 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1626 | PrevPhi = Phi; |
| 1627 | VResult = Phi; |
| 1628 | } |
| 1629 | |
| 1630 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1631 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1632 | ConstantInt::get(Predicate->getType(), 1)); |
| 1633 | |
| 1634 | // Create "cond" block |
| 1635 | // |
| 1636 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1637 | // %Elt = load i32* %EltAddr |
| 1638 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1639 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1640 | CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1641 | Builder.SetInsertPoint(InsertPt); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1642 | |
| 1643 | Value *Gep = |
| 1644 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1645 | LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1646 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); |
| 1647 | |
| 1648 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1649 | BasicBlock *NewIfBlock = |
| 1650 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1651 | Builder.SetInsertPoint(InsertPt); |
| 1652 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1653 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1654 | OldBr->eraseFromParent(); |
| 1655 | PrevIfBlock = IfBlock; |
| 1656 | IfBlock = NewIfBlock; |
| 1657 | } |
| 1658 | |
| 1659 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1660 | Phi->addIncoming(VResult, CondBlock); |
| 1661 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1662 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1663 | CI->replaceAllUsesWith(NewI); |
| 1664 | CI->eraseFromParent(); |
| 1665 | } |
| 1666 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1667 | // Translate a masked store intrinsic, like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1668 | // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, |
| 1669 | // <16 x i1> %mask) |
| 1670 | // to a chain of basic blocks, that stores element one-by-one if |
| 1671 | // the appropriate mask bit is set |
| 1672 | // |
| 1673 | // %1 = bitcast i8* %addr to i32* |
| 1674 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1675 | // %3 = icmp eq i1 %2, true |
| 1676 | // br i1 %3, label %cond.store, label %else |
| 1677 | // |
| 1678 | // cond.store: ; preds = %0 |
| 1679 | // %4 = extractelement <16 x i32> %val, i32 0 |
| 1680 | // %5 = getelementptr i32* %1, i32 0 |
| 1681 | // store i32 %4, i32* %5 |
| 1682 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1683 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1684 | // else: ; preds = %0, %cond.store |
| 1685 | // %6 = extractelement <16 x i1> %mask, i32 1 |
| 1686 | // %7 = icmp eq i1 %6, true |
| 1687 | // br i1 %7, label %cond.store1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1688 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1689 | // cond.store1: ; preds = %else |
| 1690 | // %8 = extractelement <16 x i32> %val, i32 1 |
| 1691 | // %9 = getelementptr i32* %1, i32 1 |
| 1692 | // store i32 %8, i32* %9 |
| 1693 | // br label %else2 |
| 1694 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1695 | static void scalarizeMaskedStore(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1696 | Value *Src = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1697 | Value *Ptr = CI->getArgOperand(1); |
| 1698 | Value *Alignment = CI->getArgOperand(2); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1699 | Value *Mask = CI->getArgOperand(3); |
| 1700 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1701 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1702 | VectorType *VecType = dyn_cast<VectorType>(Src->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1703 | assert(VecType && "Unexpected data type in masked store intrinsic"); |
| 1704 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1705 | Type *EltTy = VecType->getElementType(); |
| 1706 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1707 | IRBuilder<> Builder(CI->getContext()); |
| 1708 | Instruction *InsertPt = CI; |
| 1709 | BasicBlock *IfBlock = CI->getParent(); |
| 1710 | Builder.SetInsertPoint(InsertPt); |
| 1711 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1712 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1713 | // Short-cut if the mask is all-true. |
| 1714 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1715 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1716 | |
| 1717 | if (IsAllOnesMask) { |
| 1718 | Builder.CreateAlignedStore(Src, Ptr, AlignVal); |
| 1719 | CI->eraseFromParent(); |
| 1720 | return; |
| 1721 | } |
| 1722 | |
| 1723 | // Adjust alignment for the scalar instruction. |
| 1724 | AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1725 | // Bitcast %addr fron i8* to EltTy* |
| 1726 | Type *NewPtrType = |
| 1727 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1728 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1729 | unsigned VectorWidth = VecType->getNumElements(); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1730 | |
| 1731 | if (isa<ConstantVector>(Mask)) { |
| 1732 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1733 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1734 | continue; |
| 1735 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
| 1736 | Value *Gep = |
| 1737 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1738 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
| 1739 | } |
| 1740 | CI->eraseFromParent(); |
| 1741 | return; |
| 1742 | } |
| 1743 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1744 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1745 | |
| 1746 | // Fill the "else" block, created in the previous iteration |
| 1747 | // |
| 1748 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1749 | // %to_store = icmp eq i1 %mask_1, true |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1750 | // br i1 %to_store, label %cond.store, label %else |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1751 | // |
| 1752 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1753 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1754 | ConstantInt::get(Predicate->getType(), 1)); |
| 1755 | |
| 1756 | // Create "cond" block |
| 1757 | // |
| 1758 | // %OneElt = extractelement <16 x i32> %Src, i32 Idx |
| 1759 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1760 | // %store i32 %OneElt, i32* %EltAddr |
| 1761 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1762 | BasicBlock *CondBlock = |
| 1763 | IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1764 | Builder.SetInsertPoint(InsertPt); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1765 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1766 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1767 | Value *Gep = |
| 1768 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1769 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1770 | |
| 1771 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1772 | BasicBlock *NewIfBlock = |
| 1773 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1774 | Builder.SetInsertPoint(InsertPt); |
| 1775 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1776 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1777 | OldBr->eraseFromParent(); |
| 1778 | IfBlock = NewIfBlock; |
| 1779 | } |
| 1780 | CI->eraseFromParent(); |
| 1781 | } |
| 1782 | |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1783 | // Translate a masked gather intrinsic like |
| 1784 | // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, |
| 1785 | // <16 x i1> %Mask, <16 x i32> %Src) |
| 1786 | // to a chain of basic blocks, with loading element one-by-one if |
| 1787 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1788 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1789 | // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind |
| 1790 | // % Mask0 = extractelement <16 x i1> %Mask, i32 0 |
| 1791 | // % ToLoad0 = icmp eq i1 % Mask0, true |
| 1792 | // br i1 % ToLoad0, label %cond.load, label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1793 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1794 | // cond.load: |
| 1795 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1796 | // % Load0 = load i32, i32* % Ptr0, align 4 |
| 1797 | // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 |
| 1798 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1799 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1800 | // else: |
| 1801 | // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] |
| 1802 | // % Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1803 | // % ToLoad1 = icmp eq i1 % Mask1, true |
| 1804 | // br i1 % ToLoad1, label %cond.load1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1805 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1806 | // cond.load1: |
| 1807 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1808 | // % Load1 = load i32, i32* % Ptr1, align 4 |
| 1809 | // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 |
| 1810 | // br label %else2 |
| 1811 | // . . . |
| 1812 | // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src |
| 1813 | // ret <16 x i32> %Result |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1814 | static void scalarizeMaskedGather(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1815 | Value *Ptrs = CI->getArgOperand(0); |
| 1816 | Value *Alignment = CI->getArgOperand(1); |
| 1817 | Value *Mask = CI->getArgOperand(2); |
| 1818 | Value *Src0 = CI->getArgOperand(3); |
| 1819 | |
| 1820 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
| 1821 | |
| 1822 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1823 | |
| 1824 | IRBuilder<> Builder(CI->getContext()); |
| 1825 | Instruction *InsertPt = CI; |
| 1826 | BasicBlock *IfBlock = CI->getParent(); |
| 1827 | BasicBlock *CondBlock = nullptr; |
| 1828 | BasicBlock *PrevIfBlock = CI->getParent(); |
| 1829 | Builder.SetInsertPoint(InsertPt); |
| 1830 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1831 | |
| 1832 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1833 | |
| 1834 | Value *UndefVal = UndefValue::get(VecType); |
| 1835 | |
| 1836 | // The result vector |
| 1837 | Value *VResult = UndefVal; |
| 1838 | unsigned VectorWidth = VecType->getNumElements(); |
| 1839 | |
| 1840 | // Shorten the way if the mask is a vector of constants. |
| 1841 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1842 | |
| 1843 | if (IsConstMask) { |
| 1844 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1845 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1846 | continue; |
| 1847 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1848 | "Ptr" + Twine(Idx)); |
| 1849 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1850 | "Load" + Twine(Idx)); |
| 1851 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1852 | Builder.getInt32(Idx), |
| 1853 | "Res" + Twine(Idx)); |
| 1854 | } |
| 1855 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1856 | CI->replaceAllUsesWith(NewI); |
| 1857 | CI->eraseFromParent(); |
| 1858 | return; |
| 1859 | } |
| 1860 | |
| 1861 | PHINode *Phi = nullptr; |
| 1862 | Value *PrevPhi = UndefVal; |
| 1863 | |
| 1864 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1865 | |
| 1866 | // Fill the "else" block, created in the previous iteration |
| 1867 | // |
| 1868 | // %Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1869 | // %ToLoad1 = icmp eq i1 %Mask1, true |
| 1870 | // br i1 %ToLoad1, label %cond.load, label %else |
| 1871 | // |
| 1872 | if (Idx > 0) { |
| 1873 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1874 | Phi->addIncoming(VResult, CondBlock); |
| 1875 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1876 | PrevPhi = Phi; |
| 1877 | VResult = Phi; |
| 1878 | } |
| 1879 | |
| 1880 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1881 | Builder.getInt32(Idx), |
| 1882 | "Mask" + Twine(Idx)); |
| 1883 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1884 | ConstantInt::get(Predicate->getType(), 1), |
| 1885 | "ToLoad" + Twine(Idx)); |
| 1886 | |
| 1887 | // Create "cond" block |
| 1888 | // |
| 1889 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1890 | // %Elt = load i32* %EltAddr |
| 1891 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1892 | // |
| 1893 | CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); |
| 1894 | Builder.SetInsertPoint(InsertPt); |
| 1895 | |
| 1896 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1897 | "Ptr" + Twine(Idx)); |
| 1898 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1899 | "Load" + Twine(Idx)); |
| 1900 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), |
| 1901 | "Res" + Twine(Idx)); |
| 1902 | |
| 1903 | // Create "else" block, fill it in the next iteration |
| 1904 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1905 | Builder.SetInsertPoint(InsertPt); |
| 1906 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1907 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1908 | OldBr->eraseFromParent(); |
| 1909 | PrevIfBlock = IfBlock; |
| 1910 | IfBlock = NewIfBlock; |
| 1911 | } |
| 1912 | |
| 1913 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1914 | Phi->addIncoming(VResult, CondBlock); |
| 1915 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1916 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1917 | CI->replaceAllUsesWith(NewI); |
| 1918 | CI->eraseFromParent(); |
| 1919 | } |
| 1920 | |
| 1921 | // Translate a masked scatter intrinsic, like |
| 1922 | // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, |
| 1923 | // <16 x i1> %Mask) |
| 1924 | // to a chain of basic blocks, that stores element one-by-one if |
| 1925 | // the appropriate mask bit is set. |
| 1926 | // |
| 1927 | // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind |
| 1928 | // % Mask0 = extractelement <16 x i1> % Mask, i32 0 |
| 1929 | // % ToStore0 = icmp eq i1 % Mask0, true |
| 1930 | // br i1 %ToStore0, label %cond.store, label %else |
| 1931 | // |
| 1932 | // cond.store: |
| 1933 | // % Elt0 = extractelement <16 x i32> %Src, i32 0 |
| 1934 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1935 | // store i32 %Elt0, i32* % Ptr0, align 4 |
| 1936 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1937 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1938 | // else: |
| 1939 | // % Mask1 = extractelement <16 x i1> % Mask, i32 1 |
| 1940 | // % ToStore1 = icmp eq i1 % Mask1, true |
| 1941 | // br i1 % ToStore1, label %cond.store1, label %else2 |
| 1942 | // |
| 1943 | // cond.store1: |
| 1944 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1945 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1946 | // store i32 % Elt1, i32* % Ptr1, align 4 |
| 1947 | // br label %else2 |
| 1948 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1949 | static void scalarizeMaskedScatter(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1950 | Value *Src = CI->getArgOperand(0); |
| 1951 | Value *Ptrs = CI->getArgOperand(1); |
| 1952 | Value *Alignment = CI->getArgOperand(2); |
| 1953 | Value *Mask = CI->getArgOperand(3); |
| 1954 | |
| 1955 | assert(isa<VectorType>(Src->getType()) && |
| 1956 | "Unexpected data type in masked scatter intrinsic"); |
| 1957 | assert(isa<VectorType>(Ptrs->getType()) && |
| 1958 | isa<PointerType>(Ptrs->getType()->getVectorElementType()) && |
| 1959 | "Vector of pointers is expected in masked scatter intrinsic"); |
| 1960 | |
| 1961 | IRBuilder<> Builder(CI->getContext()); |
| 1962 | Instruction *InsertPt = CI; |
| 1963 | BasicBlock *IfBlock = CI->getParent(); |
| 1964 | Builder.SetInsertPoint(InsertPt); |
| 1965 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1966 | |
| 1967 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1968 | unsigned VectorWidth = Src->getType()->getVectorNumElements(); |
| 1969 | |
| 1970 | // Shorten the way if the mask is a vector of constants. |
| 1971 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1972 | |
| 1973 | if (IsConstMask) { |
| 1974 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1975 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1976 | continue; |
| 1977 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1978 | "Elt" + Twine(Idx)); |
| 1979 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1980 | "Ptr" + Twine(Idx)); |
| 1981 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1982 | } |
| 1983 | CI->eraseFromParent(); |
| 1984 | return; |
| 1985 | } |
| 1986 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1987 | // Fill the "else" block, created in the previous iteration |
| 1988 | // |
| 1989 | // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx |
| 1990 | // % ToStore = icmp eq i1 % Mask1, true |
| 1991 | // br i1 % ToStore, label %cond.store, label %else |
| 1992 | // |
| 1993 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1994 | Builder.getInt32(Idx), |
| 1995 | "Mask" + Twine(Idx)); |
| 1996 | Value *Cmp = |
| 1997 | Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1998 | ConstantInt::get(Predicate->getType(), 1), |
| 1999 | "ToStore" + Twine(Idx)); |
| 2000 | |
| 2001 | // Create "cond" block |
| 2002 | // |
| 2003 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 2004 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 2005 | // %store i32 % Elt1, i32* % Ptr1 |
| 2006 | // |
| 2007 | BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); |
| 2008 | Builder.SetInsertPoint(InsertPt); |
| 2009 | |
| 2010 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 2011 | "Elt" + Twine(Idx)); |
| 2012 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 2013 | "Ptr" + Twine(Idx)); |
| 2014 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 2015 | |
| 2016 | // Create "else" block, fill it in the next iteration |
| 2017 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 2018 | Builder.SetInsertPoint(InsertPt); |
| 2019 | Instruction *OldBr = IfBlock->getTerminator(); |
| 2020 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 2021 | OldBr->eraseFromParent(); |
| 2022 | IfBlock = NewIfBlock; |
| 2023 | } |
| 2024 | CI->eraseFromParent(); |
| 2025 | } |
| 2026 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2027 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 2028 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 2029 | /// |
| 2030 | /// We want to transform: |
| 2031 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 2032 | /// |
| 2033 | /// into: |
| 2034 | /// entry: |
| 2035 | /// %cmpz = icmp eq i64 %A, 0 |
| 2036 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 2037 | /// cond.false: |
| 2038 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 2039 | /// br label %cond.end |
| 2040 | /// cond.end: |
| 2041 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 2042 | /// |
| 2043 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 2044 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 2045 | const TargetLowering *TLI, |
| 2046 | const DataLayout *DL, |
| 2047 | bool &ModifiedDT) { |
| 2048 | if (!TLI || !DL) |
| 2049 | return false; |
| 2050 | |
| 2051 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 2052 | if (match(CountZeros->getOperand(1), m_One())) |
| 2053 | return false; |
| 2054 | |
| 2055 | // If it's cheap to speculate, there's nothing to do. |
| 2056 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 2057 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 2058 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 2059 | return false; |
| 2060 | |
| 2061 | // Only handle legal scalar cases. Anything else requires too much work. |
| 2062 | Type *Ty = CountZeros->getType(); |
| 2063 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 2064 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2065 | return false; |
| 2066 | |
| 2067 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 2068 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 2069 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 2070 | |
| 2071 | // Create another block after the count zero intrinsic. A PHI will be added |
| 2072 | // in this block to select the result of the intrinsic or the bit-width |
| 2073 | // constant if the input to the intrinsic is zero. |
| 2074 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 2075 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 2076 | |
| 2077 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 2078 | IRBuilder<> Builder(CountZeros->getContext()); |
| 2079 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 2080 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 2081 | |
| 2082 | // Replace the unconditional branch that was created by the first split with |
| 2083 | // a compare against zero and a conditional branch. |
| 2084 | Value *Zero = Constant::getNullValue(Ty); |
| 2085 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 2086 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 2087 | StartBlock->getTerminator()->eraseFromParent(); |
| 2088 | |
| 2089 | // Create a PHI in the end block to select either the output of the intrinsic |
| 2090 | // or the bit width of the operand. |
| 2091 | Builder.SetInsertPoint(&EndBlock->front()); |
| 2092 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 2093 | CountZeros->replaceAllUsesWith(PN); |
| 2094 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 2095 | PN->addIncoming(BitWidth, StartBlock); |
| 2096 | PN->addIncoming(CountZeros, CallBlock); |
| 2097 | |
| 2098 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 2099 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 2100 | // intrinsic; we only despeculate when a zero input is defined. |
| 2101 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 2102 | ModifiedDT = true; |
| 2103 | return true; |
| 2104 | } |
| 2105 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2106 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2107 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2108 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2109 | // Lower inline assembly if we can. |
| 2110 | // If we found an inline asm expession, and if the target knows how to |
| 2111 | // lower it to normal LLVM code, do so now. |
| 2112 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 2113 | if (TLI->ExpandInlineAsm(CI)) { |
| 2114 | // Avoid invalidating the iterator. |
| 2115 | CurInstIterator = BB->begin(); |
| 2116 | // Avoid processing instructions out of order, which could cause |
| 2117 | // reuse before a value is defined. |
| 2118 | SunkAddrs.clear(); |
| 2119 | return true; |
| 2120 | } |
| 2121 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2122 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2123 | return true; |
| 2124 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2125 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2126 | // Align the pointer arguments to this call if the target thinks it's a good |
| 2127 | // idea |
| 2128 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2129 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2130 | for (auto &Arg : CI->arg_operands()) { |
| 2131 | // We want to align both objects whose address is used directly and |
| 2132 | // objects whose address is used in casts and GEPs, though it only makes |
| 2133 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 2134 | // if size - offset meets the size threshold. |
| 2135 | if (!Arg->getType()->isPointerTy()) |
| 2136 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2137 | APInt Offset(DL->getPointerSizeInBits( |
| 2138 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 2139 | 0); |
| 2140 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2141 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2142 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 2143 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2144 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2145 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 2146 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2147 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2148 | // Global variables can only be aligned if they are defined in this |
| 2149 | // object (i.e. they are uniquely initialized in this object), and |
| 2150 | // over-aligning global variables that have an explicit section is |
| 2151 | // forbidden. |
| 2152 | GlobalVariable *GV; |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 2153 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && |
Tim Northover | 918f050 | 2016-07-18 18:28:52 +0000 | [diff] [blame] | 2154 | GV->getPointerAlignment(*DL) < PrefAlign && |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 2155 | DL->getTypeAllocSize(GV->getValueType()) >= |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2156 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2157 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2158 | } |
| 2159 | // If this is a memcpy (or similar) then we may be able to improve the |
| 2160 | // alignment |
| 2161 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2162 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2163 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2164 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 2165 | if (Align > MI->getAlignment()) |
| 2166 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2167 | } |
| 2168 | } |
| 2169 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 2170 | // If we have a cold call site, try to sink addressing computation into the |
| 2171 | // cold block. This interacts with our handling for loads and stores to |
| 2172 | // ensure that we can fold all uses of a potential addressing computation |
| 2173 | // into their uses. TODO: generalize this to work over profiling data |
| 2174 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 2175 | for (auto &Arg : CI->arg_operands()) { |
| 2176 | if (!Arg->getType()->isPointerTy()) |
| 2177 | continue; |
| 2178 | unsigned AS = Arg->getType()->getPointerAddressSpace(); |
| 2179 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); |
| 2180 | } |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 2181 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2182 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2183 | if (II) { |
| 2184 | switch (II->getIntrinsicID()) { |
| 2185 | default: break; |
| 2186 | case Intrinsic::objectsize: { |
| 2187 | // Lower all uses of llvm.objectsize.* |
George Burgess IV | 3f08914 | 2016-12-20 23:46:36 +0000 | [diff] [blame] | 2188 | ConstantInt *RetVal = |
| 2189 | lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2190 | // Substituting this can cause recursive simplifications, which can |
| 2191 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 2192 | // happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 2193 | Value *CurValue = &*CurInstIterator; |
| 2194 | WeakVH IterHandle(CurValue); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2195 | |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 2196 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 2197 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2198 | // If the iterator instruction was recursively deleted, start over at the |
| 2199 | // start of the block. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 2200 | if (IterHandle != CurValue) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2201 | CurInstIterator = BB->begin(); |
| 2202 | SunkAddrs.clear(); |
| 2203 | } |
| 2204 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 2205 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2206 | case Intrinsic::masked_load: { |
| 2207 | // Scalarize unsupported vector masked load |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 2208 | if (!TTI->isLegalMaskedLoad(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2209 | scalarizeMaskedLoad(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2210 | ModifiedDT = true; |
| 2211 | return true; |
| 2212 | } |
| 2213 | return false; |
| 2214 | } |
| 2215 | case Intrinsic::masked_store: { |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 2216 | if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2217 | scalarizeMaskedStore(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2218 | ModifiedDT = true; |
| 2219 | return true; |
| 2220 | } |
| 2221 | return false; |
| 2222 | } |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 2223 | case Intrinsic::masked_gather: { |
| 2224 | if (!TTI->isLegalMaskedGather(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2225 | scalarizeMaskedGather(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 2226 | ModifiedDT = true; |
| 2227 | return true; |
| 2228 | } |
| 2229 | return false; |
| 2230 | } |
| 2231 | case Intrinsic::masked_scatter: { |
| 2232 | if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2233 | scalarizeMaskedScatter(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 2234 | ModifiedDT = true; |
| 2235 | return true; |
| 2236 | } |
| 2237 | return false; |
| 2238 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2239 | case Intrinsic::aarch64_stlxr: |
| 2240 | case Intrinsic::aarch64_stxr: { |
| 2241 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 2242 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 2243 | ExtVal->getParent() == CI->getParent()) |
| 2244 | return false; |
| 2245 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 2246 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2247 | // Mark this instruction as "inserted by CGP", so that other |
| 2248 | // optimizations don't touch it. |
| 2249 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2250 | return true; |
| 2251 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 2252 | case Intrinsic::invariant_group_barrier: |
| 2253 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 2254 | II->eraseFromParent(); |
| 2255 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2256 | |
| 2257 | case Intrinsic::cttz: |
| 2258 | case Intrinsic::ctlz: |
| 2259 | // If counting zeros is expensive, try to avoid it. |
| 2260 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2261 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2262 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2263 | if (TLI) { |
| 2264 | SmallVector<Value*, 2> PtrOps; |
| 2265 | Type *AccessTy; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 2266 | if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) |
| 2267 | while (!PtrOps.empty()) { |
| 2268 | Value *PtrVal = PtrOps.pop_back_val(); |
| 2269 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); |
| 2270 | if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2271 | return true; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 2272 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2273 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 2274 | } |
| 2275 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2276 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2277 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 2278 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 2279 | // Lower all default uses of _chk calls. This is very similar |
| 2280 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2281 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 2282 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2283 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2284 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 2285 | CI->replaceAllUsesWith(V); |
| 2286 | CI->eraseFromParent(); |
| 2287 | return true; |
| 2288 | } |
| 2289 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2290 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 2291 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2292 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 2293 | /// 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] | 2294 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2295 | /// bb0: |
| 2296 | /// %tmp0 = tail call i32 @f0() |
| 2297 | /// br label %return |
| 2298 | /// bb1: |
| 2299 | /// %tmp1 = tail call i32 @f1() |
| 2300 | /// br label %return |
| 2301 | /// bb2: |
| 2302 | /// %tmp2 = tail call i32 @f2() |
| 2303 | /// br label %return |
| 2304 | /// return: |
| 2305 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 2306 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2307 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2308 | /// |
| 2309 | /// => |
| 2310 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2311 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2312 | /// bb0: |
| 2313 | /// %tmp0 = tail call i32 @f0() |
| 2314 | /// ret i32 %tmp0 |
| 2315 | /// bb1: |
| 2316 | /// %tmp1 = tail call i32 @f1() |
| 2317 | /// ret i32 %tmp1 |
| 2318 | /// bb2: |
| 2319 | /// %tmp2 = tail call i32 @f2() |
| 2320 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2321 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2322 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 2323 | if (!TLI) |
| 2324 | return false; |
| 2325 | |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2326 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 2327 | if (!RetI) |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 2328 | return false; |
| 2329 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2330 | PHINode *PN = nullptr; |
| 2331 | BitCastInst *BCI = nullptr; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2332 | Value *V = RetI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2333 | if (V) { |
| 2334 | BCI = dyn_cast<BitCastInst>(V); |
| 2335 | if (BCI) |
| 2336 | V = BCI->getOperand(0); |
| 2337 | |
| 2338 | PN = dyn_cast<PHINode>(V); |
| 2339 | if (!PN) |
| 2340 | return false; |
| 2341 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2342 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2343 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2344 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2345 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2346 | // Make sure there are no instructions between the PHI and return, or that the |
| 2347 | // return is the first instruction in the block. |
| 2348 | if (PN) { |
| 2349 | BasicBlock::iterator BI = BB->begin(); |
| 2350 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2351 | if (&*BI == BCI) |
| 2352 | // Also skip over the bitcast. |
| 2353 | ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2354 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2355 | return false; |
| 2356 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2357 | BasicBlock::iterator BI = BB->begin(); |
| 2358 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2359 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2360 | return false; |
| 2361 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2362 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2363 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 2364 | /// call. |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2365 | const Function *F = BB->getParent(); |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2366 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2367 | if (PN) { |
| 2368 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 2369 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 2370 | // Make sure the phi value is indeed produced by the tail call. |
| 2371 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2372 | TLI->mayBeEmittedAsTailCall(CI) && |
| 2373 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2374 | TailCalls.push_back(CI); |
| 2375 | } |
| 2376 | } else { |
| 2377 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2378 | 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] | 2379 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2380 | continue; |
| 2381 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2382 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2383 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 2384 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2385 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 2386 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2387 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2388 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2389 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2390 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && |
| 2391 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2392 | TailCalls.push_back(CI); |
| 2393 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2394 | } |
| 2395 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2396 | bool Changed = false; |
| 2397 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 2398 | CallInst *CI = TailCalls[i]; |
| 2399 | CallSite CS(CI); |
| 2400 | |
| 2401 | // Conservatively require the attributes of the call to match those of the |
| 2402 | // return. Ignore noalias because it doesn't affect the call sequence. |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame^] | 2403 | AttributeList CalleeAttrs = CS.getAttributes(); |
| 2404 | if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 2405 | .removeAttribute(Attribute::NoAlias) != |
| 2406 | AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 2407 | .removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2408 | continue; |
| 2409 | |
| 2410 | // Make sure the call instruction is followed by an unconditional branch to |
| 2411 | // the return block. |
| 2412 | BasicBlock *CallBB = CI->getParent(); |
| 2413 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 2414 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 2415 | continue; |
| 2416 | |
| 2417 | // Duplicate the return into CallBB. |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2418 | (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 2419 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2420 | ++NumRetsDup; |
| 2421 | } |
| 2422 | |
| 2423 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 2424 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2425 | BB->eraseFromParent(); |
| 2426 | |
| 2427 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2428 | } |
| 2429 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2430 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2431 | // Memory Optimization |
| 2432 | //===----------------------------------------------------------------------===// |
| 2433 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2434 | namespace { |
| 2435 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2436 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2437 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 2438 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2439 | Value *BaseReg; |
| 2440 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2441 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2442 | void print(raw_ostream &OS) const; |
| 2443 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2444 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2445 | bool operator==(const ExtAddrMode& O) const { |
| 2446 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 2447 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 2448 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 2449 | } |
| 2450 | }; |
| 2451 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2452 | #ifndef NDEBUG |
| 2453 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2454 | AM.print(OS); |
| 2455 | return OS; |
| 2456 | } |
| 2457 | #endif |
| 2458 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2459 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2460 | bool NeedPlus = false; |
| 2461 | OS << "["; |
| 2462 | if (BaseGV) { |
| 2463 | OS << (NeedPlus ? " + " : "") |
| 2464 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2465 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2466 | NeedPlus = true; |
| 2467 | } |
| 2468 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2469 | if (BaseOffs) { |
| 2470 | OS << (NeedPlus ? " + " : "") |
| 2471 | << BaseOffs; |
| 2472 | NeedPlus = true; |
| 2473 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2474 | |
| 2475 | if (BaseReg) { |
| 2476 | OS << (NeedPlus ? " + " : "") |
| 2477 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2478 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2479 | NeedPlus = true; |
| 2480 | } |
| 2481 | if (Scale) { |
| 2482 | OS << (NeedPlus ? " + " : "") |
| 2483 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2484 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2485 | } |
| 2486 | |
| 2487 | OS << ']'; |
| 2488 | } |
| 2489 | |
| 2490 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Yaron Keren | eb2a254 | 2016-01-29 20:50:44 +0000 | [diff] [blame] | 2491 | LLVM_DUMP_METHOD void ExtAddrMode::dump() const { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2492 | print(dbgs()); |
| 2493 | dbgs() << '\n'; |
| 2494 | } |
| 2495 | #endif |
| 2496 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2497 | /// \brief This class provides transaction based operation on the IR. |
| 2498 | /// Every change made through this class is recorded in the internal state and |
| 2499 | /// can be undone (rollback) until commit is called. |
| 2500 | class TypePromotionTransaction { |
| 2501 | |
| 2502 | /// \brief This represents the common interface of the individual transaction. |
| 2503 | /// Each class implements the logic for doing one specific modification on |
| 2504 | /// the IR via the TypePromotionTransaction. |
| 2505 | class TypePromotionAction { |
| 2506 | protected: |
| 2507 | /// The Instruction modified. |
| 2508 | Instruction *Inst; |
| 2509 | |
| 2510 | public: |
| 2511 | /// \brief Constructor of the action. |
| 2512 | /// The constructor performs the related action on the IR. |
| 2513 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2514 | |
| 2515 | virtual ~TypePromotionAction() {} |
| 2516 | |
| 2517 | /// \brief Undo the modification done by this action. |
| 2518 | /// When this method is called, the IR must be in the same state as it was |
| 2519 | /// before this action was applied. |
| 2520 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2521 | /// state as it was directly after this action was applied. |
| 2522 | virtual void undo() = 0; |
| 2523 | |
| 2524 | /// \brief Advocate every change made by this action. |
| 2525 | /// When the results on the IR of the action are to be kept, it is important |
| 2526 | /// to call this function, otherwise hidden information may be kept forever. |
| 2527 | virtual void commit() { |
| 2528 | // Nothing to be done, this action is not doing anything. |
| 2529 | } |
| 2530 | }; |
| 2531 | |
| 2532 | /// \brief Utility to remember the position of an instruction. |
| 2533 | class InsertionHandler { |
| 2534 | /// Position of an instruction. |
| 2535 | /// Either an instruction: |
| 2536 | /// - Is the first in a basic block: BB is used. |
| 2537 | /// - Has a previous instructon: PrevInst is used. |
| 2538 | union { |
| 2539 | Instruction *PrevInst; |
| 2540 | BasicBlock *BB; |
| 2541 | } Point; |
| 2542 | /// Remember whether or not the instruction had a previous instruction. |
| 2543 | bool HasPrevInstruction; |
| 2544 | |
| 2545 | public: |
| 2546 | /// \brief Record the position of \p Inst. |
| 2547 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2548 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2549 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2550 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2551 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2552 | else |
| 2553 | Point.BB = Inst->getParent(); |
| 2554 | } |
| 2555 | |
| 2556 | /// \brief Insert \p Inst at the recorded position. |
| 2557 | void insert(Instruction *Inst) { |
| 2558 | if (HasPrevInstruction) { |
| 2559 | if (Inst->getParent()) |
| 2560 | Inst->removeFromParent(); |
| 2561 | Inst->insertAfter(Point.PrevInst); |
| 2562 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2563 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2564 | if (Inst->getParent()) |
| 2565 | Inst->moveBefore(Position); |
| 2566 | else |
| 2567 | Inst->insertBefore(Position); |
| 2568 | } |
| 2569 | } |
| 2570 | }; |
| 2571 | |
| 2572 | /// \brief Move an instruction before another. |
| 2573 | class InstructionMoveBefore : public TypePromotionAction { |
| 2574 | /// Original position of the instruction. |
| 2575 | InsertionHandler Position; |
| 2576 | |
| 2577 | public: |
| 2578 | /// \brief Move \p Inst before \p Before. |
| 2579 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2580 | : TypePromotionAction(Inst), Position(Inst) { |
| 2581 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2582 | Inst->moveBefore(Before); |
| 2583 | } |
| 2584 | |
| 2585 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2586 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2587 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2588 | Position.insert(Inst); |
| 2589 | } |
| 2590 | }; |
| 2591 | |
| 2592 | /// \brief Set the operand of an instruction with a new value. |
| 2593 | class OperandSetter : public TypePromotionAction { |
| 2594 | /// Original operand of the instruction. |
| 2595 | Value *Origin; |
| 2596 | /// Index of the modified instruction. |
| 2597 | unsigned Idx; |
| 2598 | |
| 2599 | public: |
| 2600 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2601 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2602 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2603 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2604 | << "for:" << *Inst << "\n" |
| 2605 | << "with:" << *NewVal << "\n"); |
| 2606 | Origin = Inst->getOperand(Idx); |
| 2607 | Inst->setOperand(Idx, NewVal); |
| 2608 | } |
| 2609 | |
| 2610 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2611 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2612 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2613 | << "for: " << *Inst << "\n" |
| 2614 | << "with: " << *Origin << "\n"); |
| 2615 | Inst->setOperand(Idx, Origin); |
| 2616 | } |
| 2617 | }; |
| 2618 | |
| 2619 | /// \brief Hide the operands of an instruction. |
| 2620 | /// Do as if this instruction was not using any of its operands. |
| 2621 | class OperandsHider : public TypePromotionAction { |
| 2622 | /// The list of original operands. |
| 2623 | SmallVector<Value *, 4> OriginalValues; |
| 2624 | |
| 2625 | public: |
| 2626 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2627 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2628 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2629 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2630 | OriginalValues.reserve(NumOpnds); |
| 2631 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2632 | // Save the current operand. |
| 2633 | Value *Val = Inst->getOperand(It); |
| 2634 | OriginalValues.push_back(Val); |
| 2635 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2636 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2637 | // that we are not willing to pay. |
| 2638 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2639 | } |
| 2640 | } |
| 2641 | |
| 2642 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2643 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2644 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2645 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2646 | Inst->setOperand(It, OriginalValues[It]); |
| 2647 | } |
| 2648 | }; |
| 2649 | |
| 2650 | /// \brief Build a truncate instruction. |
| 2651 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2652 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2653 | public: |
| 2654 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2655 | /// result. |
| 2656 | /// trunc Opnd to Ty. |
| 2657 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2658 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2659 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2660 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2661 | } |
| 2662 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2663 | /// \brief Get the built value. |
| 2664 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2665 | |
| 2666 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2667 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2668 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2669 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2670 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2671 | } |
| 2672 | }; |
| 2673 | |
| 2674 | /// \brief Build a sign extension instruction. |
| 2675 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2676 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2677 | public: |
| 2678 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2679 | /// result. |
| 2680 | /// sext Opnd to Ty. |
| 2681 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2682 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2683 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2684 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2685 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2686 | } |
| 2687 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2688 | /// \brief Get the built value. |
| 2689 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2690 | |
| 2691 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2692 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2693 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2694 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2695 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2696 | } |
| 2697 | }; |
| 2698 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2699 | /// \brief Build a zero extension instruction. |
| 2700 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2701 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2702 | public: |
| 2703 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2704 | /// result. |
| 2705 | /// zext Opnd to Ty. |
| 2706 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2707 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2708 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2709 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2710 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2711 | } |
| 2712 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2713 | /// \brief Get the built value. |
| 2714 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2715 | |
| 2716 | /// \brief Remove the built instruction. |
| 2717 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2718 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2719 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2720 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2721 | } |
| 2722 | }; |
| 2723 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2724 | /// \brief Mutate an instruction to another type. |
| 2725 | class TypeMutator : public TypePromotionAction { |
| 2726 | /// Record the original type. |
| 2727 | Type *OrigTy; |
| 2728 | |
| 2729 | public: |
| 2730 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2731 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2732 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2733 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2734 | << "\n"); |
| 2735 | Inst->mutateType(NewTy); |
| 2736 | } |
| 2737 | |
| 2738 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2739 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2740 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2741 | << "\n"); |
| 2742 | Inst->mutateType(OrigTy); |
| 2743 | } |
| 2744 | }; |
| 2745 | |
| 2746 | /// \brief Replace the uses of an instruction by another instruction. |
| 2747 | class UsesReplacer : public TypePromotionAction { |
| 2748 | /// Helper structure to keep track of the replaced uses. |
| 2749 | struct InstructionAndIdx { |
| 2750 | /// The instruction using the instruction. |
| 2751 | Instruction *Inst; |
| 2752 | /// The index where this instruction is used for Inst. |
| 2753 | unsigned Idx; |
| 2754 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2755 | : Inst(Inst), Idx(Idx) {} |
| 2756 | }; |
| 2757 | |
| 2758 | /// Keep track of the original uses (pair Instruction, Index). |
| 2759 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 2760 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 2761 | |
| 2762 | public: |
| 2763 | /// \brief Replace all the use of \p Inst by \p New. |
| 2764 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2765 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2766 | << "\n"); |
| 2767 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2768 | for (Use &U : Inst->uses()) { |
| 2769 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2770 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2771 | } |
| 2772 | // Now, we can replace the uses. |
| 2773 | Inst->replaceAllUsesWith(New); |
| 2774 | } |
| 2775 | |
| 2776 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2777 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2778 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2779 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2780 | EndIt = OriginalUses.end(); |
| 2781 | UseIt != EndIt; ++UseIt) { |
| 2782 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2783 | } |
| 2784 | } |
| 2785 | }; |
| 2786 | |
| 2787 | /// \brief Remove an instruction from the IR. |
| 2788 | class InstructionRemover : public TypePromotionAction { |
| 2789 | /// Original position of the instruction. |
| 2790 | InsertionHandler Inserter; |
| 2791 | /// Helper structure to hide all the link to the instruction. In other |
| 2792 | /// words, this helps to do as if the instruction was removed. |
| 2793 | OperandsHider Hider; |
| 2794 | /// Keep track of the uses replaced, if any. |
| 2795 | UsesReplacer *Replacer; |
| 2796 | |
| 2797 | public: |
| 2798 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2799 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2800 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 2801 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2802 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2803 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2804 | if (New) |
| 2805 | Replacer = new UsesReplacer(Inst, New); |
| 2806 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 2807 | Inst->removeFromParent(); |
| 2808 | } |
| 2809 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2810 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2811 | |
| 2812 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2813 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2814 | |
| 2815 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2816 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2817 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2818 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2819 | Inserter.insert(Inst); |
| 2820 | if (Replacer) |
| 2821 | Replacer->undo(); |
| 2822 | Hider.undo(); |
| 2823 | } |
| 2824 | }; |
| 2825 | |
| 2826 | public: |
| 2827 | /// Restoration point. |
| 2828 | /// The restoration point is a pointer to an action instead of an iterator |
| 2829 | /// because the iterator may be invalidated but not the pointer. |
| 2830 | typedef const TypePromotionAction *ConstRestorationPt; |
| 2831 | /// Advocate every changes made in that transaction. |
| 2832 | void commit(); |
| 2833 | /// Undo all the changes made after the given point. |
| 2834 | void rollback(ConstRestorationPt Point); |
| 2835 | /// Get the current restoration point. |
| 2836 | ConstRestorationPt getRestorationPoint() const; |
| 2837 | |
| 2838 | /// \name API for IR modification with state keeping to support rollback. |
| 2839 | /// @{ |
| 2840 | /// Same as Instruction::setOperand. |
| 2841 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2842 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2843 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2844 | /// Same as Value::replaceAllUsesWith. |
| 2845 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2846 | /// Same as Value::mutateType. |
| 2847 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2848 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2849 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2850 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2851 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2852 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2853 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2854 | /// Same as Instruction::moveBefore. |
| 2855 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2856 | /// @} |
| 2857 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2858 | private: |
| 2859 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2860 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2861 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2862 | }; |
| 2863 | |
| 2864 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2865 | Value *NewVal) { |
| 2866 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2867 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2868 | } |
| 2869 | |
| 2870 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2871 | Value *NewVal) { |
| 2872 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2873 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2874 | } |
| 2875 | |
| 2876 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2877 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2878 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2879 | } |
| 2880 | |
| 2881 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2882 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2883 | } |
| 2884 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2885 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2886 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2887 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2888 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2889 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2890 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2891 | } |
| 2892 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2893 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2894 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2895 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2896 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2897 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2898 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2899 | } |
| 2900 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2901 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2902 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2903 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2904 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2905 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2906 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2907 | } |
| 2908 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2909 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2910 | Instruction *Before) { |
| 2911 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2912 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2913 | } |
| 2914 | |
| 2915 | TypePromotionTransaction::ConstRestorationPt |
| 2916 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2917 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2918 | } |
| 2919 | |
| 2920 | void TypePromotionTransaction::commit() { |
| 2921 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2922 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2923 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2924 | Actions.clear(); |
| 2925 | } |
| 2926 | |
| 2927 | void TypePromotionTransaction::rollback( |
| 2928 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2929 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2930 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2931 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2932 | } |
| 2933 | } |
| 2934 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2935 | /// \brief A helper class for matching addressing modes. |
| 2936 | /// |
| 2937 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2938 | class AddressingModeMatcher { |
| 2939 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 2940 | const TargetLowering &TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2941 | const TargetRegisterInfo &TRI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2942 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2943 | |
| 2944 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2945 | /// the memory instruction that we're computing this address for. |
| 2946 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2947 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2948 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2949 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2950 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2951 | /// part of the return value of this addressing mode matching stuff. |
| 2952 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2953 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2954 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2955 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2956 | /// A map from the instructions to their type before promotion. |
| 2957 | InstrToOrigTy &PromotedInsts; |
| 2958 | /// The ongoing transaction where every action should be registered. |
| 2959 | TypePromotionTransaction &TPT; |
| 2960 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2961 | /// This is set to true when we should not do profitability checks. |
| 2962 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2963 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2964 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2965 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2966 | const TargetLowering &TLI, |
| 2967 | const TargetRegisterInfo &TRI, |
| 2968 | Type *AT, unsigned AS, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2969 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2970 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2971 | InstrToOrigTy &PromotedInsts, |
| 2972 | TypePromotionTransaction &TPT) |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2973 | : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2974 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 2975 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 2976 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2977 | IgnoreProfitability = false; |
| 2978 | } |
| 2979 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2980 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2981 | /// 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] | 2982 | /// give an access type of AccessTy. This returns a list of involved |
| 2983 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2984 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2985 | /// optimizations. |
| 2986 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2987 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2988 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2989 | Instruction *MemoryInst, |
| 2990 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2991 | const TargetLowering &TLI, |
| 2992 | const TargetRegisterInfo &TRI, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2993 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2994 | InstrToOrigTy &PromotedInsts, |
| 2995 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2996 | ExtAddrMode Result; |
| 2997 | |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2998 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, |
| 2999 | AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3000 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3001 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3002 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3003 | return Result; |
| 3004 | } |
| 3005 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3006 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 3007 | bool matchAddr(Value *V, unsigned Depth); |
| 3008 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3009 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3010 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3011 | ExtAddrMode &AMBefore, |
| 3012 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3013 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 3014 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3015 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3016 | }; |
| 3017 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3018 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3019 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 3020 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3021 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3022 | unsigned Depth) { |
| 3023 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 3024 | // mode. Just process that directly. |
| 3025 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3026 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3027 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3028 | // If the scale is 0, it takes nothing to add this. |
| 3029 | if (Scale == 0) |
| 3030 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3031 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3032 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 3033 | // need an available scale field. |
| 3034 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 3035 | return false; |
| 3036 | |
| 3037 | ExtAddrMode TestAddrMode = AddrMode; |
| 3038 | |
| 3039 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 3040 | // [A+B + A*7] -> [B+A*8]. |
| 3041 | TestAddrMode.Scale += Scale; |
| 3042 | TestAddrMode.ScaledReg = ScaleReg; |
| 3043 | |
| 3044 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3045 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3046 | return false; |
| 3047 | |
| 3048 | // It was legal, so commit it. |
| 3049 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3050 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3051 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 3052 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 3053 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3054 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3055 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 3056 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 3057 | TestAddrMode.ScaledReg = AddLHS; |
| 3058 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3059 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3060 | // If this addressing mode is legal, commit it and remember that we folded |
| 3061 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3062 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3063 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 3064 | AddrMode = TestAddrMode; |
| 3065 | return true; |
| 3066 | } |
| 3067 | } |
| 3068 | |
| 3069 | // Otherwise, not (x+c)*scale, just return what we have. |
| 3070 | return true; |
| 3071 | } |
| 3072 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3073 | /// This is a little filter, which returns true if an addressing computation |
| 3074 | /// involving I might be folded into a load/store accessing it. |
| 3075 | /// 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] | 3076 | /// the set of instructions that MatchOperationAddr can. |
| 3077 | static bool MightBeFoldableInst(Instruction *I) { |
| 3078 | switch (I->getOpcode()) { |
| 3079 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 3080 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3081 | // Don't touch identity bitcasts. |
| 3082 | if (I->getType() == I->getOperand(0)->getType()) |
| 3083 | return false; |
| 3084 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 3085 | case Instruction::PtrToInt: |
| 3086 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 3087 | return true; |
| 3088 | case Instruction::IntToPtr: |
| 3089 | // We know the input is intptr_t, so this is foldable. |
| 3090 | return true; |
| 3091 | case Instruction::Add: |
| 3092 | return true; |
| 3093 | case Instruction::Mul: |
| 3094 | case Instruction::Shl: |
| 3095 | // Can only handle X*C and X << C. |
| 3096 | return isa<ConstantInt>(I->getOperand(1)); |
| 3097 | case Instruction::GetElementPtr: |
| 3098 | return true; |
| 3099 | default: |
| 3100 | return false; |
| 3101 | } |
| 3102 | } |
| 3103 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3104 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 3105 | /// \note \p Val is assumed to be the product of some type promotion. |
| 3106 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 3107 | /// 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] | 3108 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 3109 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3110 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 3111 | if (!PromotedInst) |
| 3112 | return false; |
| 3113 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 3114 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 3115 | if (!ISDOpcode) |
| 3116 | return true; |
| 3117 | // Otherwise, check if the promoted instruction is legal or not. |
| 3118 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3119 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3120 | } |
| 3121 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3122 | /// \brief Hepler class to perform type promotion. |
| 3123 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3124 | /// \brief Utility function to check whether or not a sign or zero extension |
| 3125 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 3126 | /// either using the operands of \p Inst or promoting \p Inst. |
| 3127 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3128 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3129 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3130 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3131 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3132 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3133 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3134 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3135 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 3136 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3137 | |
| 3138 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 3139 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3140 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3141 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3142 | } |
| 3143 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3144 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3145 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3146 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3147 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3148 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3149 | /// Newly added extensions are inserted in \p Exts. |
| 3150 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3151 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3152 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3153 | static Value *promoteOperandForTruncAndAnyExt( |
| 3154 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3155 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3156 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3157 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
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 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3160 | /// operand is promotable and is not a supported trunc or sext. |
| 3161 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3162 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3163 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3164 | /// Newly added extensions are inserted in \p Exts. |
| 3165 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3166 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3167 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3168 | static Value *promoteOperandForOther(Instruction *Ext, |
| 3169 | TypePromotionTransaction &TPT, |
| 3170 | InstrToOrigTy &PromotedInsts, |
| 3171 | unsigned &CreatedInstsCost, |
| 3172 | SmallVectorImpl<Instruction *> *Exts, |
| 3173 | SmallVectorImpl<Instruction *> *Truncs, |
| 3174 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3175 | |
| 3176 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3177 | static Value *signExtendOperandForOther( |
| 3178 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3179 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3180 | SmallVectorImpl<Instruction *> *Exts, |
| 3181 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3182 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3183 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3184 | } |
| 3185 | |
| 3186 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3187 | static Value *zeroExtendOperandForOther( |
| 3188 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3189 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3190 | SmallVectorImpl<Instruction *> *Exts, |
| 3191 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3192 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3193 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3194 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3195 | |
| 3196 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3197 | /// Type for the utility function that promotes the operand of Ext. |
| 3198 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3199 | InstrToOrigTy &PromotedInsts, |
| 3200 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3201 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3202 | SmallVectorImpl<Instruction *> *Truncs, |
| 3203 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3204 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 3205 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3206 | /// \return NULL if no promotable action is possible with the current |
| 3207 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3208 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 3209 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3210 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 3211 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 3212 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3213 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3214 | const TargetLowering &TLI, |
| 3215 | const InstrToOrigTy &PromotedInsts); |
| 3216 | }; |
| 3217 | |
| 3218 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3219 | Type *ConsideredExtType, |
| 3220 | const InstrToOrigTy &PromotedInsts, |
| 3221 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3222 | // The promotion helper does not know how to deal with vector types yet. |
| 3223 | // To be able to fix that, we would need to fix the places where we |
| 3224 | // statically extend, e.g., constants and such. |
| 3225 | if (Inst->getType()->isVectorTy()) |
| 3226 | return false; |
| 3227 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3228 | // We can always get through zext. |
| 3229 | if (isa<ZExtInst>(Inst)) |
| 3230 | return true; |
| 3231 | |
| 3232 | // sext(sext) is ok too. |
| 3233 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3234 | return true; |
| 3235 | |
| 3236 | // We can get through binary operator, if it is legal. In other words, the |
| 3237 | // binary operator must have a nuw or nsw flag. |
| 3238 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 3239 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3240 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 3241 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3242 | return true; |
| 3243 | |
| 3244 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3245 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3246 | if (!isa<TruncInst>(Inst)) |
| 3247 | return false; |
| 3248 | |
| 3249 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3250 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3251 | // 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] | 3252 | if (!OpndVal->getType()->isIntegerTy() || |
| 3253 | OpndVal->getType()->getIntegerBitWidth() > |
| 3254 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3255 | return false; |
| 3256 | |
| 3257 | // If the operand of the truncate is not an instruction, we will not have |
| 3258 | // any information on the dropped bits. |
| 3259 | // (Actually we could for constant but it is not worth the extra logic). |
| 3260 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 3261 | if (!Opnd) |
| 3262 | return false; |
| 3263 | |
| 3264 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3265 | // I.e., check that trunc just drops extended bits of the same kind of |
| 3266 | // the extension. |
| 3267 | // #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] | 3268 | const Type *OpndType; |
| 3269 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 3270 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 3271 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3272 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 3273 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3274 | else |
| 3275 | return false; |
| 3276 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3277 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3278 | return Inst->getType()->getIntegerBitWidth() >= |
| 3279 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3280 | } |
| 3281 | |
| 3282 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3283 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3284 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3285 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 3286 | "Unexpected instruction type"); |
| 3287 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 3288 | Type *ExtTy = Ext->getType(); |
| 3289 | bool IsSExt = isa<SExtInst>(Ext); |
| 3290 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3291 | // get through. |
| 3292 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3293 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3294 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3295 | |
| 3296 | // Do not promote if the operand has been added by codegenprepare. |
| 3297 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 3298 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3299 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3300 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3301 | |
| 3302 | // SExt or Trunc instructions. |
| 3303 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3304 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 3305 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3306 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3307 | |
| 3308 | // Regular instruction. |
| 3309 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3310 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3311 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3312 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3313 | } |
| 3314 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3315 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3316 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3317 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3318 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3319 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3320 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 3321 | // get through it and this method should not be called. |
| 3322 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3323 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3324 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3325 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3326 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3327 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3328 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3329 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3330 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 3331 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 3332 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3333 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3334 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3335 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 3336 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3337 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 3338 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3339 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3340 | |
| 3341 | // Remove dead code. |
| 3342 | if (SExtOpnd->use_empty()) |
| 3343 | TPT.eraseInstruction(SExtOpnd); |
| 3344 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3345 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3346 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3347 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3348 | if (ExtInst) { |
| 3349 | if (Exts) |
| 3350 | Exts->push_back(ExtInst); |
| 3351 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 3352 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3353 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3354 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3355 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3356 | // At this point we have: ext ty opnd to ty. |
| 3357 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 3358 | Value *NextVal = ExtInst->getOperand(0); |
| 3359 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3360 | return NextVal; |
| 3361 | } |
| 3362 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3363 | Value *TypePromotionHelper::promoteOperandForOther( |
| 3364 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3365 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3366 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3367 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 3368 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3369 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3370 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3371 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3372 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3373 | if (!ExtOpnd->hasOneUse()) { |
| 3374 | // ExtOpnd will be promoted. |
| 3375 | // 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] | 3376 | // promoted version. |
| 3377 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3378 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3379 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 3380 | ITrunc->removeFromParent(); |
| 3381 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3382 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3383 | if (Truncs) |
| 3384 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3385 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3386 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3387 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3388 | // 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] | 3389 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3390 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3391 | } |
| 3392 | |
| 3393 | // Get through the Instruction: |
| 3394 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3395 | // 2. Replace the uses of Ext by Inst. |
| 3396 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3397 | |
| 3398 | // Remember the original type of the instruction before promotion. |
| 3399 | // 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] | 3400 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 3401 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3402 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3403 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3404 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3405 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3406 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3407 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3408 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3409 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 3410 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3411 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3412 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 3413 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 3414 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3415 | DEBUG(dbgs() << "No need to propagate\n"); |
| 3416 | continue; |
| 3417 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3418 | // Check if we can statically extend the operand. |
| 3419 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3420 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3421 | DEBUG(dbgs() << "Statically extend\n"); |
| 3422 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3423 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3424 | : Cst->getValue().zext(BitWidth); |
| 3425 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3426 | continue; |
| 3427 | } |
| 3428 | // UndefValue are typed, so we have to statically sign extend them. |
| 3429 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3430 | DEBUG(dbgs() << "Statically extend\n"); |
| 3431 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3432 | continue; |
| 3433 | } |
| 3434 | |
| 3435 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3436 | // Check if Ext was reused to extend an operand. |
| 3437 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3438 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3439 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3440 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3441 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3442 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3443 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3444 | continue; |
| 3445 | } |
| 3446 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3447 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3448 | if (Exts) |
| 3449 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3450 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3451 | |
| 3452 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3453 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3454 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3455 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3456 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3457 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3458 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3459 | if (ExtForOpnd == Ext) { |
| 3460 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 3461 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3462 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3463 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3464 | } |
| 3465 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3466 | /// 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] | 3467 | /// \p NewCost gives the cost of extension instructions created by the |
| 3468 | /// promotion. |
| 3469 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3470 | /// plus the number of instructions that have been |
| 3471 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3472 | /// \p PromotedOperand is the value that has been promoted. |
| 3473 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3474 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3475 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 3476 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 3477 | // The cost of the new extensions is greater than the cost of the |
| 3478 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3479 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3480 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3481 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3482 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3483 | return true; |
| 3484 | // The promotion is neutral but it may help folding the sign extension in |
| 3485 | // loads for instance. |
| 3486 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3487 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3488 | } |
| 3489 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3490 | /// 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] | 3491 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3492 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3493 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3494 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3495 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3496 | /// because it has been moved away. |
| 3497 | /// Thus AddrInst must not be added in the matched instructions. |
| 3498 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3499 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3500 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3501 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3502 | unsigned Depth, |
| 3503 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3504 | // Avoid exponential behavior on extremely deep expression trees. |
| 3505 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3506 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3507 | // By default, all matched instructions stay in place. |
| 3508 | if (MovedAway) |
| 3509 | *MovedAway = false; |
| 3510 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3511 | switch (Opcode) { |
| 3512 | case Instruction::PtrToInt: |
| 3513 | // 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] | 3514 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3515 | case Instruction::IntToPtr: { |
| 3516 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3517 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3518 | // 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] | 3519 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3520 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3521 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3522 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3523 | case Instruction::BitCast: |
| 3524 | // BitCast is always a noop, and we can handle it as long as it is |
| 3525 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3526 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3527 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3528 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3529 | // and we don't want to mess around with them. Assume it knows what it |
| 3530 | // is doing. |
| 3531 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3532 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3533 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3534 | case Instruction::AddrSpaceCast: { |
| 3535 | unsigned SrcAS |
| 3536 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3537 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3538 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3539 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3540 | return false; |
| 3541 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3542 | case Instruction::Add: { |
| 3543 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3544 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3545 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3546 | // Start a transaction at this point. |
| 3547 | // The LHS may match but not the RHS. |
| 3548 | // Therefore, we need a higher level restoration point to undo partially |
| 3549 | // matched operation. |
| 3550 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3551 | TPT.getRestorationPoint(); |
| 3552 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3553 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3554 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3555 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3556 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3557 | // Restore the old addr mode info. |
| 3558 | AddrMode = BackupAddrMode; |
| 3559 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3560 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3561 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3562 | // 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] | 3563 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3564 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3565 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3566 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3567 | // Otherwise we definitely can't merge the ADD in. |
| 3568 | AddrMode = BackupAddrMode; |
| 3569 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3570 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3571 | break; |
| 3572 | } |
| 3573 | //case Instruction::Or: |
| 3574 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3575 | //break; |
| 3576 | case Instruction::Mul: |
| 3577 | case Instruction::Shl: { |
| 3578 | // Can only handle X*C and X << C. |
| 3579 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3580 | if (!RHS) |
| 3581 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3582 | int64_t Scale = RHS->getSExtValue(); |
| 3583 | if (Opcode == Instruction::Shl) |
| 3584 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3585 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3586 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3587 | } |
| 3588 | case Instruction::GetElementPtr: { |
| 3589 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3590 | // one variable offset. |
| 3591 | int VariableOperand = -1; |
| 3592 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3593 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3594 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3595 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3596 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 3597 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3598 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3599 | unsigned Idx = |
| 3600 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3601 | ConstantOffset += SL->getElementOffset(Idx); |
| 3602 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3603 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3604 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3605 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3606 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3607 | // We only allow one variable index at the moment. |
| 3608 | if (VariableOperand != -1) |
| 3609 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3610 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3611 | // Remember the variable index. |
| 3612 | VariableOperand = i; |
| 3613 | VariableScale = TypeSize; |
| 3614 | } |
| 3615 | } |
| 3616 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3617 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3618 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3619 | // just add it to the disp field and check validity. |
| 3620 | if (VariableOperand == -1) { |
| 3621 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3622 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3623 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3624 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3625 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3626 | return true; |
| 3627 | } |
| 3628 | AddrMode.BaseOffs -= ConstantOffset; |
| 3629 | return false; |
| 3630 | } |
| 3631 | |
| 3632 | // Save the valid addressing mode in case we can't match. |
| 3633 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3634 | unsigned OldSize = AddrModeInsts.size(); |
| 3635 | |
| 3636 | // See if the scale and offset amount is valid for this target. |
| 3637 | AddrMode.BaseOffs += ConstantOffset; |
| 3638 | |
| 3639 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3640 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3641 | // If it couldn't be matched, just stuff the value in a register. |
| 3642 | if (AddrMode.HasBaseReg) { |
| 3643 | AddrMode = BackupAddrMode; |
| 3644 | AddrModeInsts.resize(OldSize); |
| 3645 | return false; |
| 3646 | } |
| 3647 | AddrMode.HasBaseReg = true; |
| 3648 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3649 | } |
| 3650 | |
| 3651 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3652 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3653 | Depth)) { |
| 3654 | // If it couldn't be matched, try stuffing the base into a register |
| 3655 | // instead of matching it, and retrying the match of the scale. |
| 3656 | AddrMode = BackupAddrMode; |
| 3657 | AddrModeInsts.resize(OldSize); |
| 3658 | if (AddrMode.HasBaseReg) |
| 3659 | return false; |
| 3660 | AddrMode.HasBaseReg = true; |
| 3661 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3662 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3663 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3664 | VariableScale, Depth)) { |
| 3665 | // If even that didn't work, bail. |
| 3666 | AddrMode = BackupAddrMode; |
| 3667 | AddrModeInsts.resize(OldSize); |
| 3668 | return false; |
| 3669 | } |
| 3670 | } |
| 3671 | |
| 3672 | return true; |
| 3673 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3674 | case Instruction::SExt: |
| 3675 | case Instruction::ZExt: { |
| 3676 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3677 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3678 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3679 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3680 | // 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] | 3681 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3682 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3683 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3684 | if (!TPH) |
| 3685 | return false; |
| 3686 | |
| 3687 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3688 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3689 | unsigned CreatedInstsCost = 0; |
| 3690 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3691 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3692 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3693 | // SExt has been moved away. |
| 3694 | // Thus either it will be rematched later in the recursive calls or it is |
| 3695 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3696 | // E.g., |
| 3697 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3698 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3699 | // addr = gep base, idx |
| 3700 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3701 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3702 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3703 | // addr = gep base, op <- match |
| 3704 | if (MovedAway) |
| 3705 | *MovedAway = true; |
| 3706 | |
| 3707 | assert(PromotedOperand && |
| 3708 | "TypePromotionHelper should have filtered out those cases"); |
| 3709 | |
| 3710 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3711 | unsigned OldSize = AddrModeInsts.size(); |
| 3712 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3713 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3714 | // 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] | 3715 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3716 | // 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] | 3717 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3718 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3719 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3720 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3721 | AddrMode = BackupAddrMode; |
| 3722 | AddrModeInsts.resize(OldSize); |
| 3723 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3724 | TPT.rollback(LastKnownGood); |
| 3725 | return false; |
| 3726 | } |
| 3727 | return true; |
| 3728 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3729 | } |
| 3730 | return false; |
| 3731 | } |
| 3732 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3733 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3734 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3735 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3736 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3737 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3738 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3739 | // Start a transaction at this point that we will rollback if the matching |
| 3740 | // fails. |
| 3741 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3742 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3743 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 3744 | // Fold in immediates if legal for the target. |
| 3745 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3746 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3747 | return true; |
| 3748 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 3749 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 3750 | // 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] | 3751 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3752 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3753 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3754 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3755 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3756 | } |
| 3757 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 3758 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3759 | unsigned OldSize = AddrModeInsts.size(); |
| 3760 | |
| 3761 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3762 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3763 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3764 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3765 | // to check here. |
| 3766 | if (MovedAway) |
| 3767 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3768 | // Okay, it's possible to fold this. Check to see if it is actually |
| 3769 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 3770 | // register pressure too much. |
| 3771 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3772 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3773 | AddrModeInsts.push_back(I); |
| 3774 | return true; |
| 3775 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3776 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3777 | // It isn't profitable to do this, roll back. |
| 3778 | //cerr << "NOT FOLDING: " << *I; |
| 3779 | AddrMode = BackupAddrMode; |
| 3780 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3781 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3782 | } |
| 3783 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3784 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3785 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3786 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3787 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 3788 | // Null pointer gets folded without affecting the addressing mode. |
| 3789 | return true; |
| 3790 | } |
| 3791 | |
| 3792 | // Worse case, the target should support [reg] addressing modes. :) |
| 3793 | if (!AddrMode.HasBaseReg) { |
| 3794 | AddrMode.HasBaseReg = true; |
| 3795 | AddrMode.BaseReg = Addr; |
| 3796 | // 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] | 3797 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3798 | return true; |
| 3799 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3800 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3801 | } |
| 3802 | |
| 3803 | // If the base register is already taken, see if we can do [r+r]. |
| 3804 | if (AddrMode.Scale == 0) { |
| 3805 | AddrMode.Scale = 1; |
| 3806 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3807 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3808 | return true; |
| 3809 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3810 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3811 | } |
| 3812 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3813 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3814 | return false; |
| 3815 | } |
| 3816 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3817 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 3818 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3819 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3820 | const TargetLowering &TLI, |
| 3821 | const TargetRegisterInfo &TRI) { |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3822 | const Function *F = CI->getParent()->getParent(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3823 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3824 | TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3825 | ImmutableCallSite(CI)); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3826 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3827 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3828 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3829 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3830 | // Compute the constraint code and ConstraintType to use. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3831 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3832 | |
| 3833 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 3834 | // operand, we can't fold it! |
| 3835 | if (OpInfo.CallOperandVal == OpVal && |
| 3836 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 3837 | !OpInfo.isIndirect)) |
| 3838 | return false; |
| 3839 | } |
| 3840 | |
| 3841 | return true; |
| 3842 | } |
| 3843 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3844 | /// Recursively walk all the uses of I until we find a memory use. |
| 3845 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3846 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3847 | static bool FindAllMemoryUses( |
| 3848 | Instruction *I, |
| 3849 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3850 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, |
| 3851 | const TargetLowering &TLI, const TargetRegisterInfo &TRI) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3852 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3853 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3854 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3855 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3856 | // If this is an obviously unfoldable instruction, bail out. |
| 3857 | if (!MightBeFoldableInst(I)) |
| 3858 | return true; |
| 3859 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3860 | const bool OptSize = I->getFunction()->optForSize(); |
| 3861 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3862 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3863 | for (Use &U : I->uses()) { |
| 3864 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3865 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3866 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3867 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3868 | continue; |
| 3869 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3870 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3871 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3872 | unsigned opNo = U.getOperandNo(); |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 3873 | if (opNo != StoreInst::getPointerOperandIndex()) |
| 3874 | return true; // Storing addr, not into addr. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3875 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3876 | continue; |
| 3877 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3878 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 3879 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { |
| 3880 | unsigned opNo = U.getOperandNo(); |
| 3881 | if (opNo != AtomicRMWInst::getPointerOperandIndex()) |
| 3882 | return true; // Storing addr, not into addr. |
| 3883 | MemoryUses.push_back(std::make_pair(RMW, opNo)); |
| 3884 | continue; |
| 3885 | } |
| 3886 | |
| 3887 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { |
| 3888 | unsigned opNo = U.getOperandNo(); |
| 3889 | if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) |
| 3890 | return true; // Storing addr, not into addr. |
| 3891 | MemoryUses.push_back(std::make_pair(CmpX, opNo)); |
| 3892 | continue; |
| 3893 | } |
| 3894 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3895 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3896 | // If this is a cold call, we can sink the addressing calculation into |
| 3897 | // the cold path. See optimizeCallInst |
| 3898 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 3899 | continue; |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 3900 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3901 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 3902 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3903 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3904 | // If this is a memory operand, we're cool, otherwise bail out. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3905 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3906 | return true; |
| 3907 | continue; |
| 3908 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3909 | |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3910 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3911 | return true; |
| 3912 | } |
| 3913 | |
| 3914 | return false; |
| 3915 | } |
| 3916 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3917 | /// Return true if Val is already known to be live at the use site that we're |
| 3918 | /// folding it into. If so, there is no cost to include it in the addressing |
| 3919 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 3920 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3921 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3922 | Value *KnownLive2) { |
| 3923 | // 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] | 3924 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3925 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3926 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3927 | // All values other than instructions and arguments (e.g. constants) are live. |
| 3928 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3929 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3930 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 3931 | // true because it is just a reference to the stack/frame pointer, which is |
| 3932 | // live for the whole function. |
| 3933 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 3934 | if (AI->isStaticAlloca()) |
| 3935 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3936 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3937 | // Check to see if this value is already used in the memory instruction's |
| 3938 | // block. If so, it's already live into the block at the very least, so we |
| 3939 | // can reasonably fold it. |
| 3940 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 3941 | } |
| 3942 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3943 | /// It is possible for the addressing mode of the machine to fold the specified |
| 3944 | /// instruction into a load or store that ultimately uses it. |
| 3945 | /// However, the specified instruction has multiple uses. |
| 3946 | /// Given this, it may actually increase register pressure to fold it |
| 3947 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3948 | /// |
| 3949 | /// X = ... |
| 3950 | /// Y = X+1 |
| 3951 | /// use(Y) -> nonload/store |
| 3952 | /// Z = Y+1 |
| 3953 | /// load Z |
| 3954 | /// |
| 3955 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 3956 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 3957 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 3958 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 3959 | /// number of computations either. |
| 3960 | /// |
| 3961 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 3962 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 3963 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 3964 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3965 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3966 | ExtAddrMode &AMAfter) { |
| 3967 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3968 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3969 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 3970 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 3971 | // the set of registers referenced by AMAfter and subtract out those |
| 3972 | // referenced by AMBefore: this is the set of values which folding in this |
| 3973 | // address extends the lifetime of. |
| 3974 | // |
| 3975 | // Note that there are only two potential values being referenced here, |
| 3976 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 3977 | // folded immediates). |
| 3978 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3979 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3980 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 3981 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3982 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3983 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3984 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3985 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3986 | |
| 3987 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 3988 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3989 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3990 | return true; |
| 3991 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3992 | // If all uses of this instruction can have the address mode sunk into them, |
| 3993 | // we can remove the addressing mode and effectively trade one live register |
| 3994 | // for another (at worst.) In this context, folding an addressing mode into |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 3995 | // the use is just a particularly nice way of sinking it. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3996 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 3997 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3998 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3999 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4000 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4001 | // Now that we know that all uses of this instruction are part of a chain of |
| 4002 | // computation involving only operations that could theoretically be folded |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4003 | // into a memory use, loop over each of these memory operation uses and see |
| 4004 | // if they could *actually* fold the instruction. The assumption is that |
| 4005 | // addressing modes are cheap and that duplicating the computation involved |
| 4006 | // many times is worthwhile, even on a fastpath. For sinking candidates |
| 4007 | // (i.e. cold call sites), this serves as a way to prevent excessive code |
| 4008 | // growth since most architectures have some reasonable small and fast way to |
| 4009 | // compute an effective address. (i.e LEA on x86) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4010 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 4011 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 4012 | Instruction *User = MemoryUses[i].first; |
| 4013 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4014 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4015 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 4016 | // know what it accesses. |
| 4017 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4018 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 4019 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4020 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4021 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 4022 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4023 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4024 | // Do a match against the root of this address, ignoring profitability. This |
| 4025 | // will tell us if the addressing mode for the memory operation will |
| 4026 | // *actually* cover the shared instruction. |
| 4027 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4028 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4029 | TPT.getRestorationPoint(); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4030 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, |
| 4031 | AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4032 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4033 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4034 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4035 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4036 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 4037 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4038 | // The match was to check the profitability, the changes made are not |
| 4039 | // part of the original matcher. Therefore, they should be dropped |
| 4040 | // otherwise the original matcher will not present the right state. |
| 4041 | TPT.rollback(LastKnownGood); |
| 4042 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4043 | // 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] | 4044 | if (!is_contained(MatchedAddrModeInsts, I)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4045 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4046 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4047 | MatchedAddrModeInsts.clear(); |
| 4048 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4049 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4050 | return true; |
| 4051 | } |
| 4052 | |
| 4053 | } // end anonymous namespace |
| 4054 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4055 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4056 | /// different basic block than BB. |
| 4057 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 4058 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4059 | return I->getParent() != BB; |
| 4060 | return false; |
| 4061 | } |
| 4062 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4063 | /// Sink addressing mode computation immediate before MemoryInst if doing so |
| 4064 | /// can be done without increasing register pressure. The need for the |
| 4065 | /// register pressure constraint means this can end up being an all or nothing |
| 4066 | /// decision for all uses of the same addressing computation. |
| 4067 | /// |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4068 | /// Load and Store Instructions often have addressing modes that can do |
| 4069 | /// significant amounts of computation. As such, instruction selection will try |
| 4070 | /// to get the load or store to do as much computation as possible for the |
| 4071 | /// program. The problem is that isel can only see within a single block. As |
| 4072 | /// 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] | 4073 | /// |
| 4074 | /// 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] | 4075 | /// operands. It's also used to sink addressing computations feeding into cold |
| 4076 | /// call sites into their (cold) basic block. |
| 4077 | /// |
| 4078 | /// The motivation for handling sinking into cold blocks is that doing so can |
| 4079 | /// both enable other address mode sinking (by satisfying the register pressure |
| 4080 | /// constraint above), and reduce register pressure globally (by removing the |
| 4081 | /// addressing mode computation from the fast path entirely.). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4082 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4083 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4084 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4085 | |
| 4086 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4087 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 4088 | SmallVector<Value*, 8> worklist; |
| 4089 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4090 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4091 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4092 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 4093 | // the addressing mode obtained from the non-PHI roots of the graph |
| 4094 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4095 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4096 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4097 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4098 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 4099 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4100 | TypePromotionTransaction TPT; |
| 4101 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4102 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4103 | while (!worklist.empty()) { |
| 4104 | Value *V = worklist.back(); |
| 4105 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4106 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4107 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4108 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4109 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4110 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4111 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4112 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4113 | // For a PHI node, push all of its incoming values. |
| 4114 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 4115 | for (Value *IncValue : P->incoming_values()) |
| 4116 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4117 | continue; |
| 4118 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4119 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4120 | // For non-PHIs, determine the addressing mode being computed. Note that |
| 4121 | // the result may differ depending on what other uses our candidate |
| 4122 | // addressing instructions might have. |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4123 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4124 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4125 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4126 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4127 | |
| 4128 | // This check is broken into two cases with very similar code to avoid using |
| 4129 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 4130 | // calling getNumUses() unconditionally caused a significant compile-time |
| 4131 | // regression. |
| 4132 | if (!Consensus) { |
| 4133 | Consensus = V; |
| 4134 | AddrMode = NewAddrMode; |
| 4135 | AddrModeInsts = NewAddrModeInsts; |
| 4136 | continue; |
| 4137 | } else if (NewAddrMode == AddrMode) { |
| 4138 | if (!IsNumUsesConsensusValid) { |
| 4139 | NumUsesConsensus = Consensus->getNumUses(); |
| 4140 | IsNumUsesConsensusValid = true; |
| 4141 | } |
| 4142 | |
| 4143 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 4144 | // for all other roots of the PHI traversal. Also, when choosing one |
| 4145 | // such root as representative, select the one with the most uses in order |
| 4146 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 4147 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4148 | unsigned NumUses = V->getNumUses(); |
| 4149 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4150 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4151 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4152 | AddrModeInsts = NewAddrModeInsts; |
| 4153 | } |
| 4154 | continue; |
| 4155 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4156 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4157 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4158 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4159 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4160 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4161 | // If the addressing mode couldn't be determined, or if multiple different |
| 4162 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4163 | if (!Consensus) { |
| 4164 | TPT.rollback(LastKnownGood); |
| 4165 | return false; |
| 4166 | } |
| 4167 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4168 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4169 | // 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] | 4170 | if (none_of(AddrModeInsts, [&](Value *V) { |
| 4171 | return IsNonLocalValue(V, MemoryInst->getParent()); |
| 4172 | })) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4173 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4174 | return false; |
| 4175 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4176 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4177 | // Insert this computation right after this user. Since our caller is |
| 4178 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 4179 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4180 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4181 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4182 | // Now that we determined the addressing expression we want to use and know |
| 4183 | // that we have to sink it into this block. Check to see if we have already |
| 4184 | // done this for some other load/store instr in this block. If so, reuse the |
| 4185 | // computation. |
| 4186 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 4187 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4188 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4189 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4190 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4191 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 4192 | } else if (AddrSinkUsingGEPs || |
| 4193 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4194 | SubtargetInfo->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4195 | // By default, we use the GEP-based method when AA is used later. This |
| 4196 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 4197 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4198 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4199 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4200 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4201 | |
| 4202 | // First, find the pointer. |
| 4203 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 4204 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4205 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4206 | } |
| 4207 | |
| 4208 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 4209 | // We can't add more than one pointer together, nor can we scale a |
| 4210 | // pointer (both of which seem meaningless). |
| 4211 | if (ResultPtr || AddrMode.Scale != 1) |
| 4212 | return false; |
| 4213 | |
| 4214 | ResultPtr = AddrMode.ScaledReg; |
| 4215 | AddrMode.Scale = 0; |
| 4216 | } |
| 4217 | |
| 4218 | if (AddrMode.BaseGV) { |
| 4219 | if (ResultPtr) |
| 4220 | return false; |
| 4221 | |
| 4222 | ResultPtr = AddrMode.BaseGV; |
| 4223 | } |
| 4224 | |
| 4225 | // If the real base value actually came from an inttoptr, then the matcher |
| 4226 | // will look through it and provide only the integer value. In that case, |
| 4227 | // use it here. |
| 4228 | if (!ResultPtr && AddrMode.BaseReg) { |
| 4229 | ResultPtr = |
| 4230 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4231 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4232 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 4233 | ResultPtr = |
| 4234 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 4235 | AddrMode.Scale = 0; |
| 4236 | } |
| 4237 | |
| 4238 | if (!ResultPtr && |
| 4239 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 4240 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 4241 | } else if (!ResultPtr) { |
| 4242 | return false; |
| 4243 | } else { |
| 4244 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4245 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 4246 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4247 | |
| 4248 | // Start with the base register. Do this first so that subsequent address |
| 4249 | // matching finds it last, which will prevent it from trying to match it |
| 4250 | // as the scaled value in case it happens to be a mul. That would be |
| 4251 | // problematic if we've sunk a different mul for the scale, because then |
| 4252 | // we'd end up sinking both muls. |
| 4253 | if (AddrMode.BaseReg) { |
| 4254 | Value *V = AddrMode.BaseReg; |
| 4255 | if (V->getType() != IntPtrTy) |
| 4256 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 4257 | |
| 4258 | ResultIndex = V; |
| 4259 | } |
| 4260 | |
| 4261 | // Add the scale value. |
| 4262 | if (AddrMode.Scale) { |
| 4263 | Value *V = AddrMode.ScaledReg; |
| 4264 | if (V->getType() == IntPtrTy) { |
| 4265 | // done. |
| 4266 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4267 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 4268 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 4269 | } else { |
| 4270 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4271 | // required to create it did not overflow before we extend it. Since |
| 4272 | // the original IR value was tossed in favor of a constant back when |
| 4273 | // the AddrMode was created we need to bail out gracefully if widths |
| 4274 | // do not match instead of extending it. |
| 4275 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 4276 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 4277 | I->eraseFromParent(); |
| 4278 | return false; |
| 4279 | } |
| 4280 | |
| 4281 | if (AddrMode.Scale != 1) |
| 4282 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4283 | "sunkaddr"); |
| 4284 | if (ResultIndex) |
| 4285 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 4286 | else |
| 4287 | ResultIndex = V; |
| 4288 | } |
| 4289 | |
| 4290 | // Add in the Base Offset if present. |
| 4291 | if (AddrMode.BaseOffs) { |
| 4292 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 4293 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 4294 | // We need to add this separately from the scale above to help with |
| 4295 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4296 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4297 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4298 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4299 | } |
| 4300 | |
| 4301 | ResultIndex = V; |
| 4302 | } |
| 4303 | |
| 4304 | if (!ResultIndex) { |
| 4305 | SunkAddr = ResultPtr; |
| 4306 | } else { |
| 4307 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4308 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4309 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4310 | } |
| 4311 | |
| 4312 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4313 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4314 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4315 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4316 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4317 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4318 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4319 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4320 | |
| 4321 | // Start with the base register. Do this first so that subsequent address |
| 4322 | // matching finds it last, which will prevent it from trying to match it |
| 4323 | // as the scaled value in case it happens to be a mul. That would be |
| 4324 | // problematic if we've sunk a different mul for the scale, because then |
| 4325 | // we'd end up sinking both muls. |
| 4326 | if (AddrMode.BaseReg) { |
| 4327 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4328 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4329 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4330 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4331 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4332 | Result = V; |
| 4333 | } |
| 4334 | |
| 4335 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4336 | if (AddrMode.Scale) { |
| 4337 | Value *V = AddrMode.ScaledReg; |
| 4338 | if (V->getType() == IntPtrTy) { |
| 4339 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4340 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4341 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4342 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4343 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4344 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4345 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4346 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4347 | // required to create it did not overflow before we extend it. Since |
| 4348 | // the original IR value was tossed in favor of a constant back when |
| 4349 | // the AddrMode was created we need to bail out gracefully if widths |
| 4350 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 4351 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 4352 | if (I && (Result != AddrMode.BaseReg)) |
| 4353 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4354 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4355 | } |
| 4356 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4357 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4358 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4359 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4360 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4361 | else |
| 4362 | Result = V; |
| 4363 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4364 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4365 | // Add in the BaseGV if present. |
| 4366 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4367 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4368 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4369 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4370 | else |
| 4371 | Result = V; |
| 4372 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4373 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4374 | // Add in the Base Offset if present. |
| 4375 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4376 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4377 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4378 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4379 | else |
| 4380 | Result = V; |
| 4381 | } |
| 4382 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4383 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 4384 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4385 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4386 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4387 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4388 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4389 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4390 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4391 | // If we have no uses, recursively delete the value and all dead instructions |
| 4392 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4393 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4394 | // This can cause recursive deletion, which can invalidate our iterator. |
| 4395 | // 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] | 4396 | Value *CurValue = &*CurInstIterator; |
| 4397 | WeakVH IterHandle(CurValue); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4398 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4399 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 4400 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4401 | |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4402 | if (IterHandle != CurValue) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4403 | // If the iterator instruction was recursively deleted, start over at the |
| 4404 | // start of the block. |
| 4405 | CurInstIterator = BB->begin(); |
| 4406 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4407 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 4408 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4409 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4410 | return true; |
| 4411 | } |
| 4412 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4413 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 4414 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4415 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4416 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4417 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4418 | const TargetRegisterInfo *TRI = |
| 4419 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4420 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 4421 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4422 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 4423 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4424 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4425 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4426 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 4427 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4428 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 4429 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 4430 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4431 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4432 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4433 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 4434 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4435 | } |
| 4436 | |
| 4437 | return MadeChange; |
| 4438 | } |
| 4439 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4440 | /// \brief Check if all the uses of \p Val are equivalent (or free) zero or |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4441 | /// sign extensions. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4442 | static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { |
| 4443 | assert(!Val->use_empty() && "Input must have at least one use"); |
| 4444 | const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4445 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 4446 | Type *ExtTy = FirstUser->getType(); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4447 | for (const User *U : Val->users()) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4448 | const Instruction *UI = cast<Instruction>(U); |
| 4449 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4450 | return false; |
| 4451 | Type *CurTy = UI->getType(); |
| 4452 | // Same input and output types: Same instruction after CSE. |
| 4453 | if (CurTy == ExtTy) |
| 4454 | continue; |
| 4455 | |
| 4456 | // If IsSExt is true, we are in this situation: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4457 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4458 | // b = sext ty1 a to ty2 |
| 4459 | // c = sext ty1 a to ty3 |
| 4460 | // Assuming ty2 is shorter than ty3, this could be turned into: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4461 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4462 | // b = sext ty1 a to ty2 |
| 4463 | // c = sext ty2 b to ty3 |
| 4464 | // However, the last sext is not free. |
| 4465 | if (IsSExt) |
| 4466 | return false; |
| 4467 | |
| 4468 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4469 | // In that case, we would not account for a different use. |
| 4470 | Type *NarrowTy; |
| 4471 | Type *LargeTy; |
| 4472 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4473 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4474 | NarrowTy = CurTy; |
| 4475 | LargeTy = ExtTy; |
| 4476 | } else { |
| 4477 | NarrowTy = ExtTy; |
| 4478 | LargeTy = CurTy; |
| 4479 | } |
| 4480 | |
| 4481 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4482 | return false; |
| 4483 | } |
| 4484 | // All uses are the same or can be derived from one another for free. |
| 4485 | return true; |
| 4486 | } |
| 4487 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4488 | /// \brief Try to speculatively promote extensions in \p Exts and continue |
| 4489 | /// promoting through newly promoted operands recursively as far as doing so is |
| 4490 | /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. |
| 4491 | /// When some promotion happened, \p TPT contains the proper state to revert |
| 4492 | /// them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4493 | /// |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4494 | /// \return true if some promotion happened, false otherwise. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4495 | /// |
| 4496 | /// Example: |
| 4497 | /// \code |
| 4498 | /// %ld = load i32* %addr |
| 4499 | /// %add = add nuw i32 %ld, 4 |
| 4500 | /// %zext = zext i32 %add to i64 |
| 4501 | /// \endcode |
| 4502 | /// => |
| 4503 | /// \code |
| 4504 | /// %ld = load i32* %addr |
| 4505 | /// %zext = zext i32 %ld to i64 |
| 4506 | /// %add = add nuw i64 %zext, 4 |
Haicheng Wu | 8ce2d14 | 2017-01-18 21:12:10 +0000 | [diff] [blame] | 4507 | /// \endcode |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4508 | /// Thanks to the promotion, we can match zext(load i32*) to i64. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4509 | bool CodeGenPrepare::tryToPromoteExts( |
| 4510 | TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, |
| 4511 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 4512 | unsigned CreatedInstsCost) { |
| 4513 | bool Promoted = false; |
| 4514 | |
| 4515 | // Iterate over all the extensions to try to promote them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4516 | for (auto I : Exts) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4517 | // Early check if we directly have ext(load). |
| 4518 | if (isa<LoadInst>(I->getOperand(0))) { |
| 4519 | ProfitablyMovedExts.push_back(I); |
| 4520 | continue; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4521 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4522 | |
| 4523 | // Check whether or not we want to do any promotion. The reason we have |
| 4524 | // this check inside the for loop is to catch the case where an extension |
| 4525 | // is directly fed by a load because in such case the extension can be moved |
| 4526 | // up without any promotion on its operands. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4527 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4528 | return false; |
| 4529 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4530 | // Get the action to perform the promotion. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4531 | TypePromotionHelper::Action TPH = |
| 4532 | TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4533 | // Check if we can promote. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4534 | if (!TPH) { |
| 4535 | // Save the current extension as we cannot move up through its operand. |
| 4536 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4537 | continue; |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4538 | } |
| 4539 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4540 | // Save the current state. |
| 4541 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4542 | TPT.getRestorationPoint(); |
| 4543 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4544 | unsigned NewCreatedInstsCost = 0; |
| 4545 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4546 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4547 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4548 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4549 | assert(PromotedVal && |
| 4550 | "TypePromotionHelper should have filtered out those cases"); |
| 4551 | |
| 4552 | // We would be able to merge only one extension in a load. |
| 4553 | // Therefore, if we have more than 1 new extension we heuristically |
| 4554 | // cut this search path, because it means we degrade the code quality. |
| 4555 | // With exactly 2, the transformation is neutral, because we will merge |
| 4556 | // one extension but leave one. However, we optimistically keep going, |
| 4557 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4558 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4559 | // FIXME: It would be possible to propagate a negative value instead of |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4560 | // conservatively ceiling it to 0. |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4561 | TotalCreatedInstsCost = |
| 4562 | std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4563 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4564 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4565 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4566 | // This promotion is not profitable, rollback to the previous state, and |
| 4567 | // save the current extension in ProfitablyMovedExts as the latest |
| 4568 | // speculative promotion turned out to be unprofitable. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4569 | TPT.rollback(LastKnownGood); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4570 | ProfitablyMovedExts.push_back(I); |
| 4571 | continue; |
| 4572 | } |
| 4573 | // Continue promoting NewExts as far as doing so is profitable. |
| 4574 | SmallVector<Instruction *, 2> NewlyMovedExts; |
| 4575 | (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); |
| 4576 | bool NewPromoted = false; |
| 4577 | for (auto ExtInst : NewlyMovedExts) { |
| 4578 | Instruction *MovedExt = cast<Instruction>(ExtInst); |
| 4579 | Value *ExtOperand = MovedExt->getOperand(0); |
| 4580 | // If we have reached to a load, we need this extra profitability check |
| 4581 | // as it could potentially be merged into an ext(load). |
| 4582 | if (isa<LoadInst>(ExtOperand) && |
| 4583 | !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
| 4584 | (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) |
| 4585 | continue; |
| 4586 | |
| 4587 | ProfitablyMovedExts.push_back(MovedExt); |
| 4588 | NewPromoted = true; |
| 4589 | } |
| 4590 | |
| 4591 | // If none of speculative promotions for NewExts is profitable, rollback |
| 4592 | // and save the current extension (I) as the last profitable extension. |
| 4593 | if (!NewPromoted) { |
| 4594 | TPT.rollback(LastKnownGood); |
| 4595 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4596 | continue; |
| 4597 | } |
| 4598 | // The promotion is profitable. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4599 | Promoted = true; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4600 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4601 | return Promoted; |
| 4602 | } |
| 4603 | |
| 4604 | /// Return true, if an ext(load) can be formed from an extension in |
| 4605 | /// \p MovedExts. |
| 4606 | bool CodeGenPrepare::canFormExtLd( |
| 4607 | const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, |
| 4608 | Instruction *&Inst, bool HasPromoted) { |
| 4609 | for (auto *MovedExtInst : MovedExts) { |
| 4610 | if (isa<LoadInst>(MovedExtInst->getOperand(0))) { |
| 4611 | LI = cast<LoadInst>(MovedExtInst->getOperand(0)); |
| 4612 | Inst = MovedExtInst; |
| 4613 | break; |
| 4614 | } |
| 4615 | } |
| 4616 | if (!LI) |
| 4617 | return false; |
| 4618 | |
| 4619 | // If they're already in the same block, there's nothing to do. |
| 4620 | // Make the cheap checks first if we did not promote. |
| 4621 | // If we promoted, we need to check if it is indeed profitable. |
| 4622 | if (!HasPromoted && LI->getParent() == Inst->getParent()) |
| 4623 | return false; |
| 4624 | |
| 4625 | EVT VT = TLI->getValueType(*DL, Inst->getType()); |
| 4626 | EVT LoadVT = TLI->getValueType(*DL, LI->getType()); |
| 4627 | |
| 4628 | // If the load has other users and the truncate is not free, this probably |
| 4629 | // isn't worthwhile. |
| 4630 | if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
| 4631 | !TLI->isTruncateFree(Inst->getType(), LI->getType())) |
| 4632 | return false; |
| 4633 | |
| 4634 | // Check whether the target supports casts folded into loads. |
| 4635 | unsigned LType; |
| 4636 | if (isa<ZExtInst>(Inst)) |
| 4637 | LType = ISD::ZEXTLOAD; |
| 4638 | else { |
| 4639 | assert(isa<SExtInst>(Inst) && "Unexpected ext type!"); |
| 4640 | LType = ISD::SEXTLOAD; |
| 4641 | } |
| 4642 | |
| 4643 | return TLI->isLoadExtLegal(LType, VT, LoadVT); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4644 | } |
| 4645 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4646 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4647 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4648 | /// extend into the load. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4649 | /// \p I[in/out] the extension may be modified during the process if some |
| 4650 | /// promotions apply. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4651 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4652 | bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) { |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 4653 | // ExtLoad formation infrastructure requires TLI to be effective. |
| 4654 | if (!TLI) |
| 4655 | return false; |
| 4656 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4657 | // Try to promote a chain of computation if it allows to form |
| 4658 | // an extended load. |
| 4659 | TypePromotionTransaction TPT; |
| 4660 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4661 | TPT.getRestorationPoint(); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4662 | SmallVector<Instruction *, 1> Exts; |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4663 | SmallVector<Instruction *, 2> LastMovedExts; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4664 | Exts.push_back(I); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4665 | |
| 4666 | bool HasPromoted = tryToPromoteExts(TPT, Exts, LastMovedExts); |
| 4667 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4668 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4669 | LoadInst *LI = nullptr; |
| 4670 | Instruction *OldExt = I; |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4671 | if (!canFormExtLd(LastMovedExts, LI, I, HasPromoted)) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4672 | I = OldExt; |
| 4673 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4674 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4675 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4676 | |
| 4677 | // Move the extend into the same block as the load, so that SelectionDAG |
| 4678 | // can fold it. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4679 | TPT.commit(); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4680 | I->removeFromParent(); |
| 4681 | I->insertAfter(LI); |
Andrea Di Biagio | fa90c69 | 2016-10-17 11:32:26 +0000 | [diff] [blame] | 4682 | // CGP does not check if the zext would be speculatively executed when moved |
| 4683 | // to the same basic block as the load. Preserving its original location would |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4684 | // pessimize the debugging experience, as well as negatively impact the |
Andrea Di Biagio | fa90c69 | 2016-10-17 11:32:26 +0000 | [diff] [blame] | 4685 | // quality of sample pgo. We don't want to use "line 0" as that has a |
| 4686 | // size cost in the line-table section and logically the zext can be seen as |
| 4687 | // part of the load. Therefore we conservatively reuse the same debug location |
| 4688 | // for the load and the zext. |
| 4689 | I->setDebugLoc(LI->getDebugLoc()); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4690 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4691 | return true; |
| 4692 | } |
| 4693 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4694 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4695 | BasicBlock *DefBB = I->getParent(); |
| 4696 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 4697 | // 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] | 4698 | // other uses of the source with result of extension. |
| 4699 | Value *Src = I->getOperand(0); |
| 4700 | if (Src->hasOneUse()) |
| 4701 | return false; |
| 4702 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 4703 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 4704 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4705 | return false; |
| 4706 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4707 | // 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] | 4708 | // this block. |
| 4709 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4710 | return false; |
| 4711 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4712 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4713 | for (User *U : I->users()) { |
| 4714 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4715 | |
| 4716 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4717 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4718 | if (UserBB == DefBB) continue; |
| 4719 | DefIsLiveOut = true; |
| 4720 | break; |
| 4721 | } |
| 4722 | if (!DefIsLiveOut) |
| 4723 | return false; |
| 4724 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 4725 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4726 | for (User *U : Src->users()) { |
| 4727 | Instruction *UI = cast<Instruction>(U); |
| 4728 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4729 | if (UserBB == DefBB) continue; |
| 4730 | // Be conservative. We don't want this xform to end up introducing |
| 4731 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4732 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4733 | return false; |
| 4734 | } |
| 4735 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4736 | // InsertedTruncs - Only insert one trunc in each block once. |
| 4737 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 4738 | |
| 4739 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4740 | for (Use &U : Src->uses()) { |
| 4741 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4742 | |
| 4743 | // Figure out which BB this ext is used in. |
| 4744 | BasicBlock *UserBB = User->getParent(); |
| 4745 | if (UserBB == DefBB) continue; |
| 4746 | |
| 4747 | // Both src and def are live in this block. Rewrite the use. |
| 4748 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 4749 | |
| 4750 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 4751 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4752 | assert(InsertPt != UserBB->end()); |
| 4753 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4754 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4755 | } |
| 4756 | |
| 4757 | // 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] | 4758 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4759 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4760 | MadeChange = true; |
| 4761 | } |
| 4762 | |
| 4763 | return MadeChange; |
| 4764 | } |
| 4765 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 4766 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 4767 | // just after the load if the target can fold this into one extload instruction, |
| 4768 | // with the hope of eliminating some of the other later "and" instructions using |
| 4769 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 4770 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 4771 | // path from the load goes through a phi) are left for isel to potentially |
| 4772 | // remove. |
| 4773 | // |
| 4774 | // For example: |
| 4775 | // |
| 4776 | // b0: |
| 4777 | // x = load i32 |
| 4778 | // ... |
| 4779 | // b1: |
| 4780 | // y = and x, 0xff |
| 4781 | // z = use y |
| 4782 | // |
| 4783 | // becomes: |
| 4784 | // |
| 4785 | // b0: |
| 4786 | // x = load i32 |
| 4787 | // x' = and x, 0xff |
| 4788 | // ... |
| 4789 | // b1: |
| 4790 | // z = use x' |
| 4791 | // |
| 4792 | // whereas: |
| 4793 | // |
| 4794 | // b0: |
| 4795 | // x1 = load i32 |
| 4796 | // ... |
| 4797 | // b1: |
| 4798 | // x2 = load i32 |
| 4799 | // ... |
| 4800 | // b2: |
| 4801 | // x = phi x1, x2 |
| 4802 | // y = and x, 0xff |
| 4803 | // |
| 4804 | // becomes (after a call to optimizeLoadExt for each load): |
| 4805 | // |
| 4806 | // b0: |
| 4807 | // x1 = load i32 |
| 4808 | // x1' = and x1, 0xff |
| 4809 | // ... |
| 4810 | // b1: |
| 4811 | // x2 = load i32 |
| 4812 | // x2' = and x2, 0xff |
| 4813 | // ... |
| 4814 | // b2: |
| 4815 | // x = phi x1', x2' |
| 4816 | // y = and x, 0xff |
| 4817 | // |
| 4818 | |
| 4819 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
| 4820 | |
| 4821 | if (!Load->isSimple() || |
| 4822 | !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy())) |
| 4823 | return false; |
| 4824 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 4825 | // Skip loads we've already transformed. |
| 4826 | if (Load->hasOneUse() && |
| 4827 | InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) |
| 4828 | return false; |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 4829 | |
| 4830 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 4831 | // of the loaded value are needed. |
| 4832 | SmallVector<Instruction *, 8> WorkList; |
| 4833 | SmallPtrSet<Instruction *, 16> Visited; |
| 4834 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 4835 | for (auto *U : Load->users()) |
| 4836 | WorkList.push_back(cast<Instruction>(U)); |
| 4837 | |
| 4838 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 4839 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 4840 | APInt DemandBits(BitWidth, 0); |
| 4841 | APInt WidestAndBits(BitWidth, 0); |
| 4842 | |
| 4843 | while (!WorkList.empty()) { |
| 4844 | Instruction *I = WorkList.back(); |
| 4845 | WorkList.pop_back(); |
| 4846 | |
| 4847 | // Break use-def graph loops. |
| 4848 | if (!Visited.insert(I).second) |
| 4849 | continue; |
| 4850 | |
| 4851 | // For a PHI node, push all of its users. |
| 4852 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 4853 | for (auto *U : Phi->users()) |
| 4854 | WorkList.push_back(cast<Instruction>(U)); |
| 4855 | continue; |
| 4856 | } |
| 4857 | |
| 4858 | switch (I->getOpcode()) { |
| 4859 | case llvm::Instruction::And: { |
| 4860 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4861 | if (!AndC) |
| 4862 | return false; |
| 4863 | APInt AndBits = AndC->getValue(); |
| 4864 | DemandBits |= AndBits; |
| 4865 | // Keep track of the widest and mask we see. |
| 4866 | if (AndBits.ugt(WidestAndBits)) |
| 4867 | WidestAndBits = AndBits; |
| 4868 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 4869 | AndsToMaybeRemove.push_back(I); |
| 4870 | break; |
| 4871 | } |
| 4872 | |
| 4873 | case llvm::Instruction::Shl: { |
| 4874 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 4875 | if (!ShlC) |
| 4876 | return false; |
| 4877 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
| 4878 | auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt); |
| 4879 | DemandBits |= ShlDemandBits; |
| 4880 | break; |
| 4881 | } |
| 4882 | |
| 4883 | case llvm::Instruction::Trunc: { |
| 4884 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 4885 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
| 4886 | auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth); |
| 4887 | DemandBits |= TruncBits; |
| 4888 | break; |
| 4889 | } |
| 4890 | |
| 4891 | default: |
| 4892 | return false; |
| 4893 | } |
| 4894 | } |
| 4895 | |
| 4896 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 4897 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 4898 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 4899 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 4900 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 4901 | // followed by an AND. |
| 4902 | // TODO: Look into removing this restriction by fixing backends to either |
| 4903 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 4904 | // a single instruction. |
| 4905 | // |
| 4906 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 4907 | // mask, since these are the only ands that will be removed by isel. |
| 4908 | if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) || |
| 4909 | WidestAndBits != DemandBits) |
| 4910 | return false; |
| 4911 | |
| 4912 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 4913 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 4914 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 4915 | |
| 4916 | // Reject cases that won't be matched as extloads. |
| 4917 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 4918 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 4919 | return false; |
| 4920 | |
| 4921 | IRBuilder<> Builder(Load->getNextNode()); |
| 4922 | auto *NewAnd = dyn_cast<Instruction>( |
| 4923 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 4924 | // Mark this instruction as "inserted by CGP", so that other |
| 4925 | // optimizations don't touch it. |
| 4926 | InsertedInsts.insert(NewAnd); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 4927 | |
| 4928 | // Replace all uses of load with new and (except for the use of load in the |
| 4929 | // new and itself). |
| 4930 | Load->replaceAllUsesWith(NewAnd); |
| 4931 | NewAnd->setOperand(0, Load); |
| 4932 | |
| 4933 | // Remove any and instructions that are now redundant. |
| 4934 | for (auto *And : AndsToMaybeRemove) |
| 4935 | // Check that the and mask is the same as the one we decided to put on the |
| 4936 | // new and. |
| 4937 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 4938 | And->replaceAllUsesWith(NewAnd); |
| 4939 | if (&*CurInstIterator == And) |
| 4940 | CurInstIterator = std::next(And->getIterator()); |
| 4941 | And->eraseFromParent(); |
| 4942 | ++NumAndUses; |
| 4943 | } |
| 4944 | |
| 4945 | ++NumAndsAdded; |
| 4946 | return true; |
| 4947 | } |
| 4948 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4949 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 4950 | /// that is only used once. |
| 4951 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 4952 | auto *I = dyn_cast<Instruction>(V); |
| 4953 | // If it's safe to speculatively execute, then it should not have side |
| 4954 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 4955 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 4956 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4957 | } |
| 4958 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4959 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4960 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4961 | const TargetLowering *TLI, |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4962 | SelectInst *SI) { |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4963 | // If even a predictable select is cheap, then a branch can't be cheaper. |
| 4964 | if (!TLI->isPredictableSelectExpensive()) |
| 4965 | return false; |
| 4966 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4967 | // FIXME: This should use the same heuristics as IfConversion to determine |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4968 | // whether a select is better represented as a branch. |
| 4969 | |
| 4970 | // If metadata tells us that the select condition is obviously predictable, |
| 4971 | // then we want to replace the select with a branch. |
| 4972 | uint64_t TrueWeight, FalseWeight; |
| 4973 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { |
| 4974 | uint64_t Max = std::max(TrueWeight, FalseWeight); |
| 4975 | uint64_t Sum = TrueWeight + FalseWeight; |
Sanjay Patel | c7b91e6 | 2016-05-09 17:31:55 +0000 | [diff] [blame] | 4976 | if (Sum != 0) { |
| 4977 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); |
| 4978 | if (Probability > TLI->getPredictableBranchThreshold()) |
| 4979 | return true; |
| 4980 | } |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 4981 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4982 | |
| 4983 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 4984 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 4985 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 4986 | // comparison condition. If the compare has more than one use, there's |
| 4987 | // 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] | 4988 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4989 | return false; |
| 4990 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4991 | // If either operand of the select is expensive and only needed on one side |
| 4992 | // of the select, we should form a branch. |
| 4993 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 4994 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 4995 | return true; |
| 4996 | |
| 4997 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4998 | } |
| 4999 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5000 | /// If \p isTrue is true, return the true value of \p SI, otherwise return |
| 5001 | /// false value of \p SI. If the true/false value of \p SI is defined by any |
| 5002 | /// select instructions in \p Selects, look through the defining select |
| 5003 | /// instruction until the true/false value is not defined in \p Selects. |
| 5004 | static Value *getTrueOrFalseValue( |
| 5005 | SelectInst *SI, bool isTrue, |
| 5006 | const SmallPtrSet<const Instruction *, 2> &Selects) { |
| 5007 | Value *V; |
| 5008 | |
| 5009 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); |
| 5010 | DefSI = dyn_cast<SelectInst>(V)) { |
Dehao Chen | c32d712 | 2016-09-12 20:29:54 +0000 | [diff] [blame] | 5011 | assert(DefSI->getCondition() == SI->getCondition() && |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5012 | "The condition of DefSI does not match with SI"); |
| 5013 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); |
| 5014 | } |
| 5015 | return V; |
| 5016 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5017 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5018 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 5019 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5020 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5021 | // Find all consecutive select instructions that share the same condition. |
| 5022 | SmallVector<SelectInst *, 2> ASI; |
| 5023 | ASI.push_back(SI); |
| 5024 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); |
| 5025 | It != SI->getParent()->end(); ++It) { |
| 5026 | SelectInst *I = dyn_cast<SelectInst>(&*It); |
| 5027 | if (I && SI->getCondition() == I->getCondition()) { |
| 5028 | ASI.push_back(I); |
| 5029 | } else { |
| 5030 | break; |
| 5031 | } |
| 5032 | } |
| 5033 | |
| 5034 | SelectInst *LastSI = ASI.back(); |
| 5035 | // Increment the current iterator to skip all the rest of select instructions |
| 5036 | // because they will be either "not lowered" or "all lowered" to branch. |
| 5037 | CurInstIterator = std::next(LastSI->getIterator()); |
| 5038 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5039 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 5040 | |
| 5041 | // Can we convert the 'select' to CF ? |
Sanjay Patel | a31b0c0 | 2016-04-26 00:47:39 +0000 | [diff] [blame] | 5042 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond || |
| 5043 | SI->getMetadata(LLVMContext::MD_unpredictable)) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5044 | return false; |
| 5045 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5046 | TargetLowering::SelectSupportKind SelectKind; |
| 5047 | if (VectorCond) |
| 5048 | SelectKind = TargetLowering::VectorMaskSelect; |
| 5049 | else if (SI->getType()->isVectorTy()) |
| 5050 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 5051 | else |
| 5052 | SelectKind = TargetLowering::ScalarValSelect; |
| 5053 | |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5054 | if (TLI->isSelectSupported(SelectKind) && |
| 5055 | !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) |
| 5056 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5057 | |
| 5058 | ModifiedDT = true; |
| 5059 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5060 | // Transform a sequence like this: |
| 5061 | // start: |
| 5062 | // %cmp = cmp uge i32 %a, %b |
| 5063 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 5064 | // |
| 5065 | // Into: |
| 5066 | // start: |
| 5067 | // %cmp = cmp uge i32 %a, %b |
| 5068 | // br i1 %cmp, label %select.true, label %select.false |
| 5069 | // select.true: |
| 5070 | // br label %select.end |
| 5071 | // select.false: |
| 5072 | // br label %select.end |
| 5073 | // select.end: |
| 5074 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 5075 | // |
| 5076 | // In addition, we may sink instructions that produce %c or %d from |
| 5077 | // the entry block into the destination(s) of the new branch. |
| 5078 | // If the true or false blocks do not contain a sunken instruction, that |
| 5079 | // block and its branch may be optimized away. In that case, one side of the |
| 5080 | // first branch will point directly to select.end, and the corresponding PHI |
| 5081 | // predecessor block will be the start block. |
| 5082 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5083 | // First, we split the block containing the select into 2 blocks. |
| 5084 | BasicBlock *StartBlock = SI->getParent(); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5085 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5086 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5087 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5088 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5089 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5090 | |
| 5091 | // These are the new basic blocks for the conditional branch. |
| 5092 | // At least one will become an actual new basic block. |
| 5093 | BasicBlock *TrueBlock = nullptr; |
| 5094 | BasicBlock *FalseBlock = nullptr; |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5095 | BranchInst *TrueBranch = nullptr; |
| 5096 | BranchInst *FalseBranch = nullptr; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5097 | |
| 5098 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 5099 | // them speculatively. |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5100 | for (SelectInst *SI : ASI) { |
| 5101 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 5102 | if (TrueBlock == nullptr) { |
| 5103 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 5104 | EndBlock->getParent(), EndBlock); |
| 5105 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 5106 | } |
| 5107 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 5108 | TrueInst->moveBefore(TrueBranch); |
| 5109 | } |
| 5110 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 5111 | if (FalseBlock == nullptr) { |
| 5112 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 5113 | EndBlock->getParent(), EndBlock); |
| 5114 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 5115 | } |
| 5116 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 5117 | FalseInst->moveBefore(FalseBranch); |
| 5118 | } |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5119 | } |
| 5120 | |
| 5121 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 5122 | // for a new input value to the PHI. |
| 5123 | if (TrueBlock == FalseBlock) { |
| 5124 | assert(TrueBlock == nullptr && |
| 5125 | "Unexpected basic block transform while optimizing select"); |
| 5126 | |
| 5127 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 5128 | EndBlock->getParent(), EndBlock); |
| 5129 | BranchInst::Create(EndBlock, FalseBlock); |
| 5130 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5131 | |
| 5132 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5133 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 5134 | // of the condition, it means that side of the branch goes to the end block |
| 5135 | // directly and the path originates from the start block from the point of |
| 5136 | // view of the new PHI. |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5137 | BasicBlock *TT, *FT; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5138 | if (TrueBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5139 | TT = EndBlock; |
| 5140 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5141 | TrueBlock = StartBlock; |
| 5142 | } else if (FalseBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5143 | TT = TrueBlock; |
| 5144 | FT = EndBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5145 | FalseBlock = StartBlock; |
| 5146 | } else { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5147 | TT = TrueBlock; |
| 5148 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5149 | } |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5150 | IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5151 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5152 | SmallPtrSet<const Instruction *, 2> INS; |
| 5153 | INS.insert(ASI.begin(), ASI.end()); |
| 5154 | // Use reverse iterator because later select may use the value of the |
| 5155 | // earlier select, and we need to propagate value through earlier select |
| 5156 | // to get the PHI operand. |
| 5157 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { |
| 5158 | SelectInst *SI = *It; |
| 5159 | // The select itself is replaced with a PHI Node. |
| 5160 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
| 5161 | PN->takeName(SI); |
| 5162 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); |
| 5163 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5164 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5165 | SI->replaceAllUsesWith(PN); |
| 5166 | SI->eraseFromParent(); |
| 5167 | INS.erase(SI); |
| 5168 | ++NumSelectsExpanded; |
| 5169 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5170 | |
| 5171 | // Instruct OptimizeBlock to skip to the next block. |
| 5172 | CurInstIterator = StartBlock->end(); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5173 | return true; |
| 5174 | } |
| 5175 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 5176 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5177 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 5178 | int SplatElem = -1; |
| 5179 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 5180 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 5181 | return false; |
| 5182 | SplatElem = Mask[i]; |
| 5183 | } |
| 5184 | |
| 5185 | return true; |
| 5186 | } |
| 5187 | |
| 5188 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 5189 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 5190 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 5191 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5192 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5193 | BasicBlock *DefBB = SVI->getParent(); |
| 5194 | |
| 5195 | // Only do this xform if variable vector shifts are particularly expensive. |
| 5196 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 5197 | return false; |
| 5198 | |
| 5199 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 5200 | // constant splat. |
| 5201 | if (!isBroadcastShuffle(SVI)) |
| 5202 | return false; |
| 5203 | |
| 5204 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 5205 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 5206 | |
| 5207 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5208 | for (User *U : SVI->users()) { |
| 5209 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5210 | |
| 5211 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5212 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5213 | if (UserBB == DefBB) continue; |
| 5214 | |
| 5215 | // 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] | 5216 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5217 | |
| 5218 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 5219 | // already have a copy. |
| 5220 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 5221 | |
| 5222 | if (!InsertedShuffle) { |
| 5223 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5224 | assert(InsertPt != UserBB->end()); |
| 5225 | InsertedShuffle = |
| 5226 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 5227 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5228 | } |
| 5229 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5230 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5231 | MadeChange = true; |
| 5232 | } |
| 5233 | |
| 5234 | // If we removed all uses, nuke the shuffle. |
| 5235 | if (SVI->use_empty()) { |
| 5236 | SVI->eraseFromParent(); |
| 5237 | MadeChange = true; |
| 5238 | } |
| 5239 | |
| 5240 | return MadeChange; |
| 5241 | } |
| 5242 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5243 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 5244 | if (!TLI || !DL) |
| 5245 | return false; |
| 5246 | |
| 5247 | Value *Cond = SI->getCondition(); |
| 5248 | Type *OldType = Cond->getType(); |
| 5249 | LLVMContext &Context = Cond->getContext(); |
| 5250 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 5251 | unsigned RegWidth = RegType.getSizeInBits(); |
| 5252 | |
| 5253 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 5254 | return false; |
| 5255 | |
| 5256 | // If the register width is greater than the type width, expand the condition |
| 5257 | // of the switch instruction and each case constant to the width of the |
| 5258 | // register. By widening the type of the switch condition, subsequent |
| 5259 | // comparisons (for case comparisons) will not need to be extended to the |
| 5260 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 5261 | // where N is the number of cases in the switch. |
| 5262 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 5263 | |
| 5264 | // Zero-extend the switch condition and case constants unless the switch |
| 5265 | // condition is a function argument that is already being sign-extended. |
| 5266 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 5267 | // everything instead. |
| 5268 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 5269 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 5270 | if (Arg->hasSExtAttr()) |
| 5271 | ExtType = Instruction::SExt; |
| 5272 | |
| 5273 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 5274 | ExtInst->insertBefore(SI); |
| 5275 | SI->setCondition(ExtInst); |
| 5276 | for (SwitchInst::CaseIt Case : SI->cases()) { |
| 5277 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 5278 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 5279 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 5280 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 5281 | } |
| 5282 | |
| 5283 | return true; |
| 5284 | } |
| 5285 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5286 | namespace { |
| 5287 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 5288 | /// This class is used to move downward extractelement transition. |
| 5289 | /// E.g., |
| 5290 | /// a = vector_op <2 x i32> |
| 5291 | /// b = extractelement <2 x i32> a, i32 0 |
| 5292 | /// c = scalar_op b |
| 5293 | /// store c |
| 5294 | /// |
| 5295 | /// => |
| 5296 | /// a = vector_op <2 x i32> |
| 5297 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 5298 | /// * d = extractelement <2 x i32> c, i32 0 |
| 5299 | /// * store d |
| 5300 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 5301 | /// transition. |
| 5302 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5303 | /// DataLayout associated with the current module. |
| 5304 | const DataLayout &DL; |
| 5305 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5306 | /// Used to perform some checks on the legality of vector operations. |
| 5307 | const TargetLowering &TLI; |
| 5308 | |
| 5309 | /// Used to estimated the cost of the promoted chain. |
| 5310 | const TargetTransformInfo &TTI; |
| 5311 | |
| 5312 | /// The transition being moved downwards. |
| 5313 | Instruction *Transition; |
| 5314 | /// The sequence of instructions to be promoted. |
| 5315 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 5316 | /// Cost of combining a store and an extract. |
| 5317 | unsigned StoreExtractCombineCost; |
| 5318 | /// Instruction that will be combined with the transition. |
| 5319 | Instruction *CombineInst; |
| 5320 | |
| 5321 | /// \brief The instruction that represents the current end of the transition. |
| 5322 | /// Since we are faking the promotion until we reach the end of the chain |
| 5323 | /// of computation, we need a way to get the current end of the transition. |
| 5324 | Instruction *getEndOfTransition() const { |
| 5325 | if (InstsToBePromoted.empty()) |
| 5326 | return Transition; |
| 5327 | return InstsToBePromoted.back(); |
| 5328 | } |
| 5329 | |
| 5330 | /// \brief Return the index of the original value in the transition. |
| 5331 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 5332 | /// c, is at index 0. |
| 5333 | unsigned getTransitionOriginalValueIdx() const { |
| 5334 | assert(isa<ExtractElementInst>(Transition) && |
| 5335 | "Other kind of transitions are not supported yet"); |
| 5336 | return 0; |
| 5337 | } |
| 5338 | |
| 5339 | /// \brief Return the index of the index in the transition. |
| 5340 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 5341 | /// is at index 1. |
| 5342 | unsigned getTransitionIdx() const { |
| 5343 | assert(isa<ExtractElementInst>(Transition) && |
| 5344 | "Other kind of transitions are not supported yet"); |
| 5345 | return 1; |
| 5346 | } |
| 5347 | |
| 5348 | /// \brief Get the type of the transition. |
| 5349 | /// This is the type of the original value. |
| 5350 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 5351 | /// transition is <2 x i32>. |
| 5352 | Type *getTransitionType() const { |
| 5353 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 5354 | } |
| 5355 | |
| 5356 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 5357 | /// I.e., we have the following sequence: |
| 5358 | /// Def = Transition <ty1> a to <ty2> |
| 5359 | /// b = ToBePromoted <ty2> Def, ... |
| 5360 | /// => |
| 5361 | /// b = ToBePromoted <ty1> a, ... |
| 5362 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 5363 | void promoteImpl(Instruction *ToBePromoted); |
| 5364 | |
| 5365 | /// \brief Check whether or not it is profitable to promote all the |
| 5366 | /// instructions enqueued to be promoted. |
| 5367 | bool isProfitableToPromote() { |
| 5368 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5369 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 5370 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 5371 | : -1; |
| 5372 | Type *PromotedType = getTransitionType(); |
| 5373 | |
| 5374 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 5375 | unsigned AS = ST->getPointerAddressSpace(); |
| 5376 | unsigned Align = ST->getAlignment(); |
| 5377 | // Check if this store is supported. |
| 5378 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5379 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 5380 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5381 | // If this is not supported, there is no way we can combine |
| 5382 | // the extract with the store. |
| 5383 | return false; |
| 5384 | } |
| 5385 | |
| 5386 | // The scalar chain of computation has to pay for the transition |
| 5387 | // scalar to vector. |
| 5388 | // The vector chain has to account for the combining cost. |
| 5389 | uint64_t ScalarCost = |
| 5390 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 5391 | uint64_t VectorCost = StoreExtractCombineCost; |
| 5392 | for (const auto &Inst : InstsToBePromoted) { |
| 5393 | // Compute the cost. |
| 5394 | // By construction, all instructions being promoted are arithmetic ones. |
| 5395 | // Moreover, one argument is a constant that can be viewed as a splat |
| 5396 | // constant. |
| 5397 | Value *Arg0 = Inst->getOperand(0); |
| 5398 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 5399 | isa<ConstantFP>(Arg0); |
| 5400 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 5401 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5402 | : TargetTransformInfo::OK_AnyValue; |
| 5403 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 5404 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5405 | : TargetTransformInfo::OK_AnyValue; |
| 5406 | ScalarCost += TTI.getArithmeticInstrCost( |
| 5407 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 5408 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 5409 | Arg0OVK, Arg1OVK); |
| 5410 | } |
| 5411 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 5412 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 5413 | return ScalarCost > VectorCost; |
| 5414 | } |
| 5415 | |
| 5416 | /// \brief Generate a constant vector with \p Val with the same |
| 5417 | /// number of elements as the transition. |
| 5418 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 5419 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5420 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 5421 | /// otherwise we generate a vector with as many undef as possible: |
| 5422 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 5423 | /// used at the index of the extract. |
| 5424 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 5425 | unsigned ExtractIdx = UINT_MAX; |
| 5426 | if (!UseSplat) { |
| 5427 | // If we cannot determine where the constant must be, we have to |
| 5428 | // use a splat constant. |
| 5429 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 5430 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 5431 | ExtractIdx = CstVal->getSExtValue(); |
| 5432 | else |
| 5433 | UseSplat = true; |
| 5434 | } |
| 5435 | |
| 5436 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 5437 | if (UseSplat) |
| 5438 | return ConstantVector::getSplat(End, Val); |
| 5439 | |
| 5440 | SmallVector<Constant *, 4> ConstVec; |
| 5441 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 5442 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 5443 | if (Idx == ExtractIdx) |
| 5444 | ConstVec.push_back(Val); |
| 5445 | else |
| 5446 | ConstVec.push_back(UndefVal); |
| 5447 | } |
| 5448 | return ConstantVector::get(ConstVec); |
| 5449 | } |
| 5450 | |
| 5451 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 5452 | /// in \p Use can trigger undefined behavior. |
| 5453 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 5454 | unsigned OperandIdx) { |
| 5455 | // This is not safe to introduce undef when the operand is on |
| 5456 | // the right hand side of a division-like instruction. |
| 5457 | if (OperandIdx != 1) |
| 5458 | return false; |
| 5459 | switch (Use->getOpcode()) { |
| 5460 | default: |
| 5461 | return false; |
| 5462 | case Instruction::SDiv: |
| 5463 | case Instruction::UDiv: |
| 5464 | case Instruction::SRem: |
| 5465 | case Instruction::URem: |
| 5466 | return true; |
| 5467 | case Instruction::FDiv: |
| 5468 | case Instruction::FRem: |
| 5469 | return !Use->hasNoNaNs(); |
| 5470 | } |
| 5471 | llvm_unreachable(nullptr); |
| 5472 | } |
| 5473 | |
| 5474 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5475 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 5476 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 5477 | unsigned CombineCost) |
| 5478 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5479 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 5480 | assert(Transition && "Do not know how to promote null"); |
| 5481 | } |
| 5482 | |
| 5483 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 5484 | bool canPromote(const Instruction *ToBePromoted) const { |
| 5485 | // We could support CastInst too. |
| 5486 | return isa<BinaryOperator>(ToBePromoted); |
| 5487 | } |
| 5488 | |
| 5489 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 5490 | /// by moving downward the transition through. |
| 5491 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 5492 | // Promote only if all the operands can be statically expanded. |
| 5493 | // Indeed, we do not want to introduce any new kind of transitions. |
| 5494 | for (const Use &U : ToBePromoted->operands()) { |
| 5495 | const Value *Val = U.get(); |
| 5496 | if (Val == getEndOfTransition()) { |
| 5497 | // If the use is a division and the transition is on the rhs, |
| 5498 | // we cannot promote the operation, otherwise we may create a |
| 5499 | // division by zero. |
| 5500 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 5501 | return false; |
| 5502 | continue; |
| 5503 | } |
| 5504 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 5505 | !isa<ConstantFP>(Val)) |
| 5506 | return false; |
| 5507 | } |
| 5508 | // Check that the resulting operation is legal. |
| 5509 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 5510 | if (!ISDOpcode) |
| 5511 | return false; |
| 5512 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 5513 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5514 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5515 | } |
| 5516 | |
| 5517 | /// \brief Check whether or not \p Use can be combined |
| 5518 | /// with the transition. |
| 5519 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 5520 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 5521 | |
| 5522 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 5523 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 5524 | InstsToBePromoted.push_back(ToBePromoted); |
| 5525 | } |
| 5526 | |
| 5527 | /// \brief Set the instruction that will be combined with the transition. |
| 5528 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 5529 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 5530 | CombineInst = ToBeCombined; |
| 5531 | } |
| 5532 | |
| 5533 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 5534 | /// is profitable. |
| 5535 | /// \return True if the promotion happened, false otherwise. |
| 5536 | bool promote() { |
| 5537 | // Check if there is something to promote. |
| 5538 | // Right now, if we do not have anything to combine with, |
| 5539 | // we assume the promotion is not profitable. |
| 5540 | if (InstsToBePromoted.empty() || !CombineInst) |
| 5541 | return false; |
| 5542 | |
| 5543 | // Check cost. |
| 5544 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 5545 | return false; |
| 5546 | |
| 5547 | // Promote. |
| 5548 | for (auto &ToBePromoted : InstsToBePromoted) |
| 5549 | promoteImpl(ToBePromoted); |
| 5550 | InstsToBePromoted.clear(); |
| 5551 | return true; |
| 5552 | } |
| 5553 | }; |
| 5554 | } // End of anonymous namespace. |
| 5555 | |
| 5556 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 5557 | // At this point, we know that all the operands of ToBePromoted but Def |
| 5558 | // can be statically promoted. |
| 5559 | // For Def, we need to use its parameter in ToBePromoted: |
| 5560 | // b = ToBePromoted ty1 a |
| 5561 | // Def = Transition ty1 b to ty2 |
| 5562 | // Move the transition down. |
| 5563 | // 1. Replace all uses of the promoted operation by the transition. |
| 5564 | // = ... b => = ... Def. |
| 5565 | assert(ToBePromoted->getType() == Transition->getType() && |
| 5566 | "The type of the result of the transition does not match " |
| 5567 | "the final type"); |
| 5568 | ToBePromoted->replaceAllUsesWith(Transition); |
| 5569 | // 2. Update the type of the uses. |
| 5570 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 5571 | Type *TransitionTy = getTransitionType(); |
| 5572 | ToBePromoted->mutateType(TransitionTy); |
| 5573 | // 3. Update all the operands of the promoted operation with promoted |
| 5574 | // operands. |
| 5575 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 5576 | for (Use &U : ToBePromoted->operands()) { |
| 5577 | Value *Val = U.get(); |
| 5578 | Value *NewVal = nullptr; |
| 5579 | if (Val == Transition) |
| 5580 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5581 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 5582 | isa<ConstantFP>(Val)) { |
| 5583 | // Use a splat constant if it is not safe to use undef. |
| 5584 | NewVal = getConstantVector( |
| 5585 | cast<Constant>(Val), |
| 5586 | isa<UndefValue>(Val) || |
| 5587 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 5588 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 5589 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 5590 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5591 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 5592 | } |
| 5593 | Transition->removeFromParent(); |
| 5594 | Transition->insertAfter(ToBePromoted); |
| 5595 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 5596 | } |
| 5597 | |
| 5598 | /// Some targets can do store(extractelement) with one instruction. |
| 5599 | /// Try to push the extractelement towards the stores when the target |
| 5600 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5601 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5602 | unsigned CombineCost = UINT_MAX; |
| 5603 | if (DisableStoreExtract || !TLI || |
| 5604 | (!StressStoreExtract && |
| 5605 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 5606 | Inst->getOperand(1), CombineCost))) |
| 5607 | return false; |
| 5608 | |
| 5609 | // At this point we know that Inst is a vector to scalar transition. |
| 5610 | // Try to move it down the def-use chain, until: |
| 5611 | // - We can combine the transition with its single use |
| 5612 | // => we got rid of the transition. |
| 5613 | // - We escape the current basic block |
| 5614 | // => we would need to check that we are moving it at a cheaper place and |
| 5615 | // we do not do that for now. |
| 5616 | BasicBlock *Parent = Inst->getParent(); |
| 5617 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5618 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5619 | // If the transition has more than one use, assume this is not going to be |
| 5620 | // beneficial. |
| 5621 | while (Inst->hasOneUse()) { |
| 5622 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 5623 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 5624 | |
| 5625 | if (ToBePromoted->getParent() != Parent) { |
| 5626 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 5627 | << ToBePromoted->getParent()->getName() |
| 5628 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 5629 | return false; |
| 5630 | } |
| 5631 | |
| 5632 | if (VPH.canCombine(ToBePromoted)) { |
| 5633 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 5634 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 5635 | VPH.recordCombineInstruction(ToBePromoted); |
| 5636 | bool Changed = VPH.promote(); |
| 5637 | NumStoreExtractExposed += Changed; |
| 5638 | return Changed; |
| 5639 | } |
| 5640 | |
| 5641 | DEBUG(dbgs() << "Try promoting.\n"); |
| 5642 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 5643 | return false; |
| 5644 | |
| 5645 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 5646 | |
| 5647 | VPH.enqueueForPromotion(ToBePromoted); |
| 5648 | Inst = ToBePromoted; |
| 5649 | } |
| 5650 | return false; |
| 5651 | } |
| 5652 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 5653 | /// For the instruction sequence of store below, F and I values |
| 5654 | /// are bundled together as an i64 value before being stored into memory. |
| 5655 | /// Sometimes it is more efficent to generate separate stores for F and I, |
| 5656 | /// which can remove the bitwise instructions or sink them to colder places. |
| 5657 | /// |
| 5658 | /// (store (or (zext (bitcast F to i32) to i64), |
| 5659 | /// (shl (zext I to i64), 32)), addr) --> |
| 5660 | /// (store F, addr) and (store I, addr+4) |
| 5661 | /// |
| 5662 | /// Similarly, splitting for other merged store can also be beneficial, like: |
| 5663 | /// For pair of {i32, i32}, i64 store --> two i32 stores. |
| 5664 | /// For pair of {i32, i16}, i64 store --> two i32 stores. |
| 5665 | /// For pair of {i16, i16}, i32 store --> two i16 stores. |
| 5666 | /// For pair of {i16, i8}, i32 store --> two i16 stores. |
| 5667 | /// For pair of {i8, i8}, i16 store --> two i8 stores. |
| 5668 | /// |
| 5669 | /// We allow each target to determine specifically which kind of splitting is |
| 5670 | /// supported. |
| 5671 | /// |
| 5672 | /// The store patterns are commonly seen from the simple code snippet below |
| 5673 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. |
| 5674 | /// void goo(const std::pair<int, float> &); |
| 5675 | /// hoo() { |
| 5676 | /// ... |
| 5677 | /// goo(std::make_pair(tmp, ftmp)); |
| 5678 | /// ... |
| 5679 | /// } |
| 5680 | /// |
| 5681 | /// Although we already have similar splitting in DAG Combine, we duplicate |
| 5682 | /// it in CodeGenPrepare to catch the case in which pattern is across |
| 5683 | /// multiple BBs. The logic in DAG Combine is kept to catch case generated |
| 5684 | /// during code expansion. |
| 5685 | static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, |
| 5686 | const TargetLowering &TLI) { |
| 5687 | // Handle simple but common cases only. |
| 5688 | Type *StoreType = SI.getValueOperand()->getType(); |
| 5689 | if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) || |
| 5690 | DL.getTypeSizeInBits(StoreType) == 0) |
| 5691 | return false; |
| 5692 | |
| 5693 | unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; |
| 5694 | Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); |
| 5695 | if (DL.getTypeStoreSizeInBits(SplitStoreType) != |
| 5696 | DL.getTypeSizeInBits(SplitStoreType)) |
| 5697 | return false; |
| 5698 | |
| 5699 | // Match the following patterns: |
| 5700 | // (store (or (zext LValue to i64), |
| 5701 | // (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 5702 | // or |
| 5703 | // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 5704 | // (zext LValue to i64), |
| 5705 | // Expect both operands of OR and the first operand of SHL have only |
| 5706 | // one use. |
| 5707 | Value *LValue, *HValue; |
| 5708 | if (!match(SI.getValueOperand(), |
| 5709 | m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), |
| 5710 | m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), |
| 5711 | m_SpecificInt(HalfValBitSize)))))) |
| 5712 | return false; |
| 5713 | |
| 5714 | // Check LValue and HValue are int with size less or equal than 32. |
| 5715 | if (!LValue->getType()->isIntegerTy() || |
| 5716 | DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || |
| 5717 | !HValue->getType()->isIntegerTy() || |
| 5718 | DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) |
| 5719 | return false; |
| 5720 | |
| 5721 | // If LValue/HValue is a bitcast instruction, use the EVT before bitcast |
| 5722 | // as the input of target query. |
| 5723 | auto *LBC = dyn_cast<BitCastInst>(LValue); |
| 5724 | auto *HBC = dyn_cast<BitCastInst>(HValue); |
| 5725 | EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) |
| 5726 | : EVT::getEVT(LValue->getType()); |
| 5727 | EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) |
| 5728 | : EVT::getEVT(HValue->getType()); |
| 5729 | if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) |
| 5730 | return false; |
| 5731 | |
| 5732 | // Start to split store. |
| 5733 | IRBuilder<> Builder(SI.getContext()); |
| 5734 | Builder.SetInsertPoint(&SI); |
| 5735 | |
| 5736 | // If LValue/HValue is a bitcast in another BB, create a new one in current |
| 5737 | // BB so it may be merged with the splitted stores by dag combiner. |
| 5738 | if (LBC && LBC->getParent() != SI.getParent()) |
| 5739 | LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); |
| 5740 | if (HBC && HBC->getParent() != SI.getParent()) |
| 5741 | HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); |
| 5742 | |
| 5743 | auto CreateSplitStore = [&](Value *V, bool Upper) { |
| 5744 | V = Builder.CreateZExtOrBitCast(V, SplitStoreType); |
| 5745 | Value *Addr = Builder.CreateBitCast( |
| 5746 | SI.getOperand(1), |
| 5747 | SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); |
| 5748 | if (Upper) |
| 5749 | Addr = Builder.CreateGEP( |
| 5750 | SplitStoreType, Addr, |
| 5751 | ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); |
| 5752 | Builder.CreateAlignedStore( |
| 5753 | V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment()); |
| 5754 | }; |
| 5755 | |
| 5756 | CreateSplitStore(LValue, false); |
| 5757 | CreateSplitStore(HValue, true); |
| 5758 | |
| 5759 | // Delete the old store. |
| 5760 | SI.eraseFromParent(); |
| 5761 | return true; |
| 5762 | } |
| 5763 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5764 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5765 | // Bail out if we inserted the instruction to prevent optimizations from |
| 5766 | // stepping on each other's toes. |
| 5767 | if (InsertedInsts.count(I)) |
| 5768 | return false; |
| 5769 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5770 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 5771 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 5772 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 5773 | // trivial PHI, go ahead and zap it here. |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 5774 | if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5775 | P->replaceAllUsesWith(V); |
| 5776 | P->eraseFromParent(); |
| 5777 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5778 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5779 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5780 | return false; |
| 5781 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5782 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5783 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5784 | // If the source of the cast is a constant, then this should have |
| 5785 | // already been constant folded. The only reason NOT to constant fold |
| 5786 | // it is if something (e.g. LSR) was careful to place the constant |
| 5787 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 5788 | // the address of globals out of a loop). If this is the case, we don't |
| 5789 | // want to forward-subst the cast. |
| 5790 | if (isa<Constant>(CI->getOperand(0))) |
| 5791 | return false; |
| 5792 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5793 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5794 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5795 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5796 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5797 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 5798 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5799 | if (TLI && |
| 5800 | TLI->getTypeAction(CI->getContext(), |
| 5801 | TLI->getValueType(*DL, CI->getType())) == |
| 5802 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5803 | return SinkCast(CI); |
| 5804 | } else { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5805 | bool MadeChange = moveExtToFormExtLoad(I); |
| 5806 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5807 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5808 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5809 | return false; |
| 5810 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5811 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5812 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 5813 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 5814 | return OptimizeCmpExpression(CI, TLI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5815 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5816 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 5817 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5818 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5819 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5820 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5821 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 5822 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5823 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 5824 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5825 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5826 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5827 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 5828 | if (TLI && splitMergedValStore(*SI, *DL, *TLI)) |
| 5829 | return true; |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 5830 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5831 | if (TLI) { |
| 5832 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5833 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 5834 | SI->getOperand(0)->getType(), AS); |
| 5835 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5836 | return false; |
| 5837 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5838 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 5839 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
| 5840 | unsigned AS = RMW->getPointerAddressSpace(); |
| 5841 | return optimizeMemoryInst(I, RMW->getPointerOperand(), |
| 5842 | RMW->getType(), AS); |
| 5843 | } |
| 5844 | |
| 5845 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { |
| 5846 | unsigned AS = CmpX->getPointerAddressSpace(); |
| 5847 | return optimizeMemoryInst(I, CmpX->getPointerOperand(), |
| 5848 | CmpX->getCompareOperand()->getType(), AS); |
| 5849 | } |
| 5850 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5851 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 5852 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5853 | if (BinOp && (BinOp->getOpcode() == Instruction::And) && |
| 5854 | EnableAndCmpSinking && TLI) |
| 5855 | return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); |
| 5856 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5857 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 5858 | BinOp->getOpcode() == Instruction::LShr)) { |
| 5859 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 5860 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5861 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 5862 | |
| 5863 | return false; |
| 5864 | } |
| 5865 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5866 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5867 | if (GEPI->hasAllZeroIndices()) { |
| 5868 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 5869 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 5870 | GEPI->getName(), GEPI); |
| 5871 | GEPI->replaceAllUsesWith(NC); |
| 5872 | GEPI->eraseFromParent(); |
| 5873 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5874 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5875 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 5876 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5877 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5878 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5879 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5880 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5881 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5882 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5883 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5884 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5885 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5886 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5887 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5888 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5889 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 5890 | return optimizeSwitchInst(Switch); |
| 5891 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5892 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5893 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5894 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5895 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5896 | } |
| 5897 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5898 | /// Given an OR instruction, check to see if this is a bitreverse |
| 5899 | /// idiom. If so, insert the new intrinsic and return true. |
| 5900 | static bool makeBitReverse(Instruction &I, const DataLayout &DL, |
| 5901 | const TargetLowering &TLI) { |
| 5902 | if (!I.getType()->isIntegerTy() || |
| 5903 | !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, |
| 5904 | TLI.getValueType(DL, I.getType(), true))) |
| 5905 | return false; |
| 5906 | |
| 5907 | SmallVector<Instruction*, 4> Insts; |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 5908 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5909 | return false; |
| 5910 | Instruction *LastInst = Insts.back(); |
| 5911 | I.replaceAllUsesWith(LastInst); |
| 5912 | RecursivelyDeleteTriviallyDeadInstructions(&I); |
| 5913 | return true; |
| 5914 | } |
| 5915 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5916 | // In this pass we look for GEP and cast instructions that are used |
| 5917 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 5918 | // selection. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5919 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 5920 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 5921 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 5922 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 5923 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5924 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5925 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 5926 | if (ModifiedDT) |
| 5927 | return true; |
| 5928 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 5929 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5930 | bool MadeBitReverse = true; |
| 5931 | while (TLI && MadeBitReverse) { |
| 5932 | MadeBitReverse = false; |
| 5933 | for (auto &I : reverse(BB)) { |
| 5934 | if (makeBitReverse(I, *DL, *TLI)) { |
| 5935 | MadeBitReverse = MadeChange = true; |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 5936 | ModifiedDT = true; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 5937 | break; |
| 5938 | } |
| 5939 | } |
| 5940 | } |
James Molloy | 3ef84c4 | 2016-01-15 10:36:01 +0000 | [diff] [blame] | 5941 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Junmo Park | 7d6c5f1 | 2016-01-28 09:42:39 +0000 | [diff] [blame] | 5942 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 5943 | return MadeChange; |
| 5944 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5945 | |
| 5946 | // 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] | 5947 | // 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] | 5948 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5949 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5950 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5951 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 5952 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 5953 | 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] | 5954 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5955 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 5956 | // Leave dbg.values that refer to an alloca alone. These |
| 5957 | // instrinsics describe the address of a variable (= the alloca) |
| 5958 | // being taken. They should not be moved next to the alloca |
| 5959 | // (and to the beginning of the scope), but rather stay close to |
| 5960 | // where said address is used. |
| 5961 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5962 | PrevNonDbgInst = Insn; |
| 5963 | continue; |
| 5964 | } |
| 5965 | |
| 5966 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 5967 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 5968 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 5969 | // after it. |
| 5970 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 5971 | continue; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5972 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 5973 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 5974 | if (isa<PHINode>(VI)) |
| 5975 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 5976 | else |
| 5977 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 5978 | MadeChange = true; |
| 5979 | ++NumDbgValueMoved; |
| 5980 | } |
| 5981 | } |
| 5982 | } |
| 5983 | return MadeChange; |
| 5984 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5985 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5986 | /// \brief Scale down both weights to fit into uint32_t. |
| 5987 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 5988 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 5989 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 5990 | NewTrue = NewTrue / Scale; |
| 5991 | NewFalse = NewFalse / Scale; |
| 5992 | } |
| 5993 | |
| 5994 | /// \brief Some targets prefer to split a conditional branch like: |
| 5995 | /// \code |
| 5996 | /// %0 = icmp ne i32 %a, 0 |
| 5997 | /// %1 = icmp ne i32 %b, 0 |
| 5998 | /// %or.cond = or i1 %0, %1 |
| 5999 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 6000 | /// \endcode |
| 6001 | /// into multiple branch instructions like: |
| 6002 | /// \code |
| 6003 | /// bb1: |
| 6004 | /// %0 = icmp ne i32 %a, 0 |
| 6005 | /// br i1 %0, label %TrueBB, label %bb2 |
| 6006 | /// bb2: |
| 6007 | /// %1 = icmp ne i32 %b, 0 |
| 6008 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 6009 | /// \endcode |
| 6010 | /// This usually allows instruction selection to do even further optimizations |
| 6011 | /// and combine the compare with the branch instruction. Currently this is |
| 6012 | /// applied for targets which have "cheap" jump instructions. |
| 6013 | /// |
| 6014 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 6015 | /// |
| 6016 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6017 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6018 | return false; |
| 6019 | |
| 6020 | bool MadeChange = false; |
| 6021 | for (auto &BB : F) { |
| 6022 | // Does this BB end with the following? |
| 6023 | // %cond1 = icmp|fcmp|binary instruction ... |
| 6024 | // %cond2 = icmp|fcmp|binary instruction ... |
| 6025 | // %cond.or = or|and i1 %cond1, cond2 |
| 6026 | // br i1 %cond.or label %dest1, label %dest2" |
| 6027 | BinaryOperator *LogicOp; |
| 6028 | BasicBlock *TBB, *FBB; |
| 6029 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 6030 | continue; |
| 6031 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 6032 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 6033 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 6034 | continue; |
| 6035 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6036 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6037 | Value *Cond1, *Cond2; |
| 6038 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 6039 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6040 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6041 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 6042 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6043 | Opc = Instruction::Or; |
| 6044 | else |
| 6045 | continue; |
| 6046 | |
| 6047 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 6048 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 6049 | continue; |
| 6050 | |
| 6051 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 6052 | |
| 6053 | // Create a new BB. |
Duncan P. N. Exon Smith | a848c47 | 2016-02-21 19:52:15 +0000 | [diff] [blame] | 6054 | auto TmpBB = |
| 6055 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", |
| 6056 | BB.getParent(), BB.getNextNode()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6057 | |
| 6058 | // Update original basic block by using the first condition directly by the |
| 6059 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6060 | Br1->setCondition(Cond1); |
| 6061 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6062 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6063 | // Depending on the conditon we have to either replace the true or the false |
| 6064 | // successor of the original branch instruction. |
| 6065 | if (Opc == Instruction::And) |
| 6066 | Br1->setSuccessor(0, TmpBB); |
| 6067 | else |
| 6068 | Br1->setSuccessor(1, TmpBB); |
| 6069 | |
| 6070 | // Fill in the new basic block. |
| 6071 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6072 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 6073 | I->removeFromParent(); |
| 6074 | I->insertBefore(Br2); |
| 6075 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6076 | |
| 6077 | // Update PHI nodes in both successors. The original BB needs to be |
| 6078 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 6079 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 6080 | // incoming edge to the PHI nodes, because both branch instructions target |
| 6081 | // now the same successor. Depending on the original branch condition |
| 6082 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 6083 | // we perform the correct update for the PHI nodes. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6084 | // This doesn't change the successor order of the just created branch |
| 6085 | // instruction (or any other instruction). |
| 6086 | if (Opc == Instruction::Or) |
| 6087 | std::swap(TBB, FBB); |
| 6088 | |
| 6089 | // Replace the old BB with the new BB. |
| 6090 | for (auto &I : *TBB) { |
| 6091 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6092 | if (!PN) |
| 6093 | break; |
| 6094 | int i; |
| 6095 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 6096 | PN->setIncomingBlock(i, TmpBB); |
| 6097 | } |
| 6098 | |
| 6099 | // Add another incoming edge form the new BB. |
| 6100 | for (auto &I : *FBB) { |
| 6101 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6102 | if (!PN) |
| 6103 | break; |
| 6104 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 6105 | PN->addIncoming(Val, TmpBB); |
| 6106 | } |
| 6107 | |
| 6108 | // Update the branch weights (from SelectionDAGBuilder:: |
| 6109 | // FindMergedConditions). |
| 6110 | if (Opc == Instruction::Or) { |
| 6111 | // Codegen X | Y as: |
| 6112 | // BB1: |
| 6113 | // jmp_if_X TBB |
| 6114 | // jmp TmpBB |
| 6115 | // TmpBB: |
| 6116 | // jmp_if_Y TBB |
| 6117 | // jmp FBB |
| 6118 | // |
| 6119 | |
| 6120 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 6121 | // The requirement is that |
| 6122 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 6123 | // = TrueProb for orignal BB. |
| 6124 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6125 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 6126 | // assumes that |
| 6127 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 6128 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 6129 | // TmpBB, but the math is more complicated. |
| 6130 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6131 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6132 | uint64_t NewTrueWeight = TrueWeight; |
| 6133 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 6134 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6135 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6136 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6137 | |
| 6138 | NewTrueWeight = TrueWeight; |
| 6139 | NewFalseWeight = 2 * FalseWeight; |
| 6140 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6141 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6142 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6143 | } |
| 6144 | } else { |
| 6145 | // Codegen X & Y as: |
| 6146 | // BB1: |
| 6147 | // jmp_if_X TmpBB |
| 6148 | // jmp FBB |
| 6149 | // TmpBB: |
| 6150 | // jmp_if_Y TBB |
| 6151 | // jmp FBB |
| 6152 | // |
| 6153 | // This requires creation of TmpBB after CurBB. |
| 6154 | |
| 6155 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 6156 | // The requirement is that |
| 6157 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 6158 | // = FalseProb for orignal BB. |
| 6159 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6160 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 6161 | // assumes that |
| 6162 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 6163 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6164 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6165 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 6166 | uint64_t NewFalseWeight = FalseWeight; |
| 6167 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6168 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6169 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6170 | |
| 6171 | NewTrueWeight = 2 * TrueWeight; |
| 6172 | NewFalseWeight = FalseWeight; |
| 6173 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6174 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6175 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6176 | } |
| 6177 | } |
| 6178 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6179 | // 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] | 6180 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6181 | ModifiedDT = true; |
| 6182 | |
| 6183 | MadeChange = true; |
| 6184 | |
| 6185 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 6186 | TmpBB->dump()); |
| 6187 | } |
| 6188 | return MadeChange; |
| 6189 | } |