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" |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 17 | #include "llvm/CodeGen/TargetPassConfig.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/DenseMap.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/SmallSet.h" |
| 21 | #include "llvm/ADT/Statistic.h" |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 23 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/CFG.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/InstructionSimplify.h" |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/LoopInfo.h" |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/MemoryBuiltins.h" |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 30 | #include "llvm/Analysis/TargetTransformInfo.h" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 31 | #include "llvm/Analysis/ValueTracking.h" |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 32 | #include "llvm/CodeGen/Analysis.h" |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 33 | #include "llvm/CodeGen/Passes.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 34 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 35 | #include "llvm/IR/Constants.h" |
| 36 | #include "llvm/IR/DataLayout.h" |
| 37 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 38 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 39 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 40 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 41 | #include "llvm/IR/IRBuilder.h" |
| 42 | #include "llvm/IR/InlineAsm.h" |
| 43 | #include "llvm/IR/Instructions.h" |
| 44 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 45 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 46 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 47 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 48 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 49 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 50 | #include "llvm/Pass.h" |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 51 | #include "llvm/Support/BranchProbability.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 52 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 53 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 54 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 55 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 56 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 57 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 58 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 59 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 60 | #include "llvm/Transforms/Utils/Cloning.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 61 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 62 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 63 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 64 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 65 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 66 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 67 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 68 | #define DEBUG_TYPE "codegenprepare" |
| 69 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 70 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 71 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 72 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 73 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 74 | "sunken Cmps"); |
| 75 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 76 | "of sunken Casts"); |
| 77 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 78 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 79 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 80 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 81 | STATISTIC(NumAndsAdded, |
| 82 | "Number of and mask instructions added to form ext loads"); |
| 83 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 84 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 85 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 86 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 87 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 88 | |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 89 | STATISTIC(NumMemCmpCalls, "Number of memcmp calls"); |
| 90 | STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size"); |
| 91 | STATISTIC(NumMemCmpGreaterThanMax, |
| 92 | "Number of memcmp calls with size greater than max size"); |
| 93 | STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls"); |
| 94 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 95 | static cl::opt<bool> DisableBranchOpts( |
| 96 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 97 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 98 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 99 | static cl::opt<bool> |
| 100 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 101 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 102 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 103 | static cl::opt<bool> DisableSelectToBranch( |
| 104 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 105 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 106 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 107 | static cl::opt<bool> AddrSinkUsingGEPs( |
Eli Friedman | 5fba1e5 | 2017-04-06 22:42:18 +0000 | [diff] [blame] | 108 | "addr-sink-using-gep", cl::Hidden, cl::init(true), |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 109 | cl::desc("Address sinking in CGP using GEPs.")); |
| 110 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 111 | static cl::opt<bool> EnableAndCmpSinking( |
| 112 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 113 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 114 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 115 | static cl::opt<bool> DisableStoreExtract( |
| 116 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 117 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 118 | |
| 119 | static cl::opt<bool> StressStoreExtract( |
| 120 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 121 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 122 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 123 | static cl::opt<bool> DisableExtLdPromotion( |
| 124 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 125 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 126 | "CodeGenPrepare")); |
| 127 | |
| 128 | static cl::opt<bool> StressExtLdPromotion( |
| 129 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 130 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 131 | "optimization in CodeGenPrepare")); |
| 132 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 133 | static cl::opt<bool> DisablePreheaderProtect( |
| 134 | "disable-preheader-prot", cl::Hidden, cl::init(false), |
| 135 | cl::desc("Disable protection against removing loop preheaders")); |
| 136 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 137 | static cl::opt<bool> ProfileGuidedSectionPrefix( |
| 138 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), |
| 139 | cl::desc("Use profile info to add section prefix for hot/cold functions")); |
| 140 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 141 | static cl::opt<unsigned> FreqRatioToSkipMerge( |
| 142 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), |
| 143 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " |
| 144 | "(frequency of destination block) is greater than this ratio")); |
| 145 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 146 | static cl::opt<bool> ForceSplitStore( |
| 147 | "force-split-store", cl::Hidden, cl::init(false), |
| 148 | cl::desc("Force store splitting no matter what the target query says.")); |
| 149 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 150 | static cl::opt<bool> |
| 151 | EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, |
| 152 | cl::desc("Enable merging of redundant sexts when one is dominating" |
| 153 | " the other."), cl::init(true)); |
| 154 | |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 155 | static cl::opt<unsigned> MemCmpNumLoadsPerBlock( |
| 156 | "memcmp-num-loads-per-block", cl::Hidden, cl::init(1), |
| 157 | cl::desc("The number of loads per basic block for inline expansion of " |
| 158 | "memcmp that is only being compared against zero.")); |
| 159 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 160 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 161 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 162 | typedef PointerIntPair<Type *, 1, bool> TypeIsSExt; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 163 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 164 | typedef SmallVector<Instruction *, 16> SExts; |
| 165 | typedef DenseMap<Value *, SExts> ValueToSExts; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 166 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 167 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 168 | class CodeGenPrepare : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 169 | const TargetMachine *TM; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 170 | const TargetSubtargetInfo *SubtargetInfo; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 171 | const TargetLowering *TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 172 | const TargetRegisterInfo *TRI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 173 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 174 | const TargetLibraryInfo *TLInfo; |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 175 | const LoopInfo *LI; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 176 | std::unique_ptr<BlockFrequencyInfo> BFI; |
| 177 | std::unique_ptr<BranchProbabilityInfo> BPI; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 178 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 179 | /// As we scan instructions optimizing them, this is the next instruction |
| 180 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 181 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 182 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 183 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 184 | /// This allows us to avoid inserting duplicate code for blocks with |
| 185 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 186 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 187 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 188 | /// Keeps track of all instructions inserted for the current function. |
| 189 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 190 | /// Keeps track of the type of the related instruction before their |
| 191 | /// promotion for the current function. |
| 192 | InstrToOrigTy PromotedInsts; |
| 193 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 194 | /// Keep track of instructions removed during promotion. |
| 195 | SetOfInstrs RemovedInsts; |
| 196 | |
| 197 | /// Keep track of sext chains based on their initial value. |
| 198 | DenseMap<Value *, Instruction *> SeenChainsForSExt; |
| 199 | |
| 200 | /// Keep track of SExt promoted. |
| 201 | ValueToSExts ValToSExtendedUses; |
| 202 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 203 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 204 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 205 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 206 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 207 | bool OptSize; |
| 208 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 209 | /// DataLayout for the Function being processed. |
| 210 | const DataLayout *DL; |
| 211 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 212 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 213 | static char ID; // Pass identification, replacement for typeid |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 214 | CodeGenPrepare() |
| 215 | : FunctionPass(ID), TM(nullptr), TLI(nullptr), TTI(nullptr), |
| 216 | DL(nullptr) { |
| 217 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 218 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 219 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 220 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 221 | StringRef getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 222 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 223 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 224 | // FIXME: When we can selectively preserve passes, preserve the domtree. |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 225 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 226 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 227 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 228 | AU.addRequired<LoopInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 229 | } |
| 230 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 231 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 232 | bool eliminateFallThrough(Function &F); |
| 233 | bool eliminateMostlyEmptyBlocks(Function &F); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 234 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 235 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 236 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 237 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, |
| 238 | bool isPreheader); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 239 | bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 240 | bool optimizeInst(Instruction *I, bool& ModifiedDT); |
| 241 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 242 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 243 | bool optimizeInlineAsmInst(CallInst *CS); |
| 244 | bool optimizeCallInst(CallInst *CI, bool& ModifiedDT); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 245 | bool optimizeExt(Instruction *&I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 246 | bool optimizeExtUses(Instruction *I); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 247 | bool optimizeLoadExt(LoadInst *I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 248 | bool optimizeSelectInst(SelectInst *SI); |
| 249 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 250 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 251 | bool optimizeExtractElementInst(Instruction *Inst); |
| 252 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 253 | bool placeDbgValues(Function &F); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 254 | bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, |
| 255 | LoadInst *&LI, Instruction *&Inst, bool HasPromoted); |
| 256 | bool tryToPromoteExts(TypePromotionTransaction &TPT, |
| 257 | const SmallVectorImpl<Instruction *> &Exts, |
| 258 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 259 | unsigned CreatedInstsCost = 0); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 260 | bool mergeSExts(Function &F); |
| 261 | bool performAddressTypePromotion( |
| 262 | Instruction *&Inst, |
| 263 | bool AllowPromotionWithoutCommonHeader, |
| 264 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 265 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 266 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 267 | bool simplifyOffsetableRelocate(Instruction &I); |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 268 | bool splitIndirectCriticalEdges(Function &F); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 269 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 270 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 271 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 272 | char CodeGenPrepare::ID = 0; |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 273 | INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE, |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 274 | "Optimize for code generation", false, false) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 275 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 276 | INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 277 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 278 | |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 279 | FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 280 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 281 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 282 | if (skipFunction(F)) |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 283 | return false; |
| 284 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 285 | DL = &F.getParent()->getDataLayout(); |
| 286 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 287 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 288 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 289 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 290 | PromotedInsts.clear(); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 291 | BFI.reset(); |
| 292 | BPI.reset(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 293 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 294 | ModifiedDT = false; |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 295 | if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) { |
| 296 | TM = &TPC->getTM<TargetMachine>(); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 297 | SubtargetInfo = TM->getSubtargetImpl(F); |
| 298 | TLI = SubtargetInfo->getTargetLowering(); |
| 299 | TRI = SubtargetInfo->getRegisterInfo(); |
| 300 | } |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 301 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 302 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 303 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 304 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 305 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 306 | if (ProfileGuidedSectionPrefix) { |
| 307 | ProfileSummaryInfo *PSI = |
| 308 | getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); |
Dehao Chen | 775341a | 2017-03-23 23:14:11 +0000 | [diff] [blame] | 309 | if (PSI->isFunctionHotInCallGraph(&F)) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 310 | F.setSectionPrefix(".hot"); |
Dehao Chen | 775341a | 2017-03-23 23:14:11 +0000 | [diff] [blame] | 311 | else if (PSI->isFunctionColdInCallGraph(&F)) |
Teresa Johnson | 720d9b4 | 2017-05-09 01:43:24 +0000 | [diff] [blame] | 312 | F.setSectionPrefix(".unlikely"); |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 313 | } |
| 314 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 315 | /// This optimization identifies DIV instructions that can be |
| 316 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 317 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 318 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 319 | TLI->getBypassSlowDivWidths(); |
Eric Christopher | 49a7d6c | 2016-01-04 23:18:58 +0000 | [diff] [blame] | 320 | BasicBlock* BB = &*F.begin(); |
| 321 | while (BB != nullptr) { |
| 322 | // bypassSlowDivision may create new BBs, but we don't want to reapply the |
| 323 | // optimization to those blocks. |
| 324 | BasicBlock* Next = BB->getNextNode(); |
| 325 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); |
| 326 | BB = Next; |
| 327 | } |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 328 | } |
| 329 | |
| 330 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 331 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 332 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 333 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 334 | // 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] | 335 | // 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] | 336 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 337 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 338 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 339 | if (!DisableBranchOpts) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 340 | EverMadeChange |= splitBranchCondition(F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 341 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 342 | // Split some critical edges where one of the sources is an indirect branch, |
| 343 | // to help generate sane code for PHIs involving such edges. |
| 344 | EverMadeChange |= splitIndirectCriticalEdges(F); |
| 345 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 346 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 347 | while (MadeChange) { |
| 348 | MadeChange = false; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 349 | SeenChainsForSExt.clear(); |
| 350 | ValToSExtendedUses.clear(); |
| 351 | RemovedInsts.clear(); |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 352 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 353 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 354 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 355 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 356 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 357 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 358 | if (ModifiedDTOnIteration) |
| 359 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 360 | } |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 361 | if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) |
| 362 | MadeChange |= mergeSExts(F); |
| 363 | |
| 364 | // Really free removed instructions during promotion. |
| 365 | for (Instruction *I : RemovedInsts) |
Reid Kleckner | 96ab872 | 2017-05-18 17:24:10 +0000 | [diff] [blame] | 366 | I->deleteValue(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 367 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 368 | EverMadeChange |= MadeChange; |
| 369 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 370 | |
| 371 | SunkAddrs.clear(); |
| 372 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 373 | if (!DisableBranchOpts) { |
| 374 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 375 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 376 | for (BasicBlock &BB : F) { |
| 377 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 378 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 379 | if (!MadeChange) continue; |
| 380 | |
| 381 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 382 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 383 | if (pred_begin(*II) == pred_end(*II)) |
| 384 | WorkList.insert(*II); |
| 385 | } |
| 386 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 387 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 388 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 389 | while (!WorkList.empty()) { |
| 390 | BasicBlock *BB = *WorkList.begin(); |
| 391 | WorkList.erase(BB); |
| 392 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 393 | |
| 394 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 395 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 396 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 397 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 398 | if (pred_begin(*II) == pred_end(*II)) |
| 399 | WorkList.insert(*II); |
| 400 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 401 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 402 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 403 | // a single edge. |
| 404 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 405 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 406 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 407 | EverMadeChange |= MadeChange; |
| 408 | } |
| 409 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 410 | if (!DisableGCOpts) { |
| 411 | SmallVector<Instruction *, 2> Statepoints; |
| 412 | for (BasicBlock &BB : F) |
| 413 | for (Instruction &I : BB) |
| 414 | if (isStatepoint(I)) |
| 415 | Statepoints.push_back(&I); |
| 416 | for (auto &I : Statepoints) |
| 417 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 418 | } |
| 419 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 420 | return EverMadeChange; |
| 421 | } |
| 422 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 423 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 424 | /// basic blocks has a single successor pointing to the other basic block, |
| 425 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 426 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 427 | bool Changed = false; |
| 428 | // 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] | 429 | 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] | 430 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 431 | // If the destination block has a single pred, then this is a trivial |
| 432 | // edge, just collapse it. |
| 433 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 434 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 435 | // Don't merge if BB's address is taken. |
| 436 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 437 | |
| 438 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 439 | if (Term && !Term->isConditional()) { |
| 440 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 441 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 442 | // Remember if SinglePred was the entry block of the function. |
| 443 | // If so, we will need to move BB back to the entry position. |
| 444 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 445 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 446 | |
| 447 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 448 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 449 | |
| 450 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 451 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 452 | } |
| 453 | } |
| 454 | return Changed; |
| 455 | } |
| 456 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 457 | /// Find a destination block from BB if BB is mergeable empty block. |
| 458 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { |
| 459 | // If this block doesn't end with an uncond branch, ignore it. |
| 460 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 461 | if (!BI || !BI->isUnconditional()) |
| 462 | return nullptr; |
| 463 | |
| 464 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 465 | // node, then other stuff is happening here. |
| 466 | BasicBlock::iterator BBI = BI->getIterator(); |
| 467 | if (BBI != BB->begin()) { |
| 468 | --BBI; |
| 469 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 470 | if (BBI == BB->begin()) |
| 471 | break; |
| 472 | --BBI; |
| 473 | } |
| 474 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 475 | return nullptr; |
| 476 | } |
| 477 | |
| 478 | // Do not break infinite loops. |
| 479 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 480 | if (DestBB == BB) |
| 481 | return nullptr; |
| 482 | |
| 483 | if (!canMergeBlocks(BB, DestBB)) |
| 484 | DestBB = nullptr; |
| 485 | |
| 486 | return DestBB; |
| 487 | } |
| 488 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 489 | // Return the unique indirectbr predecessor of a block. This may return null |
| 490 | // even if such a predecessor exists, if it's not useful for splitting. |
| 491 | // If a predecessor is found, OtherPreds will contain all other (non-indirectbr) |
| 492 | // predecessors of BB. |
| 493 | static BasicBlock * |
| 494 | findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) { |
| 495 | // If the block doesn't have any PHIs, we don't care about it, since there's |
| 496 | // no point in splitting it. |
| 497 | PHINode *PN = dyn_cast<PHINode>(BB->begin()); |
| 498 | if (!PN) |
| 499 | return nullptr; |
| 500 | |
| 501 | // Verify we have exactly one IBR predecessor. |
| 502 | // Conservatively bail out if one of the other predecessors is not a "regular" |
| 503 | // terminator (that is, not a switch or a br). |
| 504 | BasicBlock *IBB = nullptr; |
| 505 | for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) { |
| 506 | BasicBlock *PredBB = PN->getIncomingBlock(Pred); |
| 507 | TerminatorInst *PredTerm = PredBB->getTerminator(); |
| 508 | switch (PredTerm->getOpcode()) { |
| 509 | case Instruction::IndirectBr: |
| 510 | if (IBB) |
| 511 | return nullptr; |
| 512 | IBB = PredBB; |
| 513 | break; |
| 514 | case Instruction::Br: |
| 515 | case Instruction::Switch: |
| 516 | OtherPreds.push_back(PredBB); |
| 517 | continue; |
| 518 | default: |
| 519 | return nullptr; |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | return IBB; |
| 524 | } |
| 525 | |
| 526 | // Split critical edges where the source of the edge is an indirectbr |
| 527 | // instruction. This isn't always possible, but we can handle some easy cases. |
| 528 | // This is useful because MI is unable to split such critical edges, |
| 529 | // which means it will not be able to sink instructions along those edges. |
| 530 | // This is especially painful for indirect branches with many successors, where |
| 531 | // we end up having to prepare all outgoing values in the origin block. |
| 532 | // |
| 533 | // Our normal algorithm for splitting critical edges requires us to update |
| 534 | // the outgoing edges of the edge origin block, but for an indirectbr this |
| 535 | // is hard, since it would require finding and updating the block addresses |
| 536 | // the indirect branch uses. But if a block only has a single indirectbr |
| 537 | // predecessor, with the others being regular branches, we can do it in a |
| 538 | // different way. |
| 539 | // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr. |
| 540 | // We can split D into D0 and D1, where D0 contains only the PHIs from D, |
| 541 | // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and |
| 542 | // create the following structure: |
| 543 | // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1 |
| 544 | bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) { |
| 545 | // Check whether the function has any indirectbrs, and collect which blocks |
| 546 | // they may jump to. Since most functions don't have indirect branches, |
| 547 | // this lowers the common case's overhead to O(Blocks) instead of O(Edges). |
| 548 | SmallSetVector<BasicBlock *, 16> Targets; |
| 549 | for (auto &BB : F) { |
| 550 | auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator()); |
| 551 | if (!IBI) |
| 552 | continue; |
| 553 | |
| 554 | for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ) |
| 555 | Targets.insert(IBI->getSuccessor(Succ)); |
| 556 | } |
| 557 | |
| 558 | if (Targets.empty()) |
| 559 | return false; |
| 560 | |
| 561 | bool Changed = false; |
| 562 | for (BasicBlock *Target : Targets) { |
| 563 | SmallVector<BasicBlock *, 16> OtherPreds; |
| 564 | BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds); |
| 565 | // If we did not found an indirectbr, or the indirectbr is the only |
| 566 | // incoming edge, this isn't the kind of edge we're looking for. |
| 567 | if (!IBRPred || OtherPreds.empty()) |
| 568 | continue; |
| 569 | |
| 570 | // Don't even think about ehpads/landingpads. |
| 571 | Instruction *FirstNonPHI = Target->getFirstNonPHI(); |
| 572 | if (FirstNonPHI->isEHPad() || Target->isLandingPad()) |
| 573 | continue; |
| 574 | |
| 575 | BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split"); |
| 576 | // It's possible Target was its own successor through an indirectbr. |
| 577 | // In this case, the indirectbr now comes from BodyBlock. |
| 578 | if (IBRPred == Target) |
| 579 | IBRPred = BodyBlock; |
| 580 | |
| 581 | // At this point Target only has PHIs, and BodyBlock has the rest of the |
| 582 | // block's body. Create a copy of Target that will be used by the "direct" |
| 583 | // preds. |
| 584 | ValueToValueMapTy VMap; |
| 585 | BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F); |
| 586 | |
Brendon Cahoon | 7769a08 | 2017-04-17 19:11:04 +0000 | [diff] [blame] | 587 | for (BasicBlock *Pred : OtherPreds) { |
| 588 | // If the target is a loop to itself, then the terminator of the split |
| 589 | // block needs to be updated. |
| 590 | if (Pred == Target) |
| 591 | BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc); |
| 592 | else |
| 593 | Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc); |
| 594 | } |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 595 | |
| 596 | // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that |
| 597 | // they are clones, so the number of PHIs are the same. |
| 598 | // (a) Remove the edge coming from IBRPred from the "Direct" PHI |
| 599 | // (b) Leave that as the only edge in the "Indirect" PHI. |
| 600 | // (c) Merge the two in the body block. |
| 601 | BasicBlock::iterator Indirect = Target->begin(), |
| 602 | End = Target->getFirstNonPHI()->getIterator(); |
| 603 | BasicBlock::iterator Direct = DirectSucc->begin(); |
| 604 | BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt(); |
| 605 | |
| 606 | assert(&*End == Target->getTerminator() && |
| 607 | "Block was expected to only contain PHIs"); |
| 608 | |
| 609 | while (Indirect != End) { |
| 610 | PHINode *DirPHI = cast<PHINode>(Direct); |
| 611 | PHINode *IndPHI = cast<PHINode>(Indirect); |
| 612 | |
| 613 | // Now, clean up - the direct block shouldn't get the indirect value, |
| 614 | // and vice versa. |
| 615 | DirPHI->removeIncomingValue(IBRPred); |
| 616 | Direct++; |
| 617 | |
| 618 | // Advance the pointer here, to avoid invalidation issues when the old |
| 619 | // PHI is erased. |
| 620 | Indirect++; |
| 621 | |
| 622 | PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI); |
| 623 | NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred), |
| 624 | IBRPred); |
| 625 | |
| 626 | // Create a PHI in the body block, to merge the direct and indirect |
| 627 | // predecessors. |
| 628 | PHINode *MergePHI = |
| 629 | PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert); |
| 630 | MergePHI->addIncoming(NewIndPHI, Target); |
| 631 | MergePHI->addIncoming(DirPHI, DirectSucc); |
| 632 | |
| 633 | IndPHI->replaceAllUsesWith(MergePHI); |
| 634 | IndPHI->eraseFromParent(); |
| 635 | } |
| 636 | |
| 637 | Changed = true; |
| 638 | } |
| 639 | |
| 640 | return Changed; |
| 641 | } |
| 642 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 643 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 644 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 645 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 646 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 647 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 648 | SmallPtrSet<BasicBlock *, 16> Preheaders; |
| 649 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); |
| 650 | while (!LoopList.empty()) { |
| 651 | Loop *L = LoopList.pop_back_val(); |
| 652 | LoopList.insert(LoopList.end(), L->begin(), L->end()); |
| 653 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 654 | Preheaders.insert(Preheader); |
| 655 | } |
| 656 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 657 | bool MadeChange = false; |
| 658 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 659 | 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] | 660 | BasicBlock *BB = &*I++; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 661 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); |
| 662 | if (!DestBB || |
| 663 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 664 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 665 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 666 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 667 | MadeChange = true; |
| 668 | } |
| 669 | return MadeChange; |
| 670 | } |
| 671 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 672 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, |
| 673 | BasicBlock *DestBB, |
| 674 | bool isPreheader) { |
| 675 | // Do not delete loop preheaders if doing so would create a critical edge. |
| 676 | // Loop preheaders can be good locations to spill registers. If the |
| 677 | // preheader is deleted and we create a critical edge, registers may be |
| 678 | // spilled in the loop body instead. |
| 679 | if (!DisablePreheaderProtect && isPreheader && |
| 680 | !(BB->getSinglePredecessor() && |
| 681 | BB->getSinglePredecessor()->getSingleSuccessor())) |
| 682 | return false; |
| 683 | |
| 684 | // Try to skip merging if the unique predecessor of BB is terminated by a |
| 685 | // switch or indirect branch instruction, and BB is used as an incoming block |
| 686 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to |
| 687 | // add COPY instructions in the predecessor of BB instead of BB (if it is not |
| 688 | // merged). Note that the critical edge created by merging such blocks wont be |
| 689 | // split in MachineSink because the jump table is not analyzable. By keeping |
| 690 | // such empty block (BB), ISel will place COPY instructions in BB, not in the |
| 691 | // predecessor of BB. |
| 692 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 693 | if (!Pred || |
| 694 | !(isa<SwitchInst>(Pred->getTerminator()) || |
| 695 | isa<IndirectBrInst>(Pred->getTerminator()))) |
| 696 | return true; |
| 697 | |
| 698 | if (BB->getTerminator() != BB->getFirstNonPHI()) |
| 699 | return true; |
| 700 | |
| 701 | // We use a simple cost heuristic which determine skipping merging is |
| 702 | // profitable if the cost of skipping merging is less than the cost of |
| 703 | // merging : Cost(skipping merging) < Cost(merging BB), where the |
| 704 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and |
| 705 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). |
| 706 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : |
| 707 | // Freq(Pred) / Freq(BB) > 2. |
| 708 | // Note that if there are multiple empty blocks sharing the same incoming |
| 709 | // value for the PHIs in the DestBB, we consider them together. In such |
| 710 | // case, Cost(merging BB) will be the sum of their frequencies. |
| 711 | |
| 712 | if (!isa<PHINode>(DestBB->begin())) |
| 713 | return true; |
| 714 | |
| 715 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; |
| 716 | |
| 717 | // Find all other incoming blocks from which incoming values of all PHIs in |
| 718 | // DestBB are the same as the ones from BB. |
| 719 | for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; |
| 720 | ++PI) { |
| 721 | BasicBlock *DestBBPred = *PI; |
| 722 | if (DestBBPred == BB) |
| 723 | continue; |
| 724 | |
| 725 | bool HasAllSameValue = true; |
| 726 | BasicBlock::const_iterator DestBBI = DestBB->begin(); |
| 727 | while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) { |
| 728 | if (DestPN->getIncomingValueForBlock(BB) != |
| 729 | DestPN->getIncomingValueForBlock(DestBBPred)) { |
| 730 | HasAllSameValue = false; |
| 731 | break; |
| 732 | } |
| 733 | } |
| 734 | if (HasAllSameValue) |
| 735 | SameIncomingValueBBs.insert(DestBBPred); |
| 736 | } |
| 737 | |
| 738 | // See if all BB's incoming values are same as the value from Pred. In this |
| 739 | // case, no reason to skip merging because COPYs are expected to be place in |
| 740 | // Pred already. |
| 741 | if (SameIncomingValueBBs.count(Pred)) |
| 742 | return true; |
| 743 | |
| 744 | if (!BFI) { |
| 745 | Function &F = *BB->getParent(); |
| 746 | LoopInfo LI{DominatorTree(F)}; |
| 747 | BPI.reset(new BranchProbabilityInfo(F, LI)); |
| 748 | BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); |
| 749 | } |
| 750 | |
| 751 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); |
| 752 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); |
| 753 | |
| 754 | for (auto SameValueBB : SameIncomingValueBBs) |
| 755 | if (SameValueBB->getUniquePredecessor() == Pred && |
| 756 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) |
| 757 | BBFreq += BFI->getBlockFreq(SameValueBB); |
| 758 | |
| 759 | return PredFreq.getFrequency() <= |
| 760 | BBFreq.getFrequency() * FreqRatioToSkipMerge; |
| 761 | } |
| 762 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 763 | /// Return true if we can merge BB into DestBB if there is a single |
| 764 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 765 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 766 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 767 | const BasicBlock *DestBB) const { |
| 768 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 769 | // the successor. If there are more complex condition (e.g. preheaders), |
| 770 | // don't mess around with them. |
| 771 | BasicBlock::const_iterator BBI = BB->begin(); |
| 772 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 773 | for (const User *U : PN->users()) { |
| 774 | const Instruction *UI = cast<Instruction>(U); |
| 775 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 776 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 777 | // If User is inside DestBB block and it is a PHINode then check |
| 778 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 779 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 780 | if (UI->getParent() == DestBB) { |
| 781 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 782 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 783 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 784 | if (Insn && Insn->getParent() == BB && |
| 785 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 786 | return false; |
| 787 | } |
| 788 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 789 | } |
| 790 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 791 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 792 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 793 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 794 | // can't merge the block. |
| 795 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 796 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 797 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 798 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 799 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 800 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 801 | // It is faster to get preds from a PHI than with pred_iterator. |
| 802 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 803 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 804 | } else { |
| 805 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 806 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 807 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 808 | // Walk the preds of DestBB. |
| 809 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 810 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 811 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 812 | BBI = DestBB->begin(); |
| 813 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 814 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 815 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 816 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 817 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 818 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 819 | if (V2PN->getParent() == BB) |
| 820 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 821 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 822 | // If there is a conflict, bail out. |
| 823 | if (V1 != V2) return false; |
| 824 | } |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | return true; |
| 829 | } |
| 830 | |
| 831 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 832 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 833 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 834 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 835 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 836 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 837 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 838 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 839 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 840 | // If the destination block has a single pred, then this is a trivial edge, |
| 841 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 842 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 843 | if (SinglePred != DestBB) { |
| 844 | // Remember if SinglePred was the entry block of the function. If so, we |
| 845 | // will need to move BB back to the entry position. |
| 846 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 847 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 848 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 849 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 850 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 851 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 852 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 853 | return; |
| 854 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 855 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 856 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 857 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 858 | // to handle the new incoming edges it is about to have. |
| 859 | PHINode *PN; |
| 860 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 861 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 862 | // Remove the incoming value for BB, and remember it. |
| 863 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 864 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 865 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 866 | // value that dominates BB. |
| 867 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 868 | if (InValPhi && InValPhi->getParent() == BB) { |
| 869 | // Add all of the input values of the input PHI as inputs of this phi. |
| 870 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 871 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 872 | InValPhi->getIncomingBlock(i)); |
| 873 | } else { |
| 874 | // Otherwise, add one instance of the dominating value for each edge that |
| 875 | // we will be adding. |
| 876 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 877 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 878 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 879 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 880 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 881 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 882 | } |
| 883 | } |
| 884 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 885 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 886 | // The PHIs are now updated, change everything that refers to BB to use |
| 887 | // DestBB and remove BB. |
| 888 | BB->replaceAllUsesWith(DestBB); |
| 889 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 890 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 891 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 892 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 893 | } |
| 894 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 895 | // Computes a map of base pointer relocation instructions to corresponding |
| 896 | // derived pointer relocation instructions given a vector of all relocate calls |
| 897 | static void computeBaseDerivedRelocateMap( |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 898 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, |
| 899 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> |
| 900 | &RelocateInstMap) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 901 | // Collect information in two maps: one primarily for locating the base object |
| 902 | // while filling the second map; the second map is the final structure holding |
| 903 | // a mapping between Base and corresponding Derived relocate calls |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 904 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; |
| 905 | for (auto *ThisRelocate : AllRelocateCalls) { |
| 906 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), |
| 907 | ThisRelocate->getDerivedPtrIndex()); |
| 908 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 909 | } |
| 910 | for (auto &Item : RelocateIdxMap) { |
| 911 | std::pair<unsigned, unsigned> Key = Item.first; |
| 912 | if (Key.first == Key.second) |
| 913 | // Base relocation: nothing to insert |
| 914 | continue; |
| 915 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 916 | GCRelocateInst *I = Item.second; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 917 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 918 | |
| 919 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 920 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 921 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 922 | // TODO: We might want to insert a new base object relocate and gep off |
| 923 | // that, if there are enough derived object relocates. |
| 924 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 925 | |
| 926 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 927 | } |
| 928 | } |
| 929 | |
| 930 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 931 | // small integer constants |
| 932 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 933 | SmallVectorImpl<Value *> &OffsetV) { |
| 934 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 935 | // Only accept small constant integer operands |
| 936 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 937 | if (!Op || Op->getZExtValue() > 20) |
| 938 | return false; |
| 939 | } |
| 940 | |
| 941 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 942 | OffsetV.push_back(GEP->getOperand(i)); |
| 943 | return true; |
| 944 | } |
| 945 | |
| 946 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 947 | // replace, computes a replacement, and affects it. |
| 948 | static bool |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 949 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, |
| 950 | const SmallVectorImpl<GCRelocateInst *> &Targets) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 951 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 952 | for (GCRelocateInst *ToReplace : Targets) { |
| 953 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 954 | "Not relocating a derived object of the original base object"); |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 955 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 956 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 957 | continue; |
| 958 | } |
| 959 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 960 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 961 | // Base and derived relocates are in different basic blocks. |
| 962 | // In this case transform is only valid when base dominates derived |
| 963 | // relocate. However it would be too expensive to check dominance |
| 964 | // for each such relocate, so we skip the whole transformation. |
| 965 | continue; |
| 966 | } |
| 967 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 968 | Value *Base = ToReplace->getBasePtr(); |
| 969 | auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 970 | if (!Derived || Derived->getPointerOperand() != Base) |
| 971 | continue; |
| 972 | |
| 973 | SmallVector<Value *, 2> OffsetV; |
| 974 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 975 | continue; |
| 976 | |
| 977 | // Create a Builder and replace the target callsite with a gep |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 978 | assert(RelocatedBase->getNextNode() && |
| 979 | "Should always have one since it's not a terminator"); |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 980 | |
| 981 | // Insert after RelocatedBase |
| 982 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 983 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 984 | |
| 985 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 986 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 987 | // match, and we should reuse it to get the derived pointer. But it could be |
| 988 | // cases like this: |
| 989 | // bb1: |
| 990 | // ... |
| 991 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 992 | // br label %merge |
| 993 | // |
| 994 | // bb2: |
| 995 | // ... |
| 996 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 997 | // br label %merge |
| 998 | // |
| 999 | // merge: |
| 1000 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 1001 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 1002 | // |
| 1003 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 1004 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 1005 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 1006 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1007 | if (RelocatedBase->getType() != Base->getType()) { |
| 1008 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 1009 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1010 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 1011 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1012 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1013 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1014 | // If the newly generated derived pointer's type does not match the original derived |
| 1015 | // 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] | 1016 | Value *ActualReplacement = Replacement; |
| 1017 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1018 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 1019 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1020 | } |
| 1021 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1022 | ToReplace->eraseFromParent(); |
| 1023 | |
| 1024 | MadeChange = true; |
| 1025 | } |
| 1026 | return MadeChange; |
| 1027 | } |
| 1028 | |
| 1029 | // Turns this: |
| 1030 | // |
| 1031 | // %base = ... |
| 1032 | // %ptr = gep %base + 15 |
| 1033 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 1034 | // %base' = relocate(%tok, i32 4, i32 4) |
| 1035 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 1036 | // %val = load %ptr' |
| 1037 | // |
| 1038 | // into this: |
| 1039 | // |
| 1040 | // %base = ... |
| 1041 | // %ptr = gep %base + 15 |
| 1042 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 1043 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 1044 | // %ptr' = gep %base' + 15 |
| 1045 | // %val = load %ptr' |
| 1046 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 1047 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1048 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1049 | |
| 1050 | for (auto *U : I.users()) |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1051 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1052 | // Collect all the relocate calls associated with a statepoint |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1053 | AllRelocateCalls.push_back(Relocate); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1054 | |
| 1055 | // We need atleast one base pointer relocation + one derived pointer |
| 1056 | // relocation to mangle |
| 1057 | if (AllRelocateCalls.size() < 2) |
| 1058 | return false; |
| 1059 | |
| 1060 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 1061 | // corresponding derived relocate instructions |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1062 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1063 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 1064 | if (RelocateInstMap.empty()) |
| 1065 | return false; |
| 1066 | |
| 1067 | for (auto &Item : RelocateInstMap) |
| 1068 | // Item.first is the RelocatedBase to offset against |
| 1069 | // Item.second is the vector of Targets to replace |
| 1070 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 1071 | return MadeChange; |
| 1072 | } |
| 1073 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1074 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 1075 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1076 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1077 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1078 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1079 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
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 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1082 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1083 | UI != E; ) { |
| 1084 | Use &TheUse = UI.getUse(); |
| 1085 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1086 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1087 | // Figure out which BB this cast is used in. For PHI's this is the |
| 1088 | // appropriate predecessor block. |
| 1089 | BasicBlock *UserBB = User->getParent(); |
| 1090 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1091 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1092 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1093 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1094 | // Preincrement use iterator so we don't invalidate it. |
| 1095 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1096 | |
David Majnemer | 0c80e2e | 2016-04-27 19:36:38 +0000 | [diff] [blame] | 1097 | // The first insertion point of a block containing an EH pad is after the |
| 1098 | // pad. If the pad is the user, we cannot sink the cast past the pad. |
| 1099 | if (User->isEHPad()) |
| 1100 | continue; |
| 1101 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 1102 | // If the block selected to receive the cast is an EH pad that does not |
| 1103 | // allow non-PHI instructions before the terminator, we can't sink the |
| 1104 | // cast. |
| 1105 | if (UserBB->getTerminator()->isEHPad()) |
| 1106 | continue; |
| 1107 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1108 | // If this user is in the same block as the cast, don't change the cast. |
| 1109 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1110 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1111 | // If we have already inserted a cast into this block, use it. |
| 1112 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 1113 | |
| 1114 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1115 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1116 | assert(InsertPt != UserBB->end()); |
| 1117 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 1118 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1119 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1120 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1121 | // 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] | 1122 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1123 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1124 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1125 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1126 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1127 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1128 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1129 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1130 | MadeChange = true; |
| 1131 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1132 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1133 | return MadeChange; |
| 1134 | } |
| 1135 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1136 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 1137 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 1138 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1139 | /// |
| 1140 | /// Return true if any changes are made. |
| 1141 | /// |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1142 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 1143 | const DataLayout &DL) { |
Justin Lebar | 3e50a5b | 2016-11-21 22:49:15 +0000 | [diff] [blame] | 1144 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition |
| 1145 | // than sinking only nop casts, but is helpful on some platforms. |
| 1146 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { |
| 1147 | if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(), |
| 1148 | ASC->getDestAddressSpace())) |
| 1149 | return false; |
| 1150 | } |
| 1151 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1152 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1153 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 1154 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1155 | |
| 1156 | // This is an fp<->int conversion? |
| 1157 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 1158 | return false; |
| 1159 | |
| 1160 | // If this is an extension, it will be a zero or sign extension, which |
| 1161 | // isn't a noop. |
| 1162 | if (SrcVT.bitsLT(DstVT)) return false; |
| 1163 | |
| 1164 | // If these values will be promoted, find out what they will be promoted |
| 1165 | // to. This helps us consider truncates on PPC as noop copies when they |
| 1166 | // are. |
| 1167 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 1168 | TargetLowering::TypePromoteInteger) |
| 1169 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 1170 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 1171 | TargetLowering::TypePromoteInteger) |
| 1172 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 1173 | |
| 1174 | // If, after promotion, these are the same types, this is a noop copy. |
| 1175 | if (SrcVT != DstVT) |
| 1176 | return false; |
| 1177 | |
| 1178 | return SinkCast(CI); |
| 1179 | } |
| 1180 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1181 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 1182 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1183 | /// |
| 1184 | /// Return true if any changes were made. |
| 1185 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 1186 | Value *A, *B; |
| 1187 | Instruction *AddI; |
| 1188 | if (!match(CI, |
| 1189 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 1190 | return false; |
| 1191 | |
| 1192 | Type *Ty = AddI->getType(); |
| 1193 | if (!isa<IntegerType>(Ty)) |
| 1194 | return false; |
| 1195 | |
| 1196 | // We don't want to move around uses of condition values this late, so we we |
| 1197 | // check if it is legal to create the call to the intrinsic in the basic |
| 1198 | // block containing the icmp: |
| 1199 | |
| 1200 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 1201 | return false; |
| 1202 | |
| 1203 | #ifndef NDEBUG |
| 1204 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 1205 | // for now: |
| 1206 | if (AddI->hasOneUse()) |
| 1207 | assert(*AddI->user_begin() == CI && "expected!"); |
| 1208 | #endif |
| 1209 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 1210 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1211 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 1212 | |
| 1213 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 1214 | |
| 1215 | auto *UAddWithOverflow = |
| 1216 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 1217 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 1218 | auto *Overflow = |
| 1219 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 1220 | |
| 1221 | CI->replaceAllUsesWith(Overflow); |
| 1222 | AddI->replaceAllUsesWith(UAdd); |
| 1223 | CI->eraseFromParent(); |
| 1224 | AddI->eraseFromParent(); |
| 1225 | return true; |
| 1226 | } |
| 1227 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1228 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 1229 | /// registers that must be created and coalesced. This is a clear win except on |
| 1230 | /// targets with multiple condition code registers (PowerPC), where it might |
| 1231 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1232 | /// |
| 1233 | /// Return true if any changes are made. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1234 | static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1235 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1236 | |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1237 | // 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] | 1238 | if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI)) |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1239 | return false; |
| 1240 | |
| 1241 | // Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1242 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1243 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1244 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1245 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1246 | UI != E; ) { |
| 1247 | Use &TheUse = UI.getUse(); |
| 1248 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1249 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1250 | // Preincrement use iterator so we don't invalidate it. |
| 1251 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1252 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1253 | // Don't bother for PHI nodes. |
| 1254 | if (isa<PHINode>(User)) |
| 1255 | continue; |
| 1256 | |
| 1257 | // Figure out which BB this cmp is used in. |
| 1258 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1259 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1260 | // If this user is in the same block as the cmp, don't change the cmp. |
| 1261 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1262 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1263 | // If we have already inserted a cmp into this block, use it. |
| 1264 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 1265 | |
| 1266 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1267 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1268 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1269 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1270 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 1271 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Wolfgang Pieb | e51bede | 2016-10-06 21:43:45 +0000 | [diff] [blame] | 1272 | // Propagate the debug info. |
| 1273 | InsertedCmp->setDebugLoc(CI->getDebugLoc()); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1274 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1275 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1276 | // Replace a use of the cmp with a use of the new cmp. |
| 1277 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1278 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1279 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1280 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1281 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1282 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1283 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1284 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1285 | MadeChange = true; |
| 1286 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1287 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1288 | return MadeChange; |
| 1289 | } |
| 1290 | |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 1291 | static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1292 | if (SinkCmpExpression(CI, TLI)) |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1293 | return true; |
| 1294 | |
| 1295 | if (CombineUAddWithOverflow(CI)) |
| 1296 | return true; |
| 1297 | |
| 1298 | return false; |
| 1299 | } |
| 1300 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1301 | /// Duplicate and sink the given 'and' instruction into user blocks where it is |
| 1302 | /// used in a compare to allow isel to generate better code for targets where |
| 1303 | /// this operation can be combined. |
| 1304 | /// |
| 1305 | /// Return true if any changes are made. |
| 1306 | static bool sinkAndCmp0Expression(Instruction *AndI, |
| 1307 | const TargetLowering &TLI, |
| 1308 | SetOfInstrs &InsertedInsts) { |
| 1309 | // Double-check that we're not trying to optimize an instruction that was |
| 1310 | // already optimized by some other part of this pass. |
| 1311 | assert(!InsertedInsts.count(AndI) && |
| 1312 | "Attempting to optimize already optimized and instruction"); |
| 1313 | (void) InsertedInsts; |
| 1314 | |
| 1315 | // Nothing to do for single use in same basic block. |
| 1316 | if (AndI->hasOneUse() && |
| 1317 | AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) |
| 1318 | return false; |
| 1319 | |
| 1320 | // Try to avoid cases where sinking/duplicating is likely to increase register |
| 1321 | // pressure. |
| 1322 | if (!isa<ConstantInt>(AndI->getOperand(0)) && |
| 1323 | !isa<ConstantInt>(AndI->getOperand(1)) && |
| 1324 | AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) |
| 1325 | return false; |
| 1326 | |
| 1327 | for (auto *U : AndI->users()) { |
| 1328 | Instruction *User = cast<Instruction>(U); |
| 1329 | |
| 1330 | // Only sink for and mask feeding icmp with 0. |
| 1331 | if (!isa<ICmpInst>(User)) |
| 1332 | return false; |
| 1333 | |
| 1334 | auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); |
| 1335 | if (!CmpC || !CmpC->isZero()) |
| 1336 | return false; |
| 1337 | } |
| 1338 | |
| 1339 | if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) |
| 1340 | return false; |
| 1341 | |
| 1342 | DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n"); |
| 1343 | DEBUG(AndI->getParent()->dump()); |
| 1344 | |
| 1345 | // Push the 'and' into the same block as the icmp 0. There should only be |
| 1346 | // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any |
| 1347 | // others, so we don't need to keep track of which BBs we insert into. |
| 1348 | for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); |
| 1349 | UI != E; ) { |
| 1350 | Use &TheUse = UI.getUse(); |
| 1351 | Instruction *User = cast<Instruction>(*UI); |
| 1352 | |
| 1353 | // Preincrement use iterator so we don't invalidate it. |
| 1354 | ++UI; |
| 1355 | |
| 1356 | DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n"); |
| 1357 | |
| 1358 | // Keep the 'and' in the same place if the use is already in the same block. |
| 1359 | Instruction *InsertPt = |
| 1360 | User->getParent() == AndI->getParent() ? AndI : User; |
| 1361 | Instruction *InsertedAnd = |
| 1362 | BinaryOperator::Create(Instruction::And, AndI->getOperand(0), |
| 1363 | AndI->getOperand(1), "", InsertPt); |
| 1364 | // Propagate the debug info. |
| 1365 | InsertedAnd->setDebugLoc(AndI->getDebugLoc()); |
| 1366 | |
| 1367 | // Replace a use of the 'and' with a use of the new 'and'. |
| 1368 | TheUse = InsertedAnd; |
| 1369 | ++NumAndUses; |
| 1370 | DEBUG(User->getParent()->dump()); |
| 1371 | } |
| 1372 | |
| 1373 | // We removed all uses, nuke the and. |
| 1374 | AndI->eraseFromParent(); |
| 1375 | return true; |
| 1376 | } |
| 1377 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1378 | /// Check if the candidates could be combined with a shift instruction, which |
| 1379 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1380 | /// 1. Truncate instruction |
| 1381 | /// 2. And instruction and the imm is a mask of the low bits: |
| 1382 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 1383 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1384 | if (!isa<TruncInst>(User)) { |
| 1385 | if (User->getOpcode() != Instruction::And || |
| 1386 | !isa<ConstantInt>(User->getOperand(1))) |
| 1387 | return false; |
| 1388 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1389 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1390 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1391 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1392 | return false; |
| 1393 | } |
| 1394 | return true; |
| 1395 | } |
| 1396 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1397 | /// 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] | 1398 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1399 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 1400 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1401 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1402 | BasicBlock *UserBB = User->getParent(); |
| 1403 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 1404 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 1405 | bool MadeChange = false; |
| 1406 | |
| 1407 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 1408 | TruncE = TruncI->user_end(); |
| 1409 | TruncUI != TruncE;) { |
| 1410 | |
| 1411 | Use &TruncTheUse = TruncUI.getUse(); |
| 1412 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 1413 | // Preincrement use iterator so we don't invalidate it. |
| 1414 | |
| 1415 | ++TruncUI; |
| 1416 | |
| 1417 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 1418 | if (!ISDOpcode) |
| 1419 | continue; |
| 1420 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 1421 | // If the use is actually a legal node, there will not be an |
| 1422 | // implicit truncate. |
| 1423 | // FIXME: always querying the result type is just an |
| 1424 | // approximation; some nodes' legality is determined by the |
| 1425 | // 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] | 1426 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1427 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1428 | continue; |
| 1429 | |
| 1430 | // Don't bother for PHI nodes. |
| 1431 | if (isa<PHINode>(TruncUser)) |
| 1432 | continue; |
| 1433 | |
| 1434 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 1435 | |
| 1436 | if (UserBB == TruncUserBB) |
| 1437 | continue; |
| 1438 | |
| 1439 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 1440 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 1441 | |
| 1442 | if (!InsertedShift && !InsertedTrunc) { |
| 1443 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1444 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1445 | // Sink the shift |
| 1446 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1447 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1448 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1449 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1450 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1451 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1452 | |
| 1453 | // Sink the trunc |
| 1454 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 1455 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1456 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1457 | |
| 1458 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1459 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1460 | |
| 1461 | MadeChange = true; |
| 1462 | |
| 1463 | TruncTheUse = InsertedTrunc; |
| 1464 | } |
| 1465 | } |
| 1466 | return MadeChange; |
| 1467 | } |
| 1468 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1469 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1470 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1471 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1472 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1473 | /// BB1: |
| 1474 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1475 | /// BB2: |
| 1476 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1477 | /// ==> |
| 1478 | /// |
| 1479 | /// BB2: |
| 1480 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1481 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1482 | /// |
| 1483 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1484 | /// instruction. |
| 1485 | /// Return true if any changes are made. |
| 1486 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1487 | const TargetLowering &TLI, |
| 1488 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1489 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1490 | |
| 1491 | /// Only insert instructions in each block once. |
| 1492 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1493 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1494 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1495 | |
| 1496 | bool MadeChange = false; |
| 1497 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1498 | UI != E;) { |
| 1499 | Use &TheUse = UI.getUse(); |
| 1500 | Instruction *User = cast<Instruction>(*UI); |
| 1501 | // Preincrement use iterator so we don't invalidate it. |
| 1502 | ++UI; |
| 1503 | |
| 1504 | // Don't bother for PHI nodes. |
| 1505 | if (isa<PHINode>(User)) |
| 1506 | continue; |
| 1507 | |
| 1508 | if (!isExtractBitsCandidateUse(User)) |
| 1509 | continue; |
| 1510 | |
| 1511 | BasicBlock *UserBB = User->getParent(); |
| 1512 | |
| 1513 | if (UserBB == DefBB) { |
| 1514 | // If the shift and truncate instruction are in the same BB. The use of |
| 1515 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1516 | // legal. In this case, we would like to sink both shift and truncate |
| 1517 | // instruction to the BB of TruncUse. |
| 1518 | // for example: |
| 1519 | // BB1: |
| 1520 | // i64 shift.result = lshr i64 opnd, imm |
| 1521 | // trunc.result = trunc shift.result to i16 |
| 1522 | // |
| 1523 | // BB2: |
| 1524 | // ----> We will have an implicit truncate here if the architecture does |
| 1525 | // not have i16 compare. |
| 1526 | // cmp i16 trunc.result, opnd2 |
| 1527 | // |
| 1528 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1529 | // If the type of the truncate is legal, no trucate will be |
| 1530 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1531 | && |
| 1532 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1533 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1534 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1535 | |
| 1536 | continue; |
| 1537 | } |
| 1538 | // If we have already inserted a shift into this block, use it. |
| 1539 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1540 | |
| 1541 | if (!InsertedShift) { |
| 1542 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1543 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1544 | |
| 1545 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1546 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1547 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1548 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1549 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1550 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1551 | |
| 1552 | MadeChange = true; |
| 1553 | } |
| 1554 | |
| 1555 | // Replace a use of the shift with a use of the new shift. |
| 1556 | TheUse = InsertedShift; |
| 1557 | } |
| 1558 | |
| 1559 | // If we removed all uses, nuke the shift. |
| 1560 | if (ShiftI->use_empty()) |
| 1561 | ShiftI->eraseFromParent(); |
| 1562 | |
| 1563 | return MadeChange; |
| 1564 | } |
| 1565 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1566 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 1567 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 1568 | /// |
| 1569 | /// We want to transform: |
| 1570 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 1571 | /// |
| 1572 | /// into: |
| 1573 | /// entry: |
| 1574 | /// %cmpz = icmp eq i64 %A, 0 |
| 1575 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 1576 | /// cond.false: |
| 1577 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 1578 | /// br label %cond.end |
| 1579 | /// cond.end: |
| 1580 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 1581 | /// |
| 1582 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 1583 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 1584 | const TargetLowering *TLI, |
| 1585 | const DataLayout *DL, |
| 1586 | bool &ModifiedDT) { |
| 1587 | if (!TLI || !DL) |
| 1588 | return false; |
| 1589 | |
| 1590 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 1591 | if (match(CountZeros->getOperand(1), m_One())) |
| 1592 | return false; |
| 1593 | |
| 1594 | // If it's cheap to speculate, there's nothing to do. |
| 1595 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 1596 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 1597 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 1598 | return false; |
| 1599 | |
| 1600 | // Only handle legal scalar cases. Anything else requires too much work. |
| 1601 | Type *Ty = CountZeros->getType(); |
| 1602 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 1603 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1604 | return false; |
| 1605 | |
| 1606 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 1607 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 1608 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 1609 | |
| 1610 | // Create another block after the count zero intrinsic. A PHI will be added |
| 1611 | // in this block to select the result of the intrinsic or the bit-width |
| 1612 | // constant if the input to the intrinsic is zero. |
| 1613 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 1614 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 1615 | |
| 1616 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 1617 | IRBuilder<> Builder(CountZeros->getContext()); |
| 1618 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 1619 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 1620 | |
| 1621 | // Replace the unconditional branch that was created by the first split with |
| 1622 | // a compare against zero and a conditional branch. |
| 1623 | Value *Zero = Constant::getNullValue(Ty); |
| 1624 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 1625 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 1626 | StartBlock->getTerminator()->eraseFromParent(); |
| 1627 | |
| 1628 | // Create a PHI in the end block to select either the output of the intrinsic |
| 1629 | // or the bit width of the operand. |
| 1630 | Builder.SetInsertPoint(&EndBlock->front()); |
| 1631 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 1632 | CountZeros->replaceAllUsesWith(PN); |
| 1633 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 1634 | PN->addIncoming(BitWidth, StartBlock); |
| 1635 | PN->addIncoming(CountZeros, CallBlock); |
| 1636 | |
| 1637 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 1638 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 1639 | // intrinsic; we only despeculate when a zero input is defined. |
| 1640 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 1641 | ModifiedDT = true; |
| 1642 | return true; |
| 1643 | } |
| 1644 | |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 1645 | // This class provides helper functions to expand a memcmp library call into an |
| 1646 | // inline expansion. |
| 1647 | class MemCmpExpansion { |
| 1648 | struct ResultBlock { |
| 1649 | BasicBlock *BB; |
| 1650 | PHINode *PhiSrc1; |
| 1651 | PHINode *PhiSrc2; |
| 1652 | ResultBlock(); |
| 1653 | }; |
| 1654 | |
| 1655 | CallInst *CI; |
| 1656 | ResultBlock ResBlock; |
| 1657 | unsigned MaxLoadSize; |
| 1658 | unsigned NumBlocks; |
| 1659 | unsigned NumBlocksNonOneByte; |
| 1660 | unsigned NumLoadsPerBlock; |
| 1661 | std::vector<BasicBlock *> LoadCmpBlocks; |
| 1662 | BasicBlock *EndBlock; |
| 1663 | PHINode *PhiRes; |
| 1664 | bool IsUsedForZeroCmp; |
| 1665 | int calculateNumBlocks(unsigned Size); |
| 1666 | void createLoadCmpBlocks(); |
| 1667 | void createResultBlock(); |
| 1668 | void setupResultBlockPHINodes(); |
| 1669 | void setupEndBlockPHINodes(); |
| 1670 | void emitLoadCompareBlock(unsigned Index, int LoadSize, int GEPIndex, |
| 1671 | bool IsLittleEndian); |
| 1672 | void emitLoadCompareBlockMultipleLoads(unsigned Index, unsigned Size, |
| 1673 | unsigned &NumBytesProcessed); |
| 1674 | void emitLoadCompareByteBlock(unsigned Index, int GEPIndex); |
| 1675 | void emitMemCmpResultBlock(bool IsLittleEndian); |
| 1676 | Value *getMemCmpExpansionZeroCase(unsigned Size, bool IsLittleEndian); |
| 1677 | unsigned getLoadSize(unsigned Size); |
| 1678 | unsigned getNumLoads(unsigned Size); |
| 1679 | |
| 1680 | public: |
| 1681 | MemCmpExpansion(CallInst *CI, unsigned MaxLoadSize, |
| 1682 | unsigned NumLoadsPerBlock); |
| 1683 | Value *getMemCmpExpansion(bool IsLittleEndian); |
| 1684 | }; |
| 1685 | |
| 1686 | MemCmpExpansion::ResultBlock::ResultBlock() |
| 1687 | : BB(nullptr), PhiSrc1(nullptr), PhiSrc2(nullptr) {} |
| 1688 | |
| 1689 | // Initialize the basic block structure required for expansion of memcmp call |
| 1690 | // with given maximum load size and memcmp size parameter. |
| 1691 | // This structure includes: |
| 1692 | // 1. A list of load compare blocks - LoadCmpBlocks. |
| 1693 | // 2. An EndBlock, split from original instruction point, which is the block to |
| 1694 | // return from. |
| 1695 | // 3. ResultBlock, block to branch to for early exit when a |
| 1696 | // LoadCmpBlock finds a difference. |
| 1697 | MemCmpExpansion::MemCmpExpansion(CallInst *CI, unsigned MaxLoadSize, |
| 1698 | unsigned NumLoadsPerBlock) |
| 1699 | : CI(CI), MaxLoadSize(MaxLoadSize), NumLoadsPerBlock(NumLoadsPerBlock) { |
| 1700 | |
| 1701 | IRBuilder<> Builder(CI->getContext()); |
| 1702 | |
| 1703 | BasicBlock *StartBlock = CI->getParent(); |
| 1704 | EndBlock = StartBlock->splitBasicBlock(CI, "endblock"); |
| 1705 | setupEndBlockPHINodes(); |
| 1706 | IsUsedForZeroCmp = isOnlyUsedInZeroEqualityComparison(CI); |
| 1707 | |
| 1708 | ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2)); |
| 1709 | uint64_t Size = SizeCast->getZExtValue(); |
| 1710 | |
| 1711 | // Calculate how many load compare blocks are required for an expansion of |
| 1712 | // given Size. |
| 1713 | NumBlocks = calculateNumBlocks(Size); |
| 1714 | createResultBlock(); |
| 1715 | |
| 1716 | // If return value of memcmp is not used in a zero equality, we need to |
| 1717 | // calculate which source was larger. The calculation requires the |
| 1718 | // two loaded source values of each load compare block. |
| 1719 | // These will be saved in the phi nodes created by setupResultBlockPHINodes. |
| 1720 | if (!IsUsedForZeroCmp) |
| 1721 | setupResultBlockPHINodes(); |
| 1722 | |
| 1723 | // Create the number of required load compare basic blocks. |
| 1724 | createLoadCmpBlocks(); |
| 1725 | |
| 1726 | // Update the terminator added by splitBasicBlock to branch to the first |
| 1727 | // LoadCmpBlock. |
| 1728 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1729 | StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]); |
| 1730 | } |
| 1731 | |
| 1732 | void MemCmpExpansion::createLoadCmpBlocks() { |
| 1733 | for (unsigned i = 0; i < NumBlocks; i++) { |
| 1734 | BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb", |
| 1735 | EndBlock->getParent(), EndBlock); |
| 1736 | LoadCmpBlocks.push_back(BB); |
| 1737 | } |
| 1738 | } |
| 1739 | |
| 1740 | void MemCmpExpansion::createResultBlock() { |
| 1741 | ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block", |
| 1742 | EndBlock->getParent(), EndBlock); |
| 1743 | } |
| 1744 | |
| 1745 | // This function creates the IR instructions for loading and comparing 1 byte. |
| 1746 | // It loads 1 byte from each source of the memcmp paramters with the given |
| 1747 | // GEPIndex. It then subtracts the two loaded values and adds this result to the |
| 1748 | // final phi node for selecting the memcmp result. |
| 1749 | void MemCmpExpansion::emitLoadCompareByteBlock(unsigned Index, int GEPIndex) { |
| 1750 | IRBuilder<> Builder(CI->getContext()); |
| 1751 | |
| 1752 | Value *Source1 = CI->getArgOperand(0); |
| 1753 | Value *Source2 = CI->getArgOperand(1); |
| 1754 | |
| 1755 | Builder.SetInsertPoint(LoadCmpBlocks[Index]); |
| 1756 | Type *LoadSizeType = Type::getInt8Ty(CI->getContext()); |
| 1757 | // Cast source to LoadSizeType* |
| 1758 | if (Source1->getType() != LoadSizeType) |
| 1759 | Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo()); |
| 1760 | if (Source2->getType() != LoadSizeType) |
| 1761 | Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo()); |
| 1762 | |
| 1763 | // Get the base address using the GEPIndex |
| 1764 | if (GEPIndex != 0) { |
| 1765 | Source1 = Builder.CreateGEP(LoadSizeType, Source1, |
| 1766 | ConstantInt::get(LoadSizeType, GEPIndex)); |
| 1767 | Source2 = Builder.CreateGEP(LoadSizeType, Source2, |
| 1768 | ConstantInt::get(LoadSizeType, GEPIndex)); |
| 1769 | } |
| 1770 | |
| 1771 | Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1); |
| 1772 | Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2); |
| 1773 | |
| 1774 | LoadSrc1 = Builder.CreateZExt(LoadSrc1, Type::getInt32Ty(CI->getContext())); |
| 1775 | LoadSrc2 = Builder.CreateZExt(LoadSrc2, Type::getInt32Ty(CI->getContext())); |
| 1776 | Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2); |
| 1777 | |
| 1778 | PhiRes->addIncoming(Diff, LoadCmpBlocks[Index]); |
| 1779 | |
| 1780 | if (Index < (LoadCmpBlocks.size() - 1)) { |
| 1781 | // Early exit branch if difference found to EndBlock, otherwise continue to |
| 1782 | // next LoadCmpBlock |
| 1783 | |
| 1784 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff, |
| 1785 | ConstantInt::get(Diff->getType(), 0)); |
| 1786 | BranchInst *CmpBr = |
| 1787 | BranchInst::Create(EndBlock, LoadCmpBlocks[Index + 1], Cmp); |
| 1788 | Builder.Insert(CmpBr); |
| 1789 | } else { |
| 1790 | // The last block has an unconditional branch to EndBlock |
| 1791 | BranchInst *CmpBr = BranchInst::Create(EndBlock); |
| 1792 | Builder.Insert(CmpBr); |
| 1793 | } |
| 1794 | } |
| 1795 | |
| 1796 | unsigned MemCmpExpansion::getNumLoads(unsigned Size) { |
| 1797 | return (Size / MaxLoadSize) + countPopulation(Size % MaxLoadSize); |
| 1798 | } |
| 1799 | |
| 1800 | unsigned MemCmpExpansion::getLoadSize(unsigned Size) { |
| 1801 | return MinAlign(PowerOf2Floor(Size), MaxLoadSize); |
| 1802 | } |
| 1803 | |
| 1804 | void MemCmpExpansion::emitLoadCompareBlockMultipleLoads( |
| 1805 | unsigned Index, unsigned Size, unsigned &NumBytesProcessed) { |
| 1806 | |
| 1807 | IRBuilder<> Builder(CI->getContext()); |
| 1808 | |
| 1809 | std::vector<Value *> XorList, OrList; |
| 1810 | Value *Diff; |
| 1811 | |
| 1812 | unsigned RemainingBytes = Size - NumBytesProcessed; |
| 1813 | unsigned NumLoadsRemaining = getNumLoads(RemainingBytes); |
| 1814 | unsigned NumLoads = std::min(NumLoadsRemaining, NumLoadsPerBlock); |
| 1815 | |
| 1816 | Builder.SetInsertPoint(LoadCmpBlocks[Index]); |
| 1817 | |
| 1818 | for (unsigned i = 0; i < NumLoads; ++i) { |
| 1819 | unsigned LoadSize = getLoadSize(RemainingBytes); |
| 1820 | unsigned GEPIndex = NumBytesProcessed / LoadSize; |
| 1821 | NumBytesProcessed += LoadSize; |
| 1822 | RemainingBytes -= LoadSize; |
| 1823 | |
| 1824 | Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8); |
| 1825 | Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8); |
| 1826 | |
| 1827 | Value *Source1 = CI->getArgOperand(0); |
| 1828 | Value *Source2 = CI->getArgOperand(1); |
| 1829 | |
| 1830 | // Cast source to LoadSizeType* |
| 1831 | if (Source1->getType() != LoadSizeType) |
| 1832 | Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo()); |
| 1833 | if (Source2->getType() != LoadSizeType) |
| 1834 | Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo()); |
| 1835 | |
| 1836 | // Get the base address using the GEPIndex |
| 1837 | if (GEPIndex != 0) { |
| 1838 | Source1 = Builder.CreateGEP(LoadSizeType, Source1, |
| 1839 | ConstantInt::get(LoadSizeType, GEPIndex)); |
| 1840 | Source2 = Builder.CreateGEP(LoadSizeType, Source2, |
| 1841 | ConstantInt::get(LoadSizeType, GEPIndex)); |
| 1842 | } |
| 1843 | |
| 1844 | // Load LoadSizeType from the base address |
| 1845 | Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1); |
| 1846 | Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2); |
| 1847 | if (LoadSizeType != MaxLoadType) { |
| 1848 | LoadSrc1 = Builder.CreateZExtOrTrunc(LoadSrc1, MaxLoadType); |
| 1849 | LoadSrc2 = Builder.CreateZExtOrTrunc(LoadSrc2, MaxLoadType); |
| 1850 | } |
| 1851 | Diff = Builder.CreateXor(LoadSrc1, LoadSrc2); |
| 1852 | Diff = Builder.CreateZExtOrTrunc(Diff, MaxLoadType); |
| 1853 | XorList.push_back(Diff); |
| 1854 | } |
| 1855 | |
| 1856 | auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> { |
| 1857 | std::vector<Value *> OutList; |
| 1858 | for (unsigned i = 0; i < InList.size() - 1; i = i + 2) { |
| 1859 | Value *Or = Builder.CreateOr(InList[i], InList[i + 1]); |
| 1860 | OutList.push_back(Or); |
| 1861 | } |
| 1862 | if (InList.size() % 2 != 0) |
| 1863 | OutList.push_back(InList.back()); |
| 1864 | return OutList; |
| 1865 | }; |
| 1866 | |
| 1867 | // Pair wise OR the XOR results |
| 1868 | OrList = pairWiseOr(XorList); |
| 1869 | |
| 1870 | // Pair wise OR the OR results until one result left |
| 1871 | while (OrList.size() != 1) { |
| 1872 | OrList = pairWiseOr(OrList); |
| 1873 | } |
| 1874 | |
| 1875 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, OrList[0], |
| 1876 | ConstantInt::get(Diff->getType(), 0)); |
| 1877 | BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1)) |
| 1878 | ? EndBlock |
| 1879 | : LoadCmpBlocks[Index + 1]; |
| 1880 | // Early exit branch if difference found to ResultBlock, otherwise continue to |
| 1881 | // next LoadCmpBlock or EndBlock. |
| 1882 | BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp); |
| 1883 | Builder.Insert(CmpBr); |
| 1884 | |
| 1885 | // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0 |
| 1886 | // since early exit to ResultBlock was not taken (no difference was found in |
| 1887 | // any of the bytes) |
| 1888 | if (Index == LoadCmpBlocks.size() - 1) { |
| 1889 | Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0); |
| 1890 | PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]); |
| 1891 | } |
| 1892 | } |
| 1893 | |
| 1894 | // This function creates the IR intructions for loading and comparing using the |
| 1895 | // given LoadSize. It loads the number of bytes specified by LoadSize from each |
| 1896 | // source of the memcmp parameters. It then does a subtract to see if there was |
| 1897 | // a difference in the loaded values. If a difference is found, it branches |
| 1898 | // with an early exit to the ResultBlock for calculating which source was |
| 1899 | // larger. Otherwise, it falls through to the either the next LoadCmpBlock or |
| 1900 | // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with |
| 1901 | // a special case through emitLoadCompareByteBlock. The special handling can |
| 1902 | // simply subtract the loaded values and add it to the result phi node. |
| 1903 | void MemCmpExpansion::emitLoadCompareBlock(unsigned Index, int LoadSize, |
| 1904 | int GEPIndex, bool IsLittleEndian) { |
| 1905 | if (LoadSize == 1) { |
| 1906 | MemCmpExpansion::emitLoadCompareByteBlock(Index, GEPIndex); |
| 1907 | return; |
| 1908 | } |
| 1909 | |
| 1910 | IRBuilder<> Builder(CI->getContext()); |
| 1911 | |
| 1912 | Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8); |
| 1913 | Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8); |
| 1914 | |
| 1915 | Value *Source1 = CI->getArgOperand(0); |
| 1916 | Value *Source2 = CI->getArgOperand(1); |
| 1917 | |
| 1918 | Builder.SetInsertPoint(LoadCmpBlocks[Index]); |
| 1919 | // Cast source to LoadSizeType* |
| 1920 | if (Source1->getType() != LoadSizeType) |
| 1921 | Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo()); |
| 1922 | if (Source2->getType() != LoadSizeType) |
| 1923 | Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo()); |
| 1924 | |
| 1925 | // Get the base address using the GEPIndex |
| 1926 | if (GEPIndex != 0) { |
| 1927 | Source1 = Builder.CreateGEP(LoadSizeType, Source1, |
| 1928 | ConstantInt::get(LoadSizeType, GEPIndex)); |
| 1929 | Source2 = Builder.CreateGEP(LoadSizeType, Source2, |
| 1930 | ConstantInt::get(LoadSizeType, GEPIndex)); |
| 1931 | } |
| 1932 | |
| 1933 | // Load LoadSizeType from the base address |
| 1934 | Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1); |
| 1935 | Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2); |
| 1936 | |
| 1937 | if (IsLittleEndian) { |
| 1938 | Function *F = LoadCmpBlocks[Index]->getParent(); |
| 1939 | |
| 1940 | Function *Bswap = Intrinsic::getDeclaration(F->getParent(), |
| 1941 | Intrinsic::bswap, LoadSizeType); |
| 1942 | LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1); |
| 1943 | LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2); |
| 1944 | } |
| 1945 | |
| 1946 | if (LoadSizeType != MaxLoadType) { |
| 1947 | LoadSrc1 = Builder.CreateZExtOrTrunc(LoadSrc1, MaxLoadType); |
| 1948 | LoadSrc2 = Builder.CreateZExtOrTrunc(LoadSrc2, MaxLoadType); |
| 1949 | } |
| 1950 | |
| 1951 | // Add the loaded values to the phi nodes for calculating memcmp result only |
| 1952 | // if result is not used in a zero equality. |
| 1953 | if (!IsUsedForZeroCmp) { |
| 1954 | ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[Index]); |
| 1955 | ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[Index]); |
| 1956 | } |
| 1957 | |
| 1958 | Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2); |
| 1959 | |
| 1960 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff, |
| 1961 | ConstantInt::get(Diff->getType(), 0)); |
| 1962 | BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1)) |
| 1963 | ? EndBlock |
| 1964 | : LoadCmpBlocks[Index + 1]; |
| 1965 | // Early exit branch if difference found to ResultBlock, otherwise continue to |
| 1966 | // next LoadCmpBlock or EndBlock. |
| 1967 | BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp); |
| 1968 | Builder.Insert(CmpBr); |
| 1969 | |
| 1970 | // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0 |
| 1971 | // since early exit to ResultBlock was not taken (no difference was found in |
| 1972 | // any of the bytes) |
| 1973 | if (Index == LoadCmpBlocks.size() - 1) { |
| 1974 | Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0); |
| 1975 | PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]); |
| 1976 | } |
| 1977 | } |
| 1978 | |
| 1979 | // This function populates the ResultBlock with a sequence to calculate the |
| 1980 | // memcmp result. It compares the two loaded source values and returns -1 if |
| 1981 | // src1 < src2 and 1 if src1 > src2. |
| 1982 | void MemCmpExpansion::emitMemCmpResultBlock(bool IsLittleEndian) { |
| 1983 | IRBuilder<> Builder(CI->getContext()); |
| 1984 | |
| 1985 | // Special case: if memcmp result is used in a zero equality, result does not |
| 1986 | // need to be calculated and can simply return 1. |
| 1987 | if (IsUsedForZeroCmp) { |
| 1988 | BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt(); |
| 1989 | Builder.SetInsertPoint(ResBlock.BB, InsertPt); |
| 1990 | Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1); |
| 1991 | PhiRes->addIncoming(Res, ResBlock.BB); |
| 1992 | BranchInst *NewBr = BranchInst::Create(EndBlock); |
| 1993 | Builder.Insert(NewBr); |
| 1994 | return; |
| 1995 | } |
| 1996 | BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt(); |
| 1997 | Builder.SetInsertPoint(ResBlock.BB, InsertPt); |
| 1998 | |
| 1999 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1, |
| 2000 | ResBlock.PhiSrc2); |
| 2001 | |
| 2002 | Value *Res = |
| 2003 | Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1), |
| 2004 | ConstantInt::get(Builder.getInt32Ty(), 1)); |
| 2005 | |
| 2006 | BranchInst *NewBr = BranchInst::Create(EndBlock); |
| 2007 | Builder.Insert(NewBr); |
| 2008 | PhiRes->addIncoming(Res, ResBlock.BB); |
| 2009 | } |
| 2010 | |
| 2011 | int MemCmpExpansion::calculateNumBlocks(unsigned Size) { |
| 2012 | int NumBlocks = 0; |
| 2013 | bool haveOneByteLoad = false; |
| 2014 | unsigned RemainingSize = Size; |
| 2015 | unsigned LoadSize = MaxLoadSize; |
| 2016 | while (RemainingSize) { |
| 2017 | if (LoadSize == 1) |
| 2018 | haveOneByteLoad = true; |
| 2019 | NumBlocks += RemainingSize / LoadSize; |
| 2020 | RemainingSize = RemainingSize % LoadSize; |
| 2021 | LoadSize = LoadSize / 2; |
| 2022 | } |
| 2023 | NumBlocksNonOneByte = haveOneByteLoad ? (NumBlocks - 1) : NumBlocks; |
| 2024 | |
| 2025 | if (IsUsedForZeroCmp) |
| 2026 | NumBlocks = NumBlocks / NumLoadsPerBlock + |
| 2027 | (NumBlocks % NumLoadsPerBlock != 0 ? 1 : 0); |
| 2028 | |
| 2029 | return NumBlocks; |
| 2030 | } |
| 2031 | |
| 2032 | void MemCmpExpansion::setupResultBlockPHINodes() { |
| 2033 | IRBuilder<> Builder(CI->getContext()); |
| 2034 | Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8); |
| 2035 | Builder.SetInsertPoint(ResBlock.BB); |
| 2036 | ResBlock.PhiSrc1 = |
| 2037 | Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src1"); |
| 2038 | ResBlock.PhiSrc2 = |
| 2039 | Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src2"); |
| 2040 | } |
| 2041 | |
| 2042 | void MemCmpExpansion::setupEndBlockPHINodes() { |
| 2043 | IRBuilder<> Builder(CI->getContext()); |
| 2044 | |
| 2045 | Builder.SetInsertPoint(&EndBlock->front()); |
| 2046 | PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res"); |
| 2047 | } |
| 2048 | |
| 2049 | Value *MemCmpExpansion::getMemCmpExpansionZeroCase(unsigned Size, |
| 2050 | bool IsLittleEndian) { |
| 2051 | unsigned NumBytesProcessed = 0; |
| 2052 | // This loop populates each of the LoadCmpBlocks with IR sequence to handle |
| 2053 | // multiple loads per block |
| 2054 | for (unsigned i = 0; i < NumBlocks; ++i) { |
| 2055 | emitLoadCompareBlockMultipleLoads(i, Size, NumBytesProcessed); |
| 2056 | } |
| 2057 | |
| 2058 | emitMemCmpResultBlock(IsLittleEndian); |
| 2059 | return PhiRes; |
| 2060 | } |
| 2061 | |
| 2062 | // This function expands the memcmp call into an inline expansion and returns |
| 2063 | // the memcmp result. |
| 2064 | Value *MemCmpExpansion::getMemCmpExpansion(bool IsLittleEndian) { |
| 2065 | |
| 2066 | ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2)); |
| 2067 | uint64_t Size = SizeCast->getZExtValue(); |
| 2068 | |
| 2069 | int LoadSize = MaxLoadSize; |
| 2070 | int NumBytesToBeProcessed = Size; |
| 2071 | |
| 2072 | if (IsUsedForZeroCmp) { |
| 2073 | return getMemCmpExpansionZeroCase(Size, IsLittleEndian); |
| 2074 | } |
| 2075 | |
| 2076 | unsigned Index = 0; |
| 2077 | // This loop calls emitLoadCompareBlock for comparing SizeVal bytes of the two |
| 2078 | // memcmp source. It starts with loading using the maximum load size set by |
| 2079 | // the target. It processes any remaining bytes using a load size which is the |
| 2080 | // next smallest power of 2. |
| 2081 | while (NumBytesToBeProcessed) { |
| 2082 | // Calculate how many blocks we can create with the current load size |
| 2083 | int NumBlocks = NumBytesToBeProcessed / LoadSize; |
| 2084 | int GEPIndex = (Size - NumBytesToBeProcessed) / LoadSize; |
| 2085 | NumBytesToBeProcessed = NumBytesToBeProcessed % LoadSize; |
| 2086 | |
| 2087 | // For each NumBlocks, populate the instruction sequence for loading and |
| 2088 | // comparing LoadSize bytes |
| 2089 | while (NumBlocks--) { |
| 2090 | emitLoadCompareBlock(Index, LoadSize, GEPIndex, IsLittleEndian); |
| 2091 | Index++; |
| 2092 | GEPIndex++; |
| 2093 | } |
| 2094 | // Get the next LoadSize to use |
| 2095 | LoadSize = LoadSize / 2; |
| 2096 | } |
| 2097 | |
| 2098 | emitMemCmpResultBlock(IsLittleEndian); |
| 2099 | return PhiRes; |
| 2100 | } |
| 2101 | |
| 2102 | // This function checks to see if an expansion of memcmp can be generated. |
| 2103 | // It checks for constant compare size that is less than the max inline size. |
| 2104 | // If an expansion cannot occur, returns false to leave as a library call. |
| 2105 | // Otherwise, the library call is replaced wtih new IR instruction sequence. |
| 2106 | /// We want to transform: |
| 2107 | /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15) |
| 2108 | /// To: |
| 2109 | /// loadbb: |
| 2110 | /// %0 = bitcast i32* %buffer2 to i8* |
| 2111 | /// %1 = bitcast i32* %buffer1 to i8* |
| 2112 | /// %2 = bitcast i8* %1 to i64* |
| 2113 | /// %3 = bitcast i8* %0 to i64* |
| 2114 | /// %4 = load i64, i64* %2 |
| 2115 | /// %5 = load i64, i64* %3 |
| 2116 | /// %6 = call i64 @llvm.bswap.i64(i64 %4) |
| 2117 | /// %7 = call i64 @llvm.bswap.i64(i64 %5) |
| 2118 | /// %8 = sub i64 %6, %7 |
| 2119 | /// %9 = icmp ne i64 %8, 0 |
| 2120 | /// br i1 %9, label %res_block, label %loadbb1 |
| 2121 | /// res_block: ; preds = %loadbb2, |
| 2122 | /// %loadbb1, %loadbb |
| 2123 | /// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ] |
| 2124 | /// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ] |
| 2125 | /// %10 = icmp ult i64 %phi.src1, %phi.src2 |
| 2126 | /// %11 = select i1 %10, i32 -1, i32 1 |
| 2127 | /// br label %endblock |
| 2128 | /// loadbb1: ; preds = %loadbb |
| 2129 | /// %12 = bitcast i32* %buffer2 to i8* |
| 2130 | /// %13 = bitcast i32* %buffer1 to i8* |
| 2131 | /// %14 = bitcast i8* %13 to i32* |
| 2132 | /// %15 = bitcast i8* %12 to i32* |
| 2133 | /// %16 = getelementptr i32, i32* %14, i32 2 |
| 2134 | /// %17 = getelementptr i32, i32* %15, i32 2 |
| 2135 | /// %18 = load i32, i32* %16 |
| 2136 | /// %19 = load i32, i32* %17 |
| 2137 | /// %20 = call i32 @llvm.bswap.i32(i32 %18) |
| 2138 | /// %21 = call i32 @llvm.bswap.i32(i32 %19) |
| 2139 | /// %22 = zext i32 %20 to i64 |
| 2140 | /// %23 = zext i32 %21 to i64 |
| 2141 | /// %24 = sub i64 %22, %23 |
| 2142 | /// %25 = icmp ne i64 %24, 0 |
| 2143 | /// br i1 %25, label %res_block, label %loadbb2 |
| 2144 | /// loadbb2: ; preds = %loadbb1 |
| 2145 | /// %26 = bitcast i32* %buffer2 to i8* |
| 2146 | /// %27 = bitcast i32* %buffer1 to i8* |
| 2147 | /// %28 = bitcast i8* %27 to i16* |
| 2148 | /// %29 = bitcast i8* %26 to i16* |
| 2149 | /// %30 = getelementptr i16, i16* %28, i16 6 |
| 2150 | /// %31 = getelementptr i16, i16* %29, i16 6 |
| 2151 | /// %32 = load i16, i16* %30 |
| 2152 | /// %33 = load i16, i16* %31 |
| 2153 | /// %34 = call i16 @llvm.bswap.i16(i16 %32) |
| 2154 | /// %35 = call i16 @llvm.bswap.i16(i16 %33) |
| 2155 | /// %36 = zext i16 %34 to i64 |
| 2156 | /// %37 = zext i16 %35 to i64 |
| 2157 | /// %38 = sub i64 %36, %37 |
| 2158 | /// %39 = icmp ne i64 %38, 0 |
| 2159 | /// br i1 %39, label %res_block, label %loadbb3 |
| 2160 | /// loadbb3: ; preds = %loadbb2 |
| 2161 | /// %40 = bitcast i32* %buffer2 to i8* |
| 2162 | /// %41 = bitcast i32* %buffer1 to i8* |
| 2163 | /// %42 = getelementptr i8, i8* %41, i8 14 |
| 2164 | /// %43 = getelementptr i8, i8* %40, i8 14 |
| 2165 | /// %44 = load i8, i8* %42 |
| 2166 | /// %45 = load i8, i8* %43 |
| 2167 | /// %46 = zext i8 %44 to i32 |
| 2168 | /// %47 = zext i8 %45 to i32 |
| 2169 | /// %48 = sub i32 %46, %47 |
| 2170 | /// br label %endblock |
| 2171 | /// endblock: ; preds = %res_block, |
| 2172 | /// %loadbb3 |
| 2173 | /// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ] |
| 2174 | /// ret i32 %phi.res |
| 2175 | static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI, |
| 2176 | const TargetLowering *TLI, const DataLayout *DL) { |
| 2177 | NumMemCmpCalls++; |
| 2178 | IRBuilder<> Builder(CI->getContext()); |
| 2179 | |
| 2180 | // TTI call to check if target would like to expand memcmp and get the |
| 2181 | // MaxLoadSize |
| 2182 | unsigned MaxLoadSize; |
| 2183 | if (!TTI->expandMemCmp(CI, MaxLoadSize)) |
| 2184 | return false; |
| 2185 | |
| 2186 | // Early exit from expansion if -Oz |
| 2187 | if (CI->getParent()->getParent()->optForMinSize()) { |
| 2188 | return false; |
| 2189 | } |
| 2190 | |
| 2191 | // Early exit from expansion if size is not a constant |
| 2192 | ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2)); |
| 2193 | if (!SizeCast) { |
| 2194 | NumMemCmpNotConstant++; |
| 2195 | return false; |
| 2196 | } |
| 2197 | |
| 2198 | // Early exit from expansion if size greater than max bytes to load |
| 2199 | uint64_t SizeVal = SizeCast->getZExtValue(); |
| 2200 | |
| 2201 | unsigned NumLoads = 0; |
| 2202 | unsigned RemainingSize = SizeVal; |
| 2203 | unsigned LoadSize = MaxLoadSize; |
| 2204 | while (RemainingSize) { |
| 2205 | NumLoads += RemainingSize / LoadSize; |
| 2206 | RemainingSize = RemainingSize % LoadSize; |
| 2207 | LoadSize = LoadSize / 2; |
| 2208 | } |
| 2209 | |
| 2210 | if (NumLoads > |
| 2211 | TLI->getMaxExpandSizeMemcmp(CI->getParent()->getParent()->optForSize())) { |
| 2212 | NumMemCmpGreaterThanMax++; |
| 2213 | return false; |
| 2214 | } |
| 2215 | |
| 2216 | NumMemCmpInlined++; |
| 2217 | |
| 2218 | // MemCmpHelper object, creates and sets up basic blocks required for |
| 2219 | // expanding memcmp with size SizeVal |
| 2220 | unsigned NumLoadsPerBlock = MemCmpNumLoadsPerBlock; |
| 2221 | MemCmpExpansion MemCmpHelper(CI, MaxLoadSize, NumLoadsPerBlock); |
| 2222 | |
| 2223 | Value *Res = MemCmpHelper.getMemCmpExpansion(DL->isLittleEndian()); |
| 2224 | |
| 2225 | // Replace call with result of expansion and erarse call. |
| 2226 | CI->replaceAllUsesWith(Res); |
| 2227 | CI->eraseFromParent(); |
| 2228 | |
| 2229 | return true; |
| 2230 | } |
| 2231 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2232 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2233 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2234 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2235 | // Lower inline assembly if we can. |
| 2236 | // If we found an inline asm expession, and if the target knows how to |
| 2237 | // lower it to normal LLVM code, do so now. |
| 2238 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 2239 | if (TLI->ExpandInlineAsm(CI)) { |
| 2240 | // Avoid invalidating the iterator. |
| 2241 | CurInstIterator = BB->begin(); |
| 2242 | // Avoid processing instructions out of order, which could cause |
| 2243 | // reuse before a value is defined. |
| 2244 | SunkAddrs.clear(); |
| 2245 | return true; |
| 2246 | } |
| 2247 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2248 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2249 | return true; |
| 2250 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2251 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2252 | // Align the pointer arguments to this call if the target thinks it's a good |
| 2253 | // idea |
| 2254 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2255 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2256 | for (auto &Arg : CI->arg_operands()) { |
| 2257 | // We want to align both objects whose address is used directly and |
| 2258 | // objects whose address is used in casts and GEPs, though it only makes |
| 2259 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 2260 | // if size - offset meets the size threshold. |
| 2261 | if (!Arg->getType()->isPointerTy()) |
| 2262 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2263 | APInt Offset(DL->getPointerSizeInBits( |
| 2264 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 2265 | 0); |
| 2266 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2267 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2268 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 2269 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2270 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2271 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 2272 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2273 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2274 | // Global variables can only be aligned if they are defined in this |
| 2275 | // object (i.e. they are uniquely initialized in this object), and |
| 2276 | // over-aligning global variables that have an explicit section is |
| 2277 | // forbidden. |
| 2278 | GlobalVariable *GV; |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 2279 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && |
Tim Northover | 918f050 | 2016-07-18 18:28:52 +0000 | [diff] [blame] | 2280 | GV->getPointerAlignment(*DL) < PrefAlign && |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 2281 | DL->getTypeAllocSize(GV->getValueType()) >= |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2282 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2283 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2284 | } |
| 2285 | // If this is a memcpy (or similar) then we may be able to improve the |
| 2286 | // alignment |
| 2287 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2288 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2289 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2290 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 2291 | if (Align > MI->getAlignment()) |
| 2292 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2293 | } |
| 2294 | } |
| 2295 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 2296 | // If we have a cold call site, try to sink addressing computation into the |
| 2297 | // cold block. This interacts with our handling for loads and stores to |
| 2298 | // ensure that we can fold all uses of a potential addressing computation |
| 2299 | // into their uses. TODO: generalize this to work over profiling data |
| 2300 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 2301 | for (auto &Arg : CI->arg_operands()) { |
| 2302 | if (!Arg->getType()->isPointerTy()) |
| 2303 | continue; |
| 2304 | unsigned AS = Arg->getType()->getPointerAddressSpace(); |
| 2305 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); |
| 2306 | } |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 2307 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2308 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2309 | if (II) { |
| 2310 | switch (II->getIntrinsicID()) { |
| 2311 | default: break; |
| 2312 | case Intrinsic::objectsize: { |
| 2313 | // Lower all uses of llvm.objectsize.* |
George Burgess IV | 3f08914 | 2016-12-20 23:46:36 +0000 | [diff] [blame] | 2314 | ConstantInt *RetVal = |
| 2315 | lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2316 | // Substituting this can cause recursive simplifications, which can |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 2317 | // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case |
| 2318 | // this |
Sanjoy Das | 2cbeb00 | 2017-04-26 16:37:05 +0000 | [diff] [blame] | 2319 | // happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 2320 | Value *CurValue = &*CurInstIterator; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 2321 | WeakTrackingVH IterHandle(CurValue); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2322 | |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 2323 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 2324 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2325 | // If the iterator instruction was recursively deleted, start over at the |
| 2326 | // start of the block. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 2327 | if (IterHandle != CurValue) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2328 | CurInstIterator = BB->begin(); |
| 2329 | SunkAddrs.clear(); |
| 2330 | } |
| 2331 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 2332 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2333 | case Intrinsic::aarch64_stlxr: |
| 2334 | case Intrinsic::aarch64_stxr: { |
| 2335 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 2336 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 2337 | ExtVal->getParent() == CI->getParent()) |
| 2338 | return false; |
| 2339 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 2340 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2341 | // Mark this instruction as "inserted by CGP", so that other |
| 2342 | // optimizations don't touch it. |
| 2343 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2344 | return true; |
| 2345 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 2346 | case Intrinsic::invariant_group_barrier: |
| 2347 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 2348 | II->eraseFromParent(); |
| 2349 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2350 | |
| 2351 | case Intrinsic::cttz: |
| 2352 | case Intrinsic::ctlz: |
| 2353 | // If counting zeros is expensive, try to avoid it. |
| 2354 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2355 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2356 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2357 | if (TLI) { |
| 2358 | SmallVector<Value*, 2> PtrOps; |
| 2359 | Type *AccessTy; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 2360 | if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) |
| 2361 | while (!PtrOps.empty()) { |
| 2362 | Value *PtrVal = PtrOps.pop_back_val(); |
| 2363 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); |
| 2364 | if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2365 | return true; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 2366 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2367 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 2368 | } |
| 2369 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2370 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2371 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 2372 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 2373 | // Lower all default uses of _chk calls. This is very similar |
| 2374 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2375 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 2376 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2377 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2378 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 2379 | CI->replaceAllUsesWith(V); |
| 2380 | CI->eraseFromParent(); |
| 2381 | return true; |
| 2382 | } |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 2383 | |
| 2384 | LibFunc Func; |
| 2385 | if (TLInfo->getLibFunc(*CI->getCalledFunction(), Func) && |
| 2386 | Func == LibFunc_memcmp) { |
| 2387 | if (expandMemCmp(CI, TTI, TLI, DL)) { |
| 2388 | ModifiedDT = true; |
| 2389 | return true; |
| 2390 | } |
| 2391 | } |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2392 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2393 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 2394 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2395 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 2396 | /// 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] | 2397 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2398 | /// bb0: |
| 2399 | /// %tmp0 = tail call i32 @f0() |
| 2400 | /// br label %return |
| 2401 | /// bb1: |
| 2402 | /// %tmp1 = tail call i32 @f1() |
| 2403 | /// br label %return |
| 2404 | /// bb2: |
| 2405 | /// %tmp2 = tail call i32 @f2() |
| 2406 | /// br label %return |
| 2407 | /// return: |
| 2408 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 2409 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2410 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2411 | /// |
| 2412 | /// => |
| 2413 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2414 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2415 | /// bb0: |
| 2416 | /// %tmp0 = tail call i32 @f0() |
| 2417 | /// ret i32 %tmp0 |
| 2418 | /// bb1: |
| 2419 | /// %tmp1 = tail call i32 @f1() |
| 2420 | /// ret i32 %tmp1 |
| 2421 | /// bb2: |
| 2422 | /// %tmp2 = tail call i32 @f2() |
| 2423 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2424 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2425 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 2426 | if (!TLI) |
| 2427 | return false; |
| 2428 | |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2429 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 2430 | if (!RetI) |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 2431 | return false; |
| 2432 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2433 | PHINode *PN = nullptr; |
| 2434 | BitCastInst *BCI = nullptr; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2435 | Value *V = RetI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2436 | if (V) { |
| 2437 | BCI = dyn_cast<BitCastInst>(V); |
| 2438 | if (BCI) |
| 2439 | V = BCI->getOperand(0); |
| 2440 | |
| 2441 | PN = dyn_cast<PHINode>(V); |
| 2442 | if (!PN) |
| 2443 | return false; |
| 2444 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2445 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2446 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2447 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2448 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2449 | // Make sure there are no instructions between the PHI and return, or that the |
| 2450 | // return is the first instruction in the block. |
| 2451 | if (PN) { |
| 2452 | BasicBlock::iterator BI = BB->begin(); |
| 2453 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2454 | if (&*BI == BCI) |
| 2455 | // Also skip over the bitcast. |
| 2456 | ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2457 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2458 | return false; |
| 2459 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2460 | BasicBlock::iterator BI = BB->begin(); |
| 2461 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2462 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2463 | return false; |
| 2464 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2465 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2466 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 2467 | /// call. |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2468 | const Function *F = BB->getParent(); |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2469 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2470 | if (PN) { |
| 2471 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 2472 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 2473 | // Make sure the phi value is indeed produced by the tail call. |
| 2474 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2475 | TLI->mayBeEmittedAsTailCall(CI) && |
| 2476 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2477 | TailCalls.push_back(CI); |
| 2478 | } |
| 2479 | } else { |
| 2480 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2481 | 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] | 2482 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2483 | continue; |
| 2484 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2485 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2486 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 2487 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2488 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 2489 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2490 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2491 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2492 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2493 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && |
| 2494 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2495 | TailCalls.push_back(CI); |
| 2496 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2497 | } |
| 2498 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2499 | bool Changed = false; |
| 2500 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 2501 | CallInst *CI = TailCalls[i]; |
| 2502 | CallSite CS(CI); |
| 2503 | |
| 2504 | // Conservatively require the attributes of the call to match those of the |
| 2505 | // return. Ignore noalias because it doesn't affect the call sequence. |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame] | 2506 | AttributeList CalleeAttrs = CS.getAttributes(); |
| 2507 | if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 2508 | .removeAttribute(Attribute::NoAlias) != |
| 2509 | AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 2510 | .removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2511 | continue; |
| 2512 | |
| 2513 | // Make sure the call instruction is followed by an unconditional branch to |
| 2514 | // the return block. |
| 2515 | BasicBlock *CallBB = CI->getParent(); |
| 2516 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 2517 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 2518 | continue; |
| 2519 | |
| 2520 | // Duplicate the return into CallBB. |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2521 | (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 2522 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2523 | ++NumRetsDup; |
| 2524 | } |
| 2525 | |
| 2526 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 2527 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2528 | BB->eraseFromParent(); |
| 2529 | |
| 2530 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2531 | } |
| 2532 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2533 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2534 | // Memory Optimization |
| 2535 | //===----------------------------------------------------------------------===// |
| 2536 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2537 | namespace { |
| 2538 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2539 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2540 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 2541 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2542 | Value *BaseReg; |
| 2543 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2544 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2545 | void print(raw_ostream &OS) const; |
| 2546 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2547 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2548 | bool operator==(const ExtAddrMode& O) const { |
| 2549 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 2550 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 2551 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 2552 | } |
| 2553 | }; |
| 2554 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2555 | #ifndef NDEBUG |
| 2556 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2557 | AM.print(OS); |
| 2558 | return OS; |
| 2559 | } |
| 2560 | #endif |
| 2561 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2562 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2563 | bool NeedPlus = false; |
| 2564 | OS << "["; |
| 2565 | if (BaseGV) { |
| 2566 | OS << (NeedPlus ? " + " : "") |
| 2567 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2568 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2569 | NeedPlus = true; |
| 2570 | } |
| 2571 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2572 | if (BaseOffs) { |
| 2573 | OS << (NeedPlus ? " + " : "") |
| 2574 | << BaseOffs; |
| 2575 | NeedPlus = true; |
| 2576 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2577 | |
| 2578 | if (BaseReg) { |
| 2579 | OS << (NeedPlus ? " + " : "") |
| 2580 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2581 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2582 | NeedPlus = true; |
| 2583 | } |
| 2584 | if (Scale) { |
| 2585 | OS << (NeedPlus ? " + " : "") |
| 2586 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2587 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2588 | } |
| 2589 | |
| 2590 | OS << ']'; |
| 2591 | } |
| 2592 | |
| 2593 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Yaron Keren | eb2a254 | 2016-01-29 20:50:44 +0000 | [diff] [blame] | 2594 | LLVM_DUMP_METHOD void ExtAddrMode::dump() const { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2595 | print(dbgs()); |
| 2596 | dbgs() << '\n'; |
| 2597 | } |
| 2598 | #endif |
| 2599 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2600 | /// \brief This class provides transaction based operation on the IR. |
| 2601 | /// Every change made through this class is recorded in the internal state and |
| 2602 | /// can be undone (rollback) until commit is called. |
| 2603 | class TypePromotionTransaction { |
| 2604 | |
| 2605 | /// \brief This represents the common interface of the individual transaction. |
| 2606 | /// Each class implements the logic for doing one specific modification on |
| 2607 | /// the IR via the TypePromotionTransaction. |
| 2608 | class TypePromotionAction { |
| 2609 | protected: |
| 2610 | /// The Instruction modified. |
| 2611 | Instruction *Inst; |
| 2612 | |
| 2613 | public: |
| 2614 | /// \brief Constructor of the action. |
| 2615 | /// The constructor performs the related action on the IR. |
| 2616 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2617 | |
| 2618 | virtual ~TypePromotionAction() {} |
| 2619 | |
| 2620 | /// \brief Undo the modification done by this action. |
| 2621 | /// When this method is called, the IR must be in the same state as it was |
| 2622 | /// before this action was applied. |
| 2623 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2624 | /// state as it was directly after this action was applied. |
| 2625 | virtual void undo() = 0; |
| 2626 | |
| 2627 | /// \brief Advocate every change made by this action. |
| 2628 | /// When the results on the IR of the action are to be kept, it is important |
| 2629 | /// to call this function, otherwise hidden information may be kept forever. |
| 2630 | virtual void commit() { |
| 2631 | // Nothing to be done, this action is not doing anything. |
| 2632 | } |
| 2633 | }; |
| 2634 | |
| 2635 | /// \brief Utility to remember the position of an instruction. |
| 2636 | class InsertionHandler { |
| 2637 | /// Position of an instruction. |
| 2638 | /// Either an instruction: |
| 2639 | /// - Is the first in a basic block: BB is used. |
| 2640 | /// - Has a previous instructon: PrevInst is used. |
| 2641 | union { |
| 2642 | Instruction *PrevInst; |
| 2643 | BasicBlock *BB; |
| 2644 | } Point; |
| 2645 | /// Remember whether or not the instruction had a previous instruction. |
| 2646 | bool HasPrevInstruction; |
| 2647 | |
| 2648 | public: |
| 2649 | /// \brief Record the position of \p Inst. |
| 2650 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2651 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2652 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2653 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2654 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2655 | else |
| 2656 | Point.BB = Inst->getParent(); |
| 2657 | } |
| 2658 | |
| 2659 | /// \brief Insert \p Inst at the recorded position. |
| 2660 | void insert(Instruction *Inst) { |
| 2661 | if (HasPrevInstruction) { |
| 2662 | if (Inst->getParent()) |
| 2663 | Inst->removeFromParent(); |
| 2664 | Inst->insertAfter(Point.PrevInst); |
| 2665 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2666 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2667 | if (Inst->getParent()) |
| 2668 | Inst->moveBefore(Position); |
| 2669 | else |
| 2670 | Inst->insertBefore(Position); |
| 2671 | } |
| 2672 | } |
| 2673 | }; |
| 2674 | |
| 2675 | /// \brief Move an instruction before another. |
| 2676 | class InstructionMoveBefore : public TypePromotionAction { |
| 2677 | /// Original position of the instruction. |
| 2678 | InsertionHandler Position; |
| 2679 | |
| 2680 | public: |
| 2681 | /// \brief Move \p Inst before \p Before. |
| 2682 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2683 | : TypePromotionAction(Inst), Position(Inst) { |
| 2684 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2685 | Inst->moveBefore(Before); |
| 2686 | } |
| 2687 | |
| 2688 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2689 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2690 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2691 | Position.insert(Inst); |
| 2692 | } |
| 2693 | }; |
| 2694 | |
| 2695 | /// \brief Set the operand of an instruction with a new value. |
| 2696 | class OperandSetter : public TypePromotionAction { |
| 2697 | /// Original operand of the instruction. |
| 2698 | Value *Origin; |
| 2699 | /// Index of the modified instruction. |
| 2700 | unsigned Idx; |
| 2701 | |
| 2702 | public: |
| 2703 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2704 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2705 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2706 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2707 | << "for:" << *Inst << "\n" |
| 2708 | << "with:" << *NewVal << "\n"); |
| 2709 | Origin = Inst->getOperand(Idx); |
| 2710 | Inst->setOperand(Idx, NewVal); |
| 2711 | } |
| 2712 | |
| 2713 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2714 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2715 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2716 | << "for: " << *Inst << "\n" |
| 2717 | << "with: " << *Origin << "\n"); |
| 2718 | Inst->setOperand(Idx, Origin); |
| 2719 | } |
| 2720 | }; |
| 2721 | |
| 2722 | /// \brief Hide the operands of an instruction. |
| 2723 | /// Do as if this instruction was not using any of its operands. |
| 2724 | class OperandsHider : public TypePromotionAction { |
| 2725 | /// The list of original operands. |
| 2726 | SmallVector<Value *, 4> OriginalValues; |
| 2727 | |
| 2728 | public: |
| 2729 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2730 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2731 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2732 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2733 | OriginalValues.reserve(NumOpnds); |
| 2734 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2735 | // Save the current operand. |
| 2736 | Value *Val = Inst->getOperand(It); |
| 2737 | OriginalValues.push_back(Val); |
| 2738 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2739 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2740 | // that we are not willing to pay. |
| 2741 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2742 | } |
| 2743 | } |
| 2744 | |
| 2745 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2746 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2747 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2748 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2749 | Inst->setOperand(It, OriginalValues[It]); |
| 2750 | } |
| 2751 | }; |
| 2752 | |
| 2753 | /// \brief Build a truncate instruction. |
| 2754 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2755 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2756 | public: |
| 2757 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2758 | /// result. |
| 2759 | /// trunc Opnd to Ty. |
| 2760 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2761 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2762 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2763 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2764 | } |
| 2765 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2766 | /// \brief Get the built value. |
| 2767 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2768 | |
| 2769 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2770 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2771 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2772 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2773 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2774 | } |
| 2775 | }; |
| 2776 | |
| 2777 | /// \brief Build a sign extension instruction. |
| 2778 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2779 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2780 | public: |
| 2781 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2782 | /// result. |
| 2783 | /// sext Opnd to Ty. |
| 2784 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2785 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2786 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2787 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2788 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2789 | } |
| 2790 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2791 | /// \brief Get the built value. |
| 2792 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2793 | |
| 2794 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2795 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2796 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2797 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2798 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2799 | } |
| 2800 | }; |
| 2801 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2802 | /// \brief Build a zero extension instruction. |
| 2803 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2804 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2805 | public: |
| 2806 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2807 | /// result. |
| 2808 | /// zext Opnd to Ty. |
| 2809 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2810 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2811 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2812 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2813 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2814 | } |
| 2815 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2816 | /// \brief Get the built value. |
| 2817 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2818 | |
| 2819 | /// \brief Remove the built instruction. |
| 2820 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2821 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2822 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2823 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2824 | } |
| 2825 | }; |
| 2826 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2827 | /// \brief Mutate an instruction to another type. |
| 2828 | class TypeMutator : public TypePromotionAction { |
| 2829 | /// Record the original type. |
| 2830 | Type *OrigTy; |
| 2831 | |
| 2832 | public: |
| 2833 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2834 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2835 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2836 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2837 | << "\n"); |
| 2838 | Inst->mutateType(NewTy); |
| 2839 | } |
| 2840 | |
| 2841 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2842 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2843 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2844 | << "\n"); |
| 2845 | Inst->mutateType(OrigTy); |
| 2846 | } |
| 2847 | }; |
| 2848 | |
| 2849 | /// \brief Replace the uses of an instruction by another instruction. |
| 2850 | class UsesReplacer : public TypePromotionAction { |
| 2851 | /// Helper structure to keep track of the replaced uses. |
| 2852 | struct InstructionAndIdx { |
| 2853 | /// The instruction using the instruction. |
| 2854 | Instruction *Inst; |
| 2855 | /// The index where this instruction is used for Inst. |
| 2856 | unsigned Idx; |
| 2857 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2858 | : Inst(Inst), Idx(Idx) {} |
| 2859 | }; |
| 2860 | |
| 2861 | /// Keep track of the original uses (pair Instruction, Index). |
| 2862 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 2863 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 2864 | |
| 2865 | public: |
| 2866 | /// \brief Replace all the use of \p Inst by \p New. |
| 2867 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2868 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2869 | << "\n"); |
| 2870 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2871 | for (Use &U : Inst->uses()) { |
| 2872 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2873 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2874 | } |
| 2875 | // Now, we can replace the uses. |
| 2876 | Inst->replaceAllUsesWith(New); |
| 2877 | } |
| 2878 | |
| 2879 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2880 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2881 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2882 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2883 | EndIt = OriginalUses.end(); |
| 2884 | UseIt != EndIt; ++UseIt) { |
| 2885 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2886 | } |
| 2887 | } |
| 2888 | }; |
| 2889 | |
| 2890 | /// \brief Remove an instruction from the IR. |
| 2891 | class InstructionRemover : public TypePromotionAction { |
| 2892 | /// Original position of the instruction. |
| 2893 | InsertionHandler Inserter; |
| 2894 | /// Helper structure to hide all the link to the instruction. In other |
| 2895 | /// words, this helps to do as if the instruction was removed. |
| 2896 | OperandsHider Hider; |
| 2897 | /// Keep track of the uses replaced, if any. |
| 2898 | UsesReplacer *Replacer; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2899 | /// Keep track of instructions removed. |
| 2900 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2901 | |
| 2902 | public: |
| 2903 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2904 | /// uses with New. |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2905 | /// \p RemovedInsts Keep track of the instructions removed by this Action. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2906 | /// \pre If !Inst->use_empty(), then New != nullptr |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2907 | InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, |
| 2908 | Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2909 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2910 | Replacer(nullptr), RemovedInsts(RemovedInsts) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2911 | if (New) |
| 2912 | Replacer = new UsesReplacer(Inst, New); |
| 2913 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2914 | RemovedInsts.insert(Inst); |
| 2915 | /// The instructions removed here will be freed after completing |
| 2916 | /// optimizeBlock() for all blocks as we need to keep track of the |
| 2917 | /// removed instructions during promotion. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2918 | Inst->removeFromParent(); |
| 2919 | } |
| 2920 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2921 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2922 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2923 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2924 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2925 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2926 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2927 | Inserter.insert(Inst); |
| 2928 | if (Replacer) |
| 2929 | Replacer->undo(); |
| 2930 | Hider.undo(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2931 | RemovedInsts.erase(Inst); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2932 | } |
| 2933 | }; |
| 2934 | |
| 2935 | public: |
| 2936 | /// Restoration point. |
| 2937 | /// The restoration point is a pointer to an action instead of an iterator |
| 2938 | /// because the iterator may be invalidated but not the pointer. |
| 2939 | typedef const TypePromotionAction *ConstRestorationPt; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2940 | |
| 2941 | TypePromotionTransaction(SetOfInstrs &RemovedInsts) |
| 2942 | : RemovedInsts(RemovedInsts) {} |
| 2943 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2944 | /// Advocate every changes made in that transaction. |
| 2945 | void commit(); |
| 2946 | /// Undo all the changes made after the given point. |
| 2947 | void rollback(ConstRestorationPt Point); |
| 2948 | /// Get the current restoration point. |
| 2949 | ConstRestorationPt getRestorationPoint() const; |
| 2950 | |
| 2951 | /// \name API for IR modification with state keeping to support rollback. |
| 2952 | /// @{ |
| 2953 | /// Same as Instruction::setOperand. |
| 2954 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2955 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2956 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2957 | /// Same as Value::replaceAllUsesWith. |
| 2958 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2959 | /// Same as Value::mutateType. |
| 2960 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2961 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2962 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2963 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2964 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2965 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2966 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2967 | /// Same as Instruction::moveBefore. |
| 2968 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2969 | /// @} |
| 2970 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2971 | private: |
| 2972 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2973 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2974 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2975 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2976 | }; |
| 2977 | |
| 2978 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2979 | Value *NewVal) { |
| 2980 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2981 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2982 | } |
| 2983 | |
| 2984 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2985 | Value *NewVal) { |
| 2986 | Actions.push_back( |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2987 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, |
| 2988 | RemovedInsts, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2989 | } |
| 2990 | |
| 2991 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2992 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2993 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2994 | } |
| 2995 | |
| 2996 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2997 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2998 | } |
| 2999 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3000 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 3001 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3002 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3003 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3004 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3005 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3006 | } |
| 3007 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3008 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 3009 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3010 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3011 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3012 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3013 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3014 | } |
| 3015 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3016 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 3017 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3018 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3019 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3020 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3021 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3022 | } |
| 3023 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3024 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 3025 | Instruction *Before) { |
| 3026 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3027 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3028 | } |
| 3029 | |
| 3030 | TypePromotionTransaction::ConstRestorationPt |
| 3031 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3032 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3033 | } |
| 3034 | |
| 3035 | void TypePromotionTransaction::commit() { |
| 3036 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3037 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3038 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3039 | Actions.clear(); |
| 3040 | } |
| 3041 | |
| 3042 | void TypePromotionTransaction::rollback( |
| 3043 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 3044 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 3045 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3046 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3047 | } |
| 3048 | } |
| 3049 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3050 | /// \brief A helper class for matching addressing modes. |
| 3051 | /// |
| 3052 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 3053 | class AddressingModeMatcher { |
| 3054 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 3055 | const TargetLowering &TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3056 | const TargetRegisterInfo &TRI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3057 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3058 | |
| 3059 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 3060 | /// the memory instruction that we're computing this address for. |
| 3061 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3062 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3063 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3064 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3065 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3066 | /// part of the return value of this addressing mode matching stuff. |
| 3067 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3068 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3069 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 3070 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3071 | /// A map from the instructions to their type before promotion. |
| 3072 | InstrToOrigTy &PromotedInsts; |
| 3073 | /// The ongoing transaction where every action should be registered. |
| 3074 | TypePromotionTransaction &TPT; |
| 3075 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3076 | /// This is set to true when we should not do profitability checks. |
| 3077 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3078 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3079 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3080 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3081 | const TargetLowering &TLI, |
| 3082 | const TargetRegisterInfo &TRI, |
| 3083 | Type *AT, unsigned AS, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3084 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3085 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3086 | InstrToOrigTy &PromotedInsts, |
| 3087 | TypePromotionTransaction &TPT) |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3088 | : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3089 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 3090 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 3091 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3092 | IgnoreProfitability = false; |
| 3093 | } |
| 3094 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3095 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3096 | /// 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] | 3097 | /// give an access type of AccessTy. This returns a list of involved |
| 3098 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3099 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3100 | /// optimizations. |
| 3101 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 3102 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3103 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3104 | Instruction *MemoryInst, |
| 3105 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3106 | const TargetLowering &TLI, |
| 3107 | const TargetRegisterInfo &TRI, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3108 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3109 | InstrToOrigTy &PromotedInsts, |
| 3110 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3111 | ExtAddrMode Result; |
| 3112 | |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3113 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, |
| 3114 | AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3115 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3116 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3117 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3118 | return Result; |
| 3119 | } |
| 3120 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3121 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 3122 | bool matchAddr(Value *V, unsigned Depth); |
| 3123 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3124 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3125 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3126 | ExtAddrMode &AMBefore, |
| 3127 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3128 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 3129 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3130 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3131 | }; |
| 3132 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3133 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3134 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 3135 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3136 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3137 | unsigned Depth) { |
| 3138 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 3139 | // mode. Just process that directly. |
| 3140 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3141 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3142 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3143 | // If the scale is 0, it takes nothing to add this. |
| 3144 | if (Scale == 0) |
| 3145 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3146 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3147 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 3148 | // need an available scale field. |
| 3149 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 3150 | return false; |
| 3151 | |
| 3152 | ExtAddrMode TestAddrMode = AddrMode; |
| 3153 | |
| 3154 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 3155 | // [A+B + A*7] -> [B+A*8]. |
| 3156 | TestAddrMode.Scale += Scale; |
| 3157 | TestAddrMode.ScaledReg = ScaleReg; |
| 3158 | |
| 3159 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3160 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3161 | return false; |
| 3162 | |
| 3163 | // It was legal, so commit it. |
| 3164 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3165 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3166 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 3167 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 3168 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3169 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3170 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 3171 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 3172 | TestAddrMode.ScaledReg = AddLHS; |
| 3173 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3174 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3175 | // If this addressing mode is legal, commit it and remember that we folded |
| 3176 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3177 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3178 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 3179 | AddrMode = TestAddrMode; |
| 3180 | return true; |
| 3181 | } |
| 3182 | } |
| 3183 | |
| 3184 | // Otherwise, not (x+c)*scale, just return what we have. |
| 3185 | return true; |
| 3186 | } |
| 3187 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3188 | /// This is a little filter, which returns true if an addressing computation |
| 3189 | /// involving I might be folded into a load/store accessing it. |
| 3190 | /// 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] | 3191 | /// the set of instructions that MatchOperationAddr can. |
| 3192 | static bool MightBeFoldableInst(Instruction *I) { |
| 3193 | switch (I->getOpcode()) { |
| 3194 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 3195 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3196 | // Don't touch identity bitcasts. |
| 3197 | if (I->getType() == I->getOperand(0)->getType()) |
| 3198 | return false; |
| 3199 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 3200 | case Instruction::PtrToInt: |
| 3201 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 3202 | return true; |
| 3203 | case Instruction::IntToPtr: |
| 3204 | // We know the input is intptr_t, so this is foldable. |
| 3205 | return true; |
| 3206 | case Instruction::Add: |
| 3207 | return true; |
| 3208 | case Instruction::Mul: |
| 3209 | case Instruction::Shl: |
| 3210 | // Can only handle X*C and X << C. |
| 3211 | return isa<ConstantInt>(I->getOperand(1)); |
| 3212 | case Instruction::GetElementPtr: |
| 3213 | return true; |
| 3214 | default: |
| 3215 | return false; |
| 3216 | } |
| 3217 | } |
| 3218 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3219 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 3220 | /// \note \p Val is assumed to be the product of some type promotion. |
| 3221 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 3222 | /// 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] | 3223 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 3224 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3225 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 3226 | if (!PromotedInst) |
| 3227 | return false; |
| 3228 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 3229 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 3230 | if (!ISDOpcode) |
| 3231 | return true; |
| 3232 | // Otherwise, check if the promoted instruction is legal or not. |
| 3233 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3234 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3235 | } |
| 3236 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3237 | /// \brief Hepler class to perform type promotion. |
| 3238 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3239 | /// \brief Utility function to check whether or not a sign or zero extension |
| 3240 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 3241 | /// either using the operands of \p Inst or promoting \p Inst. |
| 3242 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3243 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3244 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3245 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3246 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3247 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3248 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3249 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3250 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 3251 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3252 | |
| 3253 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 3254 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3255 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3256 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3257 | } |
| 3258 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3259 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3260 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3261 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3262 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3263 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3264 | /// Newly added extensions are inserted in \p Exts. |
| 3265 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3266 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3267 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3268 | static Value *promoteOperandForTruncAndAnyExt( |
| 3269 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3270 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3271 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3272 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3273 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3274 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3275 | /// operand is promotable and is not a supported trunc or sext. |
| 3276 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3277 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3278 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3279 | /// Newly added extensions are inserted in \p Exts. |
| 3280 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3281 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3282 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3283 | static Value *promoteOperandForOther(Instruction *Ext, |
| 3284 | TypePromotionTransaction &TPT, |
| 3285 | InstrToOrigTy &PromotedInsts, |
| 3286 | unsigned &CreatedInstsCost, |
| 3287 | SmallVectorImpl<Instruction *> *Exts, |
| 3288 | SmallVectorImpl<Instruction *> *Truncs, |
| 3289 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3290 | |
| 3291 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3292 | static Value *signExtendOperandForOther( |
| 3293 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3294 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3295 | SmallVectorImpl<Instruction *> *Exts, |
| 3296 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3297 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3298 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3299 | } |
| 3300 | |
| 3301 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3302 | static Value *zeroExtendOperandForOther( |
| 3303 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3304 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3305 | SmallVectorImpl<Instruction *> *Exts, |
| 3306 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3307 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3308 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3309 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3310 | |
| 3311 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3312 | /// Type for the utility function that promotes the operand of Ext. |
| 3313 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3314 | InstrToOrigTy &PromotedInsts, |
| 3315 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3316 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3317 | SmallVectorImpl<Instruction *> *Truncs, |
| 3318 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3319 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 3320 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3321 | /// \return NULL if no promotable action is possible with the current |
| 3322 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3323 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 3324 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3325 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 3326 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 3327 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3328 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3329 | const TargetLowering &TLI, |
| 3330 | const InstrToOrigTy &PromotedInsts); |
| 3331 | }; |
| 3332 | |
| 3333 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3334 | Type *ConsideredExtType, |
| 3335 | const InstrToOrigTy &PromotedInsts, |
| 3336 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3337 | // The promotion helper does not know how to deal with vector types yet. |
| 3338 | // To be able to fix that, we would need to fix the places where we |
| 3339 | // statically extend, e.g., constants and such. |
| 3340 | if (Inst->getType()->isVectorTy()) |
| 3341 | return false; |
| 3342 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3343 | // We can always get through zext. |
| 3344 | if (isa<ZExtInst>(Inst)) |
| 3345 | return true; |
| 3346 | |
| 3347 | // sext(sext) is ok too. |
| 3348 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3349 | return true; |
| 3350 | |
| 3351 | // We can get through binary operator, if it is legal. In other words, the |
| 3352 | // binary operator must have a nuw or nsw flag. |
| 3353 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 3354 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3355 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 3356 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3357 | return true; |
| 3358 | |
| 3359 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3360 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3361 | if (!isa<TruncInst>(Inst)) |
| 3362 | return false; |
| 3363 | |
| 3364 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3365 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3366 | // 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] | 3367 | if (!OpndVal->getType()->isIntegerTy() || |
| 3368 | OpndVal->getType()->getIntegerBitWidth() > |
| 3369 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3370 | return false; |
| 3371 | |
| 3372 | // If the operand of the truncate is not an instruction, we will not have |
| 3373 | // any information on the dropped bits. |
| 3374 | // (Actually we could for constant but it is not worth the extra logic). |
| 3375 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 3376 | if (!Opnd) |
| 3377 | return false; |
| 3378 | |
| 3379 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3380 | // I.e., check that trunc just drops extended bits of the same kind of |
| 3381 | // the extension. |
| 3382 | // #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] | 3383 | const Type *OpndType; |
| 3384 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 3385 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 3386 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3387 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 3388 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3389 | else |
| 3390 | return false; |
| 3391 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3392 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3393 | return Inst->getType()->getIntegerBitWidth() >= |
| 3394 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3395 | } |
| 3396 | |
| 3397 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3398 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3399 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3400 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 3401 | "Unexpected instruction type"); |
| 3402 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 3403 | Type *ExtTy = Ext->getType(); |
| 3404 | bool IsSExt = isa<SExtInst>(Ext); |
| 3405 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3406 | // get through. |
| 3407 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3408 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3409 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3410 | |
| 3411 | // Do not promote if the operand has been added by codegenprepare. |
| 3412 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 3413 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3414 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3415 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3416 | |
| 3417 | // SExt or Trunc instructions. |
| 3418 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3419 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 3420 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3421 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3422 | |
| 3423 | // Regular instruction. |
| 3424 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3425 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3426 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3427 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3428 | } |
| 3429 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3430 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3431 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3432 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3433 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3434 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3435 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 3436 | // get through it and this method should not be called. |
| 3437 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3438 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3439 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3440 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3441 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3442 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3443 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3444 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3445 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 3446 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 3447 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3448 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3449 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3450 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 3451 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3452 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 3453 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3454 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3455 | |
| 3456 | // Remove dead code. |
| 3457 | if (SExtOpnd->use_empty()) |
| 3458 | TPT.eraseInstruction(SExtOpnd); |
| 3459 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3460 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3461 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3462 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3463 | if (ExtInst) { |
| 3464 | if (Exts) |
| 3465 | Exts->push_back(ExtInst); |
| 3466 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 3467 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3468 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3469 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3470 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3471 | // At this point we have: ext ty opnd to ty. |
| 3472 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 3473 | Value *NextVal = ExtInst->getOperand(0); |
| 3474 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3475 | return NextVal; |
| 3476 | } |
| 3477 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3478 | Value *TypePromotionHelper::promoteOperandForOther( |
| 3479 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3480 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3481 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3482 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 3483 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3484 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3485 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3486 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3487 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3488 | if (!ExtOpnd->hasOneUse()) { |
| 3489 | // ExtOpnd will be promoted. |
| 3490 | // 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] | 3491 | // promoted version. |
| 3492 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3493 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3494 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 3495 | ITrunc->removeFromParent(); |
| 3496 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3497 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3498 | if (Truncs) |
| 3499 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3500 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3501 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3502 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3503 | // 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] | 3504 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3505 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3506 | } |
| 3507 | |
| 3508 | // Get through the Instruction: |
| 3509 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3510 | // 2. Replace the uses of Ext by Inst. |
| 3511 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3512 | |
| 3513 | // Remember the original type of the instruction before promotion. |
| 3514 | // 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] | 3515 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 3516 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3517 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3518 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3519 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3520 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3521 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3522 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3523 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3524 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 3525 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3526 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3527 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 3528 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 3529 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3530 | DEBUG(dbgs() << "No need to propagate\n"); |
| 3531 | continue; |
| 3532 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3533 | // Check if we can statically extend the operand. |
| 3534 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3535 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3536 | DEBUG(dbgs() << "Statically extend\n"); |
| 3537 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3538 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3539 | : Cst->getValue().zext(BitWidth); |
| 3540 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3541 | continue; |
| 3542 | } |
| 3543 | // UndefValue are typed, so we have to statically sign extend them. |
| 3544 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3545 | DEBUG(dbgs() << "Statically extend\n"); |
| 3546 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3547 | continue; |
| 3548 | } |
| 3549 | |
| 3550 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3551 | // Check if Ext was reused to extend an operand. |
| 3552 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3553 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3554 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3555 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3556 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3557 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3558 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3559 | continue; |
| 3560 | } |
| 3561 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3562 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3563 | if (Exts) |
| 3564 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3565 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3566 | |
| 3567 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3568 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3569 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3570 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3571 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3572 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3573 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3574 | if (ExtForOpnd == Ext) { |
| 3575 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 3576 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3577 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3578 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3579 | } |
| 3580 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3581 | /// 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] | 3582 | /// \p NewCost gives the cost of extension instructions created by the |
| 3583 | /// promotion. |
| 3584 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3585 | /// plus the number of instructions that have been |
| 3586 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3587 | /// \p PromotedOperand is the value that has been promoted. |
| 3588 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3589 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3590 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 3591 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 3592 | // The cost of the new extensions is greater than the cost of the |
| 3593 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3594 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3595 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3596 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3597 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3598 | return true; |
| 3599 | // The promotion is neutral but it may help folding the sign extension in |
| 3600 | // loads for instance. |
| 3601 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3602 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3603 | } |
| 3604 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3605 | /// 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] | 3606 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3607 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3608 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3609 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3610 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3611 | /// because it has been moved away. |
| 3612 | /// Thus AddrInst must not be added in the matched instructions. |
| 3613 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3614 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3615 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3616 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3617 | unsigned Depth, |
| 3618 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3619 | // Avoid exponential behavior on extremely deep expression trees. |
| 3620 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3621 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3622 | // By default, all matched instructions stay in place. |
| 3623 | if (MovedAway) |
| 3624 | *MovedAway = false; |
| 3625 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3626 | switch (Opcode) { |
| 3627 | case Instruction::PtrToInt: |
| 3628 | // 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] | 3629 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3630 | case Instruction::IntToPtr: { |
| 3631 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3632 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3633 | // 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] | 3634 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3635 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3636 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3637 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3638 | case Instruction::BitCast: |
| 3639 | // BitCast is always a noop, and we can handle it as long as it is |
| 3640 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3641 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3642 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3643 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3644 | // and we don't want to mess around with them. Assume it knows what it |
| 3645 | // is doing. |
| 3646 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3647 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3648 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3649 | case Instruction::AddrSpaceCast: { |
| 3650 | unsigned SrcAS |
| 3651 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3652 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3653 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3654 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3655 | return false; |
| 3656 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3657 | case Instruction::Add: { |
| 3658 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3659 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3660 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3661 | // Start a transaction at this point. |
| 3662 | // The LHS may match but not the RHS. |
| 3663 | // Therefore, we need a higher level restoration point to undo partially |
| 3664 | // matched operation. |
| 3665 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3666 | TPT.getRestorationPoint(); |
| 3667 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3668 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3669 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3670 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3671 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3672 | // Restore the old addr mode info. |
| 3673 | AddrMode = BackupAddrMode; |
| 3674 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3675 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3676 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3677 | // 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] | 3678 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3679 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3680 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3681 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3682 | // Otherwise we definitely can't merge the ADD in. |
| 3683 | AddrMode = BackupAddrMode; |
| 3684 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3685 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3686 | break; |
| 3687 | } |
| 3688 | //case Instruction::Or: |
| 3689 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3690 | //break; |
| 3691 | case Instruction::Mul: |
| 3692 | case Instruction::Shl: { |
| 3693 | // Can only handle X*C and X << C. |
| 3694 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3695 | if (!RHS) |
| 3696 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3697 | int64_t Scale = RHS->getSExtValue(); |
| 3698 | if (Opcode == Instruction::Shl) |
| 3699 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3700 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3701 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3702 | } |
| 3703 | case Instruction::GetElementPtr: { |
| 3704 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3705 | // one variable offset. |
| 3706 | int VariableOperand = -1; |
| 3707 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3708 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3709 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3710 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3711 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 3712 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3713 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3714 | unsigned Idx = |
| 3715 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3716 | ConstantOffset += SL->getElementOffset(Idx); |
| 3717 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3718 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3719 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3720 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3721 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3722 | // We only allow one variable index at the moment. |
| 3723 | if (VariableOperand != -1) |
| 3724 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3725 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3726 | // Remember the variable index. |
| 3727 | VariableOperand = i; |
| 3728 | VariableScale = TypeSize; |
| 3729 | } |
| 3730 | } |
| 3731 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3732 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3733 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3734 | // just add it to the disp field and check validity. |
| 3735 | if (VariableOperand == -1) { |
| 3736 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3737 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3738 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3739 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3740 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3741 | return true; |
| 3742 | } |
| 3743 | AddrMode.BaseOffs -= ConstantOffset; |
| 3744 | return false; |
| 3745 | } |
| 3746 | |
| 3747 | // Save the valid addressing mode in case we can't match. |
| 3748 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3749 | unsigned OldSize = AddrModeInsts.size(); |
| 3750 | |
| 3751 | // See if the scale and offset amount is valid for this target. |
| 3752 | AddrMode.BaseOffs += ConstantOffset; |
| 3753 | |
| 3754 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3755 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3756 | // If it couldn't be matched, just stuff the value in a register. |
| 3757 | if (AddrMode.HasBaseReg) { |
| 3758 | AddrMode = BackupAddrMode; |
| 3759 | AddrModeInsts.resize(OldSize); |
| 3760 | return false; |
| 3761 | } |
| 3762 | AddrMode.HasBaseReg = true; |
| 3763 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3764 | } |
| 3765 | |
| 3766 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3767 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3768 | Depth)) { |
| 3769 | // If it couldn't be matched, try stuffing the base into a register |
| 3770 | // instead of matching it, and retrying the match of the scale. |
| 3771 | AddrMode = BackupAddrMode; |
| 3772 | AddrModeInsts.resize(OldSize); |
| 3773 | if (AddrMode.HasBaseReg) |
| 3774 | return false; |
| 3775 | AddrMode.HasBaseReg = true; |
| 3776 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3777 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3778 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3779 | VariableScale, Depth)) { |
| 3780 | // If even that didn't work, bail. |
| 3781 | AddrMode = BackupAddrMode; |
| 3782 | AddrModeInsts.resize(OldSize); |
| 3783 | return false; |
| 3784 | } |
| 3785 | } |
| 3786 | |
| 3787 | return true; |
| 3788 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3789 | case Instruction::SExt: |
| 3790 | case Instruction::ZExt: { |
| 3791 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3792 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3793 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3794 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3795 | // 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] | 3796 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3797 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3798 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3799 | if (!TPH) |
| 3800 | return false; |
| 3801 | |
| 3802 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3803 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3804 | unsigned CreatedInstsCost = 0; |
| 3805 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3806 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3807 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3808 | // SExt has been moved away. |
| 3809 | // Thus either it will be rematched later in the recursive calls or it is |
| 3810 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3811 | // E.g., |
| 3812 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3813 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3814 | // addr = gep base, idx |
| 3815 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3816 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3817 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3818 | // addr = gep base, op <- match |
| 3819 | if (MovedAway) |
| 3820 | *MovedAway = true; |
| 3821 | |
| 3822 | assert(PromotedOperand && |
| 3823 | "TypePromotionHelper should have filtered out those cases"); |
| 3824 | |
| 3825 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3826 | unsigned OldSize = AddrModeInsts.size(); |
| 3827 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3828 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3829 | // 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] | 3830 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3831 | // 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] | 3832 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3833 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3834 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3835 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3836 | AddrMode = BackupAddrMode; |
| 3837 | AddrModeInsts.resize(OldSize); |
| 3838 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3839 | TPT.rollback(LastKnownGood); |
| 3840 | return false; |
| 3841 | } |
| 3842 | return true; |
| 3843 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3844 | } |
| 3845 | return false; |
| 3846 | } |
| 3847 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3848 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3849 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3850 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3851 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3852 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3853 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3854 | // Start a transaction at this point that we will rollback if the matching |
| 3855 | // fails. |
| 3856 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3857 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3858 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 3859 | // Fold in immediates if legal for the target. |
| 3860 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3861 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3862 | return true; |
| 3863 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 3864 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 3865 | // 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] | 3866 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3867 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3868 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3869 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3870 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3871 | } |
| 3872 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 3873 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3874 | unsigned OldSize = AddrModeInsts.size(); |
| 3875 | |
| 3876 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3877 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3878 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3879 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3880 | // to check here. |
| 3881 | if (MovedAway) |
| 3882 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3883 | // Okay, it's possible to fold this. Check to see if it is actually |
| 3884 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 3885 | // register pressure too much. |
| 3886 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3887 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3888 | AddrModeInsts.push_back(I); |
| 3889 | return true; |
| 3890 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3891 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3892 | // It isn't profitable to do this, roll back. |
| 3893 | //cerr << "NOT FOLDING: " << *I; |
| 3894 | AddrMode = BackupAddrMode; |
| 3895 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3896 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3897 | } |
| 3898 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3899 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3900 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3901 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3902 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 3903 | // Null pointer gets folded without affecting the addressing mode. |
| 3904 | return true; |
| 3905 | } |
| 3906 | |
| 3907 | // Worse case, the target should support [reg] addressing modes. :) |
| 3908 | if (!AddrMode.HasBaseReg) { |
| 3909 | AddrMode.HasBaseReg = true; |
| 3910 | AddrMode.BaseReg = Addr; |
| 3911 | // 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] | 3912 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3913 | return true; |
| 3914 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3915 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3916 | } |
| 3917 | |
| 3918 | // If the base register is already taken, see if we can do [r+r]. |
| 3919 | if (AddrMode.Scale == 0) { |
| 3920 | AddrMode.Scale = 1; |
| 3921 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3922 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3923 | return true; |
| 3924 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3925 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3926 | } |
| 3927 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3928 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3929 | return false; |
| 3930 | } |
| 3931 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3932 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 3933 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3934 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3935 | const TargetLowering &TLI, |
| 3936 | const TargetRegisterInfo &TRI) { |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3937 | const Function *F = CI->getParent()->getParent(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3938 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3939 | TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3940 | ImmutableCallSite(CI)); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3941 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3942 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3943 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3944 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3945 | // Compute the constraint code and ConstraintType to use. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3946 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3947 | |
| 3948 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 3949 | // operand, we can't fold it! |
| 3950 | if (OpInfo.CallOperandVal == OpVal && |
| 3951 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 3952 | !OpInfo.isIndirect)) |
| 3953 | return false; |
| 3954 | } |
| 3955 | |
| 3956 | return true; |
| 3957 | } |
| 3958 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3959 | /// Recursively walk all the uses of I until we find a memory use. |
| 3960 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3961 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3962 | static bool FindAllMemoryUses( |
| 3963 | Instruction *I, |
| 3964 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3965 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, |
| 3966 | const TargetLowering &TLI, const TargetRegisterInfo &TRI) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3967 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3968 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3969 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3970 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3971 | // If this is an obviously unfoldable instruction, bail out. |
| 3972 | if (!MightBeFoldableInst(I)) |
| 3973 | return true; |
| 3974 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3975 | const bool OptSize = I->getFunction()->optForSize(); |
| 3976 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3977 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3978 | for (Use &U : I->uses()) { |
| 3979 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3980 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3981 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3982 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3983 | continue; |
| 3984 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3985 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3986 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3987 | unsigned opNo = U.getOperandNo(); |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 3988 | if (opNo != StoreInst::getPointerOperandIndex()) |
| 3989 | return true; // Storing addr, not into addr. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3990 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3991 | continue; |
| 3992 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3993 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 3994 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { |
| 3995 | unsigned opNo = U.getOperandNo(); |
| 3996 | if (opNo != AtomicRMWInst::getPointerOperandIndex()) |
| 3997 | return true; // Storing addr, not into addr. |
| 3998 | MemoryUses.push_back(std::make_pair(RMW, opNo)); |
| 3999 | continue; |
| 4000 | } |
| 4001 | |
| 4002 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { |
| 4003 | unsigned opNo = U.getOperandNo(); |
| 4004 | if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) |
| 4005 | return true; // Storing addr, not into addr. |
| 4006 | MemoryUses.push_back(std::make_pair(CmpX, opNo)); |
| 4007 | continue; |
| 4008 | } |
| 4009 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4010 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4011 | // If this is a cold call, we can sink the addressing calculation into |
| 4012 | // the cold path. See optimizeCallInst |
| 4013 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 4014 | continue; |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 4015 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4016 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 4017 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4018 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4019 | // If this is a memory operand, we're cool, otherwise bail out. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4020 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4021 | return true; |
| 4022 | continue; |
| 4023 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4024 | |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4025 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4026 | return true; |
| 4027 | } |
| 4028 | |
| 4029 | return false; |
| 4030 | } |
| 4031 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 4032 | /// Return true if Val is already known to be live at the use site that we're |
| 4033 | /// folding it into. If so, there is no cost to include it in the addressing |
| 4034 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 4035 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4036 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4037 | Value *KnownLive2) { |
| 4038 | // 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] | 4039 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4040 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4041 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4042 | // All values other than instructions and arguments (e.g. constants) are live. |
| 4043 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4044 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4045 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 4046 | // true because it is just a reference to the stack/frame pointer, which is |
| 4047 | // live for the whole function. |
| 4048 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 4049 | if (AI->isStaticAlloca()) |
| 4050 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4051 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4052 | // Check to see if this value is already used in the memory instruction's |
| 4053 | // block. If so, it's already live into the block at the very least, so we |
| 4054 | // can reasonably fold it. |
| 4055 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 4056 | } |
| 4057 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4058 | /// It is possible for the addressing mode of the machine to fold the specified |
| 4059 | /// instruction into a load or store that ultimately uses it. |
| 4060 | /// However, the specified instruction has multiple uses. |
| 4061 | /// Given this, it may actually increase register pressure to fold it |
| 4062 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4063 | /// |
| 4064 | /// X = ... |
| 4065 | /// Y = X+1 |
| 4066 | /// use(Y) -> nonload/store |
| 4067 | /// Z = Y+1 |
| 4068 | /// load Z |
| 4069 | /// |
| 4070 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 4071 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 4072 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 4073 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 4074 | /// number of computations either. |
| 4075 | /// |
| 4076 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 4077 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 4078 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 4079 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4080 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4081 | ExtAddrMode &AMAfter) { |
| 4082 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4083 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4084 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 4085 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 4086 | // the set of registers referenced by AMAfter and subtract out those |
| 4087 | // referenced by AMBefore: this is the set of values which folding in this |
| 4088 | // address extends the lifetime of. |
| 4089 | // |
| 4090 | // Note that there are only two potential values being referenced here, |
| 4091 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 4092 | // folded immediates). |
| 4093 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4094 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4095 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 4096 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4097 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4098 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4099 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4100 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4101 | |
| 4102 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 4103 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4104 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4105 | return true; |
| 4106 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4107 | // If all uses of this instruction can have the address mode sunk into them, |
| 4108 | // we can remove the addressing mode and effectively trade one live register |
| 4109 | // for another (at worst.) In this context, folding an addressing mode into |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 4110 | // the use is just a particularly nice way of sinking it. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4111 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 4112 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4113 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4114 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4115 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4116 | // Now that we know that all uses of this instruction are part of a chain of |
| 4117 | // computation involving only operations that could theoretically be folded |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4118 | // into a memory use, loop over each of these memory operation uses and see |
| 4119 | // if they could *actually* fold the instruction. The assumption is that |
| 4120 | // addressing modes are cheap and that duplicating the computation involved |
| 4121 | // many times is worthwhile, even on a fastpath. For sinking candidates |
| 4122 | // (i.e. cold call sites), this serves as a way to prevent excessive code |
| 4123 | // growth since most architectures have some reasonable small and fast way to |
| 4124 | // compute an effective address. (i.e LEA on x86) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4125 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 4126 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 4127 | Instruction *User = MemoryUses[i].first; |
| 4128 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4129 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4130 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 4131 | // know what it accesses. |
| 4132 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4133 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 4134 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4135 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4136 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 4137 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4138 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4139 | // Do a match against the root of this address, ignoring profitability. This |
| 4140 | // will tell us if the addressing mode for the memory operation will |
| 4141 | // *actually* cover the shared instruction. |
| 4142 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4143 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4144 | TPT.getRestorationPoint(); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4145 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, |
| 4146 | AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4147 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4148 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4149 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4150 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4151 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 4152 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4153 | // The match was to check the profitability, the changes made are not |
| 4154 | // part of the original matcher. Therefore, they should be dropped |
| 4155 | // otherwise the original matcher will not present the right state. |
| 4156 | TPT.rollback(LastKnownGood); |
| 4157 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4158 | // 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] | 4159 | if (!is_contained(MatchedAddrModeInsts, I)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4160 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4161 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4162 | MatchedAddrModeInsts.clear(); |
| 4163 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4164 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4165 | return true; |
| 4166 | } |
| 4167 | |
| 4168 | } // end anonymous namespace |
| 4169 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4170 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4171 | /// different basic block than BB. |
| 4172 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 4173 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4174 | return I->getParent() != BB; |
| 4175 | return false; |
| 4176 | } |
| 4177 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4178 | /// Sink addressing mode computation immediate before MemoryInst if doing so |
| 4179 | /// can be done without increasing register pressure. The need for the |
| 4180 | /// register pressure constraint means this can end up being an all or nothing |
| 4181 | /// decision for all uses of the same addressing computation. |
| 4182 | /// |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4183 | /// Load and Store Instructions often have addressing modes that can do |
| 4184 | /// significant amounts of computation. As such, instruction selection will try |
| 4185 | /// to get the load or store to do as much computation as possible for the |
| 4186 | /// program. The problem is that isel can only see within a single block. As |
| 4187 | /// 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] | 4188 | /// |
| 4189 | /// 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] | 4190 | /// operands. It's also used to sink addressing computations feeding into cold |
| 4191 | /// call sites into their (cold) basic block. |
| 4192 | /// |
| 4193 | /// The motivation for handling sinking into cold blocks is that doing so can |
| 4194 | /// both enable other address mode sinking (by satisfying the register pressure |
| 4195 | /// constraint above), and reduce register pressure globally (by removing the |
| 4196 | /// addressing mode computation from the fast path entirely.). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4197 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4198 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4199 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4200 | |
| 4201 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4202 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 4203 | SmallVector<Value*, 8> worklist; |
| 4204 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4205 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4206 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4207 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 4208 | // the addressing mode obtained from the non-PHI roots of the graph |
| 4209 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4210 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4211 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4212 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4213 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 4214 | ExtAddrMode AddrMode; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4215 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4216 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4217 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4218 | while (!worklist.empty()) { |
| 4219 | Value *V = worklist.back(); |
| 4220 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4221 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4222 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4223 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4224 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4225 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4226 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4227 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4228 | // For a PHI node, push all of its incoming values. |
| 4229 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 4230 | for (Value *IncValue : P->incoming_values()) |
| 4231 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4232 | continue; |
| 4233 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4234 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4235 | // For non-PHIs, determine the addressing mode being computed. Note that |
| 4236 | // the result may differ depending on what other uses our candidate |
| 4237 | // addressing instructions might have. |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4238 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4239 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4240 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4241 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4242 | |
| 4243 | // This check is broken into two cases with very similar code to avoid using |
| 4244 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 4245 | // calling getNumUses() unconditionally caused a significant compile-time |
| 4246 | // regression. |
| 4247 | if (!Consensus) { |
| 4248 | Consensus = V; |
| 4249 | AddrMode = NewAddrMode; |
| 4250 | AddrModeInsts = NewAddrModeInsts; |
| 4251 | continue; |
| 4252 | } else if (NewAddrMode == AddrMode) { |
| 4253 | if (!IsNumUsesConsensusValid) { |
| 4254 | NumUsesConsensus = Consensus->getNumUses(); |
| 4255 | IsNumUsesConsensusValid = true; |
| 4256 | } |
| 4257 | |
| 4258 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 4259 | // for all other roots of the PHI traversal. Also, when choosing one |
| 4260 | // such root as representative, select the one with the most uses in order |
| 4261 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 4262 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4263 | unsigned NumUses = V->getNumUses(); |
| 4264 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4265 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4266 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4267 | AddrModeInsts = NewAddrModeInsts; |
| 4268 | } |
| 4269 | continue; |
| 4270 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4271 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4272 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4273 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4274 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4275 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4276 | // If the addressing mode couldn't be determined, or if multiple different |
| 4277 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4278 | if (!Consensus) { |
| 4279 | TPT.rollback(LastKnownGood); |
| 4280 | return false; |
| 4281 | } |
| 4282 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4283 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4284 | // 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] | 4285 | if (none_of(AddrModeInsts, [&](Value *V) { |
| 4286 | return IsNonLocalValue(V, MemoryInst->getParent()); |
| 4287 | })) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4288 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4289 | return false; |
| 4290 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4291 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4292 | // Insert this computation right after this user. Since our caller is |
| 4293 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 4294 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4295 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4296 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4297 | // Now that we determined the addressing expression we want to use and know |
| 4298 | // that we have to sink it into this block. Check to see if we have already |
| 4299 | // done this for some other load/store instr in this block. If so, reuse the |
| 4300 | // computation. |
| 4301 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 4302 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4303 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4304 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4305 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4306 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 4307 | } else if (AddrSinkUsingGEPs || |
| 4308 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4309 | SubtargetInfo->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4310 | // By default, we use the GEP-based method when AA is used later. This |
| 4311 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 4312 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4313 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4314 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4315 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4316 | |
| 4317 | // First, find the pointer. |
| 4318 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 4319 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4320 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4321 | } |
| 4322 | |
| 4323 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 4324 | // We can't add more than one pointer together, nor can we scale a |
| 4325 | // pointer (both of which seem meaningless). |
| 4326 | if (ResultPtr || AddrMode.Scale != 1) |
| 4327 | return false; |
| 4328 | |
| 4329 | ResultPtr = AddrMode.ScaledReg; |
| 4330 | AddrMode.Scale = 0; |
| 4331 | } |
| 4332 | |
| 4333 | if (AddrMode.BaseGV) { |
| 4334 | if (ResultPtr) |
| 4335 | return false; |
| 4336 | |
| 4337 | ResultPtr = AddrMode.BaseGV; |
| 4338 | } |
| 4339 | |
| 4340 | // If the real base value actually came from an inttoptr, then the matcher |
| 4341 | // will look through it and provide only the integer value. In that case, |
| 4342 | // use it here. |
| 4343 | if (!ResultPtr && AddrMode.BaseReg) { |
| 4344 | ResultPtr = |
| 4345 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4346 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4347 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 4348 | ResultPtr = |
| 4349 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 4350 | AddrMode.Scale = 0; |
| 4351 | } |
| 4352 | |
| 4353 | if (!ResultPtr && |
| 4354 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 4355 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 4356 | } else if (!ResultPtr) { |
| 4357 | return false; |
| 4358 | } else { |
| 4359 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4360 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 4361 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4362 | |
| 4363 | // Start with the base register. Do this first so that subsequent address |
| 4364 | // matching finds it last, which will prevent it from trying to match it |
| 4365 | // as the scaled value in case it happens to be a mul. That would be |
| 4366 | // problematic if we've sunk a different mul for the scale, because then |
| 4367 | // we'd end up sinking both muls. |
| 4368 | if (AddrMode.BaseReg) { |
| 4369 | Value *V = AddrMode.BaseReg; |
| 4370 | if (V->getType() != IntPtrTy) |
| 4371 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 4372 | |
| 4373 | ResultIndex = V; |
| 4374 | } |
| 4375 | |
| 4376 | // Add the scale value. |
| 4377 | if (AddrMode.Scale) { |
| 4378 | Value *V = AddrMode.ScaledReg; |
| 4379 | if (V->getType() == IntPtrTy) { |
| 4380 | // done. |
| 4381 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4382 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 4383 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 4384 | } else { |
| 4385 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4386 | // required to create it did not overflow before we extend it. Since |
| 4387 | // the original IR value was tossed in favor of a constant back when |
| 4388 | // the AddrMode was created we need to bail out gracefully if widths |
| 4389 | // do not match instead of extending it. |
| 4390 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 4391 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 4392 | I->eraseFromParent(); |
| 4393 | return false; |
| 4394 | } |
| 4395 | |
| 4396 | if (AddrMode.Scale != 1) |
| 4397 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4398 | "sunkaddr"); |
| 4399 | if (ResultIndex) |
| 4400 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 4401 | else |
| 4402 | ResultIndex = V; |
| 4403 | } |
| 4404 | |
| 4405 | // Add in the Base Offset if present. |
| 4406 | if (AddrMode.BaseOffs) { |
| 4407 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 4408 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 4409 | // We need to add this separately from the scale above to help with |
| 4410 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4411 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4412 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4413 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4414 | } |
| 4415 | |
| 4416 | ResultIndex = V; |
| 4417 | } |
| 4418 | |
| 4419 | if (!ResultIndex) { |
| 4420 | SunkAddr = ResultPtr; |
| 4421 | } else { |
| 4422 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4423 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4424 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4425 | } |
| 4426 | |
| 4427 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4428 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4429 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4430 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4431 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4432 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4433 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4434 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4435 | |
| 4436 | // Start with the base register. Do this first so that subsequent address |
| 4437 | // matching finds it last, which will prevent it from trying to match it |
| 4438 | // as the scaled value in case it happens to be a mul. That would be |
| 4439 | // problematic if we've sunk a different mul for the scale, because then |
| 4440 | // we'd end up sinking both muls. |
| 4441 | if (AddrMode.BaseReg) { |
| 4442 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4443 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4444 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4445 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4446 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4447 | Result = V; |
| 4448 | } |
| 4449 | |
| 4450 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4451 | if (AddrMode.Scale) { |
| 4452 | Value *V = AddrMode.ScaledReg; |
| 4453 | if (V->getType() == IntPtrTy) { |
| 4454 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4455 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4456 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4457 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4458 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4459 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4460 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4461 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4462 | // required to create it did not overflow before we extend it. Since |
| 4463 | // the original IR value was tossed in favor of a constant back when |
| 4464 | // the AddrMode was created we need to bail out gracefully if widths |
| 4465 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 4466 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 4467 | if (I && (Result != AddrMode.BaseReg)) |
| 4468 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4469 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4470 | } |
| 4471 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4472 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4473 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4474 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4475 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4476 | else |
| 4477 | Result = V; |
| 4478 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4479 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4480 | // Add in the BaseGV if present. |
| 4481 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4482 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4483 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4484 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4485 | else |
| 4486 | Result = V; |
| 4487 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4488 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4489 | // Add in the Base Offset if present. |
| 4490 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4491 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4492 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4493 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4494 | else |
| 4495 | Result = V; |
| 4496 | } |
| 4497 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4498 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 4499 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4500 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4501 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4502 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4503 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4504 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4505 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4506 | // If we have no uses, recursively delete the value and all dead instructions |
| 4507 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4508 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4509 | // This can cause recursive deletion, which can invalidate our iterator. |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 4510 | // Use a WeakTrackingVH to hold onto it in case this happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4511 | Value *CurValue = &*CurInstIterator; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 4512 | WeakTrackingVH IterHandle(CurValue); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4513 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4514 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 4515 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4516 | |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4517 | if (IterHandle != CurValue) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4518 | // If the iterator instruction was recursively deleted, start over at the |
| 4519 | // start of the block. |
| 4520 | CurInstIterator = BB->begin(); |
| 4521 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4522 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 4523 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4524 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4525 | return true; |
| 4526 | } |
| 4527 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4528 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 4529 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4530 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4531 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4532 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4533 | const TargetRegisterInfo *TRI = |
| 4534 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4535 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 4536 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4537 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 4538 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4539 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4540 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4541 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 4542 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4543 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 4544 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 4545 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4546 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4547 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4548 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 4549 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4550 | } |
| 4551 | |
| 4552 | return MadeChange; |
| 4553 | } |
| 4554 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4555 | /// \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] | 4556 | /// sign extensions. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4557 | static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { |
| 4558 | assert(!Val->use_empty() && "Input must have at least one use"); |
| 4559 | const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4560 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 4561 | Type *ExtTy = FirstUser->getType(); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4562 | for (const User *U : Val->users()) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4563 | const Instruction *UI = cast<Instruction>(U); |
| 4564 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4565 | return false; |
| 4566 | Type *CurTy = UI->getType(); |
| 4567 | // Same input and output types: Same instruction after CSE. |
| 4568 | if (CurTy == ExtTy) |
| 4569 | continue; |
| 4570 | |
| 4571 | // If IsSExt is true, we are in this situation: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4572 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4573 | // b = sext ty1 a to ty2 |
| 4574 | // c = sext ty1 a to ty3 |
| 4575 | // Assuming ty2 is shorter than ty3, this could be turned into: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4576 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4577 | // b = sext ty1 a to ty2 |
| 4578 | // c = sext ty2 b to ty3 |
| 4579 | // However, the last sext is not free. |
| 4580 | if (IsSExt) |
| 4581 | return false; |
| 4582 | |
| 4583 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4584 | // In that case, we would not account for a different use. |
| 4585 | Type *NarrowTy; |
| 4586 | Type *LargeTy; |
| 4587 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4588 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4589 | NarrowTy = CurTy; |
| 4590 | LargeTy = ExtTy; |
| 4591 | } else { |
| 4592 | NarrowTy = ExtTy; |
| 4593 | LargeTy = CurTy; |
| 4594 | } |
| 4595 | |
| 4596 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4597 | return false; |
| 4598 | } |
| 4599 | // All uses are the same or can be derived from one another for free. |
| 4600 | return true; |
| 4601 | } |
| 4602 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4603 | /// \brief Try to speculatively promote extensions in \p Exts and continue |
| 4604 | /// promoting through newly promoted operands recursively as far as doing so is |
| 4605 | /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. |
| 4606 | /// When some promotion happened, \p TPT contains the proper state to revert |
| 4607 | /// them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4608 | /// |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4609 | /// \return true if some promotion happened, false otherwise. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4610 | bool CodeGenPrepare::tryToPromoteExts( |
| 4611 | TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, |
| 4612 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 4613 | unsigned CreatedInstsCost) { |
| 4614 | bool Promoted = false; |
| 4615 | |
| 4616 | // Iterate over all the extensions to try to promote them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4617 | for (auto I : Exts) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4618 | // Early check if we directly have ext(load). |
| 4619 | if (isa<LoadInst>(I->getOperand(0))) { |
| 4620 | ProfitablyMovedExts.push_back(I); |
| 4621 | continue; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4622 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4623 | |
| 4624 | // Check whether or not we want to do any promotion. The reason we have |
| 4625 | // this check inside the for loop is to catch the case where an extension |
| 4626 | // is directly fed by a load because in such case the extension can be moved |
| 4627 | // up without any promotion on its operands. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4628 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4629 | return false; |
| 4630 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4631 | // Get the action to perform the promotion. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4632 | TypePromotionHelper::Action TPH = |
| 4633 | TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4634 | // Check if we can promote. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4635 | if (!TPH) { |
| 4636 | // Save the current extension as we cannot move up through its operand. |
| 4637 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4638 | continue; |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4639 | } |
| 4640 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4641 | // Save the current state. |
| 4642 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4643 | TPT.getRestorationPoint(); |
| 4644 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4645 | unsigned NewCreatedInstsCost = 0; |
| 4646 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4647 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4648 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4649 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4650 | assert(PromotedVal && |
| 4651 | "TypePromotionHelper should have filtered out those cases"); |
| 4652 | |
| 4653 | // We would be able to merge only one extension in a load. |
| 4654 | // Therefore, if we have more than 1 new extension we heuristically |
| 4655 | // cut this search path, because it means we degrade the code quality. |
| 4656 | // With exactly 2, the transformation is neutral, because we will merge |
| 4657 | // one extension but leave one. However, we optimistically keep going, |
| 4658 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4659 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4660 | // 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] | 4661 | // conservatively ceiling it to 0. |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4662 | TotalCreatedInstsCost = |
| 4663 | std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4664 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4665 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4666 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4667 | // This promotion is not profitable, rollback to the previous state, and |
| 4668 | // save the current extension in ProfitablyMovedExts as the latest |
| 4669 | // speculative promotion turned out to be unprofitable. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4670 | TPT.rollback(LastKnownGood); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4671 | ProfitablyMovedExts.push_back(I); |
| 4672 | continue; |
| 4673 | } |
| 4674 | // Continue promoting NewExts as far as doing so is profitable. |
| 4675 | SmallVector<Instruction *, 2> NewlyMovedExts; |
| 4676 | (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); |
| 4677 | bool NewPromoted = false; |
| 4678 | for (auto ExtInst : NewlyMovedExts) { |
| 4679 | Instruction *MovedExt = cast<Instruction>(ExtInst); |
| 4680 | Value *ExtOperand = MovedExt->getOperand(0); |
| 4681 | // If we have reached to a load, we need this extra profitability check |
| 4682 | // as it could potentially be merged into an ext(load). |
| 4683 | if (isa<LoadInst>(ExtOperand) && |
| 4684 | !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
| 4685 | (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) |
| 4686 | continue; |
| 4687 | |
| 4688 | ProfitablyMovedExts.push_back(MovedExt); |
| 4689 | NewPromoted = true; |
| 4690 | } |
| 4691 | |
| 4692 | // If none of speculative promotions for NewExts is profitable, rollback |
| 4693 | // and save the current extension (I) as the last profitable extension. |
| 4694 | if (!NewPromoted) { |
| 4695 | TPT.rollback(LastKnownGood); |
| 4696 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4697 | continue; |
| 4698 | } |
| 4699 | // The promotion is profitable. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4700 | Promoted = true; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4701 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4702 | return Promoted; |
| 4703 | } |
| 4704 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4705 | /// Merging redundant sexts when one is dominating the other. |
| 4706 | bool CodeGenPrepare::mergeSExts(Function &F) { |
| 4707 | DominatorTree DT(F); |
| 4708 | bool Changed = false; |
| 4709 | for (auto &Entry : ValToSExtendedUses) { |
| 4710 | SExts &Insts = Entry.second; |
| 4711 | SExts CurPts; |
| 4712 | for (Instruction *Inst : Insts) { |
| 4713 | if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || |
| 4714 | Inst->getOperand(0) != Entry.first) |
| 4715 | continue; |
| 4716 | bool inserted = false; |
| 4717 | for (auto &Pt : CurPts) { |
| 4718 | if (DT.dominates(Inst, Pt)) { |
| 4719 | Pt->replaceAllUsesWith(Inst); |
| 4720 | RemovedInsts.insert(Pt); |
| 4721 | Pt->removeFromParent(); |
| 4722 | Pt = Inst; |
| 4723 | inserted = true; |
| 4724 | Changed = true; |
| 4725 | break; |
| 4726 | } |
| 4727 | if (!DT.dominates(Pt, Inst)) |
| 4728 | // Give up if we need to merge in a common dominator as the |
| 4729 | // expermients show it is not profitable. |
| 4730 | continue; |
| 4731 | Inst->replaceAllUsesWith(Pt); |
| 4732 | RemovedInsts.insert(Inst); |
| 4733 | Inst->removeFromParent(); |
| 4734 | inserted = true; |
| 4735 | Changed = true; |
| 4736 | break; |
| 4737 | } |
| 4738 | if (!inserted) |
| 4739 | CurPts.push_back(Inst); |
| 4740 | } |
| 4741 | } |
| 4742 | return Changed; |
| 4743 | } |
| 4744 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4745 | /// Return true, if an ext(load) can be formed from an extension in |
| 4746 | /// \p MovedExts. |
| 4747 | bool CodeGenPrepare::canFormExtLd( |
| 4748 | const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, |
| 4749 | Instruction *&Inst, bool HasPromoted) { |
| 4750 | for (auto *MovedExtInst : MovedExts) { |
| 4751 | if (isa<LoadInst>(MovedExtInst->getOperand(0))) { |
| 4752 | LI = cast<LoadInst>(MovedExtInst->getOperand(0)); |
| 4753 | Inst = MovedExtInst; |
| 4754 | break; |
| 4755 | } |
| 4756 | } |
| 4757 | if (!LI) |
| 4758 | return false; |
| 4759 | |
| 4760 | // If they're already in the same block, there's nothing to do. |
| 4761 | // Make the cheap checks first if we did not promote. |
| 4762 | // If we promoted, we need to check if it is indeed profitable. |
| 4763 | if (!HasPromoted && LI->getParent() == Inst->getParent()) |
| 4764 | return false; |
| 4765 | |
| 4766 | EVT VT = TLI->getValueType(*DL, Inst->getType()); |
| 4767 | EVT LoadVT = TLI->getValueType(*DL, LI->getType()); |
| 4768 | |
| 4769 | // If the load has other users and the truncate is not free, this probably |
| 4770 | // isn't worthwhile. |
| 4771 | if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
| 4772 | !TLI->isTruncateFree(Inst->getType(), LI->getType())) |
| 4773 | return false; |
| 4774 | |
| 4775 | // Check whether the target supports casts folded into loads. |
| 4776 | unsigned LType; |
| 4777 | if (isa<ZExtInst>(Inst)) |
| 4778 | LType = ISD::ZEXTLOAD; |
| 4779 | else { |
| 4780 | assert(isa<SExtInst>(Inst) && "Unexpected ext type!"); |
| 4781 | LType = ISD::SEXTLOAD; |
| 4782 | } |
| 4783 | |
| 4784 | return TLI->isLoadExtLegal(LType, VT, LoadVT); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4785 | } |
| 4786 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4787 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4788 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4789 | /// extend into the load. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4790 | /// |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4791 | /// E.g., |
| 4792 | /// \code |
| 4793 | /// %ld = load i32* %addr |
| 4794 | /// %add = add nuw i32 %ld, 4 |
| 4795 | /// %zext = zext i32 %add to i64 |
| 4796 | // \endcode |
| 4797 | /// => |
| 4798 | /// \code |
| 4799 | /// %ld = load i32* %addr |
| 4800 | /// %zext = zext i32 %ld to i64 |
| 4801 | /// %add = add nuw i64 %zext, 4 |
| 4802 | /// \encode |
| 4803 | /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which |
| 4804 | /// allow us to match zext(load i32*) to i64. |
| 4805 | /// |
| 4806 | /// Also, try to promote the computations used to obtain a sign extended |
| 4807 | /// value used into memory accesses. |
| 4808 | /// E.g., |
| 4809 | /// \code |
| 4810 | /// a = add nsw i32 b, 3 |
| 4811 | /// d = sext i32 a to i64 |
| 4812 | /// e = getelementptr ..., i64 d |
| 4813 | /// \endcode |
| 4814 | /// => |
| 4815 | /// \code |
| 4816 | /// f = sext i32 b to i64 |
| 4817 | /// a = add nsw i64 f, 3 |
| 4818 | /// e = getelementptr ..., i64 a |
| 4819 | /// \endcode |
| 4820 | /// |
| 4821 | /// \p Inst[in/out] the extension may be modified during the process if some |
| 4822 | /// promotions apply. |
| 4823 | bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { |
| 4824 | // ExtLoad formation and address type promotion infrastructure requires TLI to |
| 4825 | // be effective. |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 4826 | if (!TLI) |
| 4827 | return false; |
| 4828 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4829 | bool AllowPromotionWithoutCommonHeader = false; |
| 4830 | /// See if it is an interesting sext operations for the address type |
| 4831 | /// promotion before trying to promote it, e.g., the ones with the right |
| 4832 | /// type and used in memory accesses. |
| 4833 | bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( |
| 4834 | *Inst, AllowPromotionWithoutCommonHeader); |
| 4835 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4836 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4837 | TPT.getRestorationPoint(); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4838 | SmallVector<Instruction *, 1> Exts; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4839 | SmallVector<Instruction *, 2> SpeculativelyMovedExts; |
| 4840 | Exts.push_back(Inst); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4841 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4842 | bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4843 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4844 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4845 | LoadInst *LI = nullptr; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4846 | Instruction *ExtFedByLoad; |
| 4847 | |
| 4848 | // Try to promote a chain of computation if it allows to form an extended |
| 4849 | // load. |
| 4850 | if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { |
| 4851 | assert(LI && ExtFedByLoad && "Expect a valid load and extension"); |
| 4852 | TPT.commit(); |
| 4853 | // Move the extend into the same block as the load |
| 4854 | ExtFedByLoad->removeFromParent(); |
| 4855 | ExtFedByLoad->insertAfter(LI); |
| 4856 | // CGP does not check if the zext would be speculatively executed when moved |
| 4857 | // to the same basic block as the load. Preserving its original location |
| 4858 | // would pessimize the debugging experience, as well as negatively impact |
| 4859 | // the quality of sample pgo. We don't want to use "line 0" as that has a |
| 4860 | // size cost in the line-table section and logically the zext can be seen as |
| 4861 | // part of the load. Therefore we conservatively reuse the same debug |
| 4862 | // location for the load and the zext. |
| 4863 | ExtFedByLoad->setDebugLoc(LI->getDebugLoc()); |
| 4864 | ++NumExtsMoved; |
| 4865 | Inst = ExtFedByLoad; |
| 4866 | return true; |
| 4867 | } |
| 4868 | |
| 4869 | // Continue promoting SExts if known as considerable depending on targets. |
| 4870 | if (ATPConsiderable && |
| 4871 | performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, |
| 4872 | HasPromoted, TPT, SpeculativelyMovedExts)) |
| 4873 | return true; |
| 4874 | |
| 4875 | TPT.rollback(LastKnownGood); |
| 4876 | return false; |
| 4877 | } |
| 4878 | |
| 4879 | // Perform address type promotion if doing so is profitable. |
| 4880 | // If AllowPromotionWithoutCommonHeader == false, we should find other sext |
| 4881 | // instructions that sign extended the same initial value. However, if |
| 4882 | // AllowPromotionWithoutCommonHeader == true, we expect promoting the |
| 4883 | // extension is just profitable. |
| 4884 | bool CodeGenPrepare::performAddressTypePromotion( |
| 4885 | Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, |
| 4886 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 4887 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { |
| 4888 | bool Promoted = false; |
| 4889 | SmallPtrSet<Instruction *, 1> UnhandledExts; |
| 4890 | bool AllSeenFirst = true; |
| 4891 | for (auto I : SpeculativelyMovedExts) { |
| 4892 | Value *HeadOfChain = I->getOperand(0); |
| 4893 | DenseMap<Value *, Instruction *>::iterator AlreadySeen = |
| 4894 | SeenChainsForSExt.find(HeadOfChain); |
| 4895 | // If there is an unhandled SExt which has the same header, try to promote |
| 4896 | // it as well. |
| 4897 | if (AlreadySeen != SeenChainsForSExt.end()) { |
| 4898 | if (AlreadySeen->second != nullptr) |
| 4899 | UnhandledExts.insert(AlreadySeen->second); |
| 4900 | AllSeenFirst = false; |
| 4901 | } |
| 4902 | } |
| 4903 | |
| 4904 | if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && |
| 4905 | SpeculativelyMovedExts.size() == 1)) { |
| 4906 | TPT.commit(); |
| 4907 | if (HasPromoted) |
| 4908 | Promoted = true; |
| 4909 | for (auto I : SpeculativelyMovedExts) { |
| 4910 | Value *HeadOfChain = I->getOperand(0); |
| 4911 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 4912 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 4913 | } |
| 4914 | // Update Inst as promotion happen. |
| 4915 | Inst = SpeculativelyMovedExts.pop_back_val(); |
| 4916 | } else { |
| 4917 | // This is the first chain visited from the header, keep the current chain |
| 4918 | // as unhandled. Defer to promote this until we encounter another SExt |
| 4919 | // chain derived from the same header. |
| 4920 | for (auto I : SpeculativelyMovedExts) { |
| 4921 | Value *HeadOfChain = I->getOperand(0); |
| 4922 | SeenChainsForSExt[HeadOfChain] = Inst; |
| 4923 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4924 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4925 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4926 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4927 | if (!AllSeenFirst && !UnhandledExts.empty()) |
| 4928 | for (auto VisitedSExt : UnhandledExts) { |
| 4929 | if (RemovedInsts.count(VisitedSExt)) |
| 4930 | continue; |
| 4931 | TypePromotionTransaction TPT(RemovedInsts); |
| 4932 | SmallVector<Instruction *, 1> Exts; |
| 4933 | SmallVector<Instruction *, 2> Chains; |
| 4934 | Exts.push_back(VisitedSExt); |
| 4935 | bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); |
| 4936 | TPT.commit(); |
| 4937 | if (HasPromoted) |
| 4938 | Promoted = true; |
| 4939 | for (auto I : Chains) { |
| 4940 | Value *HeadOfChain = I->getOperand(0); |
| 4941 | // Mark this as handled. |
| 4942 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 4943 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 4944 | } |
| 4945 | } |
| 4946 | return Promoted; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4947 | } |
| 4948 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4949 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4950 | BasicBlock *DefBB = I->getParent(); |
| 4951 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 4952 | // 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] | 4953 | // other uses of the source with result of extension. |
| 4954 | Value *Src = I->getOperand(0); |
| 4955 | if (Src->hasOneUse()) |
| 4956 | return false; |
| 4957 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 4958 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 4959 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4960 | return false; |
| 4961 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4962 | // 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] | 4963 | // this block. |
| 4964 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4965 | return false; |
| 4966 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4967 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4968 | for (User *U : I->users()) { |
| 4969 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4970 | |
| 4971 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4972 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4973 | if (UserBB == DefBB) continue; |
| 4974 | DefIsLiveOut = true; |
| 4975 | break; |
| 4976 | } |
| 4977 | if (!DefIsLiveOut) |
| 4978 | return false; |
| 4979 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 4980 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4981 | for (User *U : Src->users()) { |
| 4982 | Instruction *UI = cast<Instruction>(U); |
| 4983 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4984 | if (UserBB == DefBB) continue; |
| 4985 | // Be conservative. We don't want this xform to end up introducing |
| 4986 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4987 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4988 | return false; |
| 4989 | } |
| 4990 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4991 | // InsertedTruncs - Only insert one trunc in each block once. |
| 4992 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 4993 | |
| 4994 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4995 | for (Use &U : Src->uses()) { |
| 4996 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4997 | |
| 4998 | // Figure out which BB this ext is used in. |
| 4999 | BasicBlock *UserBB = User->getParent(); |
| 5000 | if (UserBB == DefBB) continue; |
| 5001 | |
| 5002 | // Both src and def are live in this block. Rewrite the use. |
| 5003 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 5004 | |
| 5005 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 5006 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5007 | assert(InsertPt != UserBB->end()); |
| 5008 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5009 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5010 | } |
| 5011 | |
| 5012 | // 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] | 5013 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 5014 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5015 | MadeChange = true; |
| 5016 | } |
| 5017 | |
| 5018 | return MadeChange; |
| 5019 | } |
| 5020 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5021 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 5022 | // just after the load if the target can fold this into one extload instruction, |
| 5023 | // with the hope of eliminating some of the other later "and" instructions using |
| 5024 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 5025 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 5026 | // path from the load goes through a phi) are left for isel to potentially |
| 5027 | // remove. |
| 5028 | // |
| 5029 | // For example: |
| 5030 | // |
| 5031 | // b0: |
| 5032 | // x = load i32 |
| 5033 | // ... |
| 5034 | // b1: |
| 5035 | // y = and x, 0xff |
| 5036 | // z = use y |
| 5037 | // |
| 5038 | // becomes: |
| 5039 | // |
| 5040 | // b0: |
| 5041 | // x = load i32 |
| 5042 | // x' = and x, 0xff |
| 5043 | // ... |
| 5044 | // b1: |
| 5045 | // z = use x' |
| 5046 | // |
| 5047 | // whereas: |
| 5048 | // |
| 5049 | // b0: |
| 5050 | // x1 = load i32 |
| 5051 | // ... |
| 5052 | // b1: |
| 5053 | // x2 = load i32 |
| 5054 | // ... |
| 5055 | // b2: |
| 5056 | // x = phi x1, x2 |
| 5057 | // y = and x, 0xff |
| 5058 | // |
| 5059 | // becomes (after a call to optimizeLoadExt for each load): |
| 5060 | // |
| 5061 | // b0: |
| 5062 | // x1 = load i32 |
| 5063 | // x1' = and x1, 0xff |
| 5064 | // ... |
| 5065 | // b1: |
| 5066 | // x2 = load i32 |
| 5067 | // x2' = and x2, 0xff |
| 5068 | // ... |
| 5069 | // b2: |
| 5070 | // x = phi x1', x2' |
| 5071 | // y = and x, 0xff |
| 5072 | // |
| 5073 | |
| 5074 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
| 5075 | |
| 5076 | if (!Load->isSimple() || |
| 5077 | !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy())) |
| 5078 | return false; |
| 5079 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5080 | // Skip loads we've already transformed. |
| 5081 | if (Load->hasOneUse() && |
| 5082 | InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) |
| 5083 | return false; |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5084 | |
| 5085 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 5086 | // of the loaded value are needed. |
| 5087 | SmallVector<Instruction *, 8> WorkList; |
| 5088 | SmallPtrSet<Instruction *, 16> Visited; |
| 5089 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 5090 | for (auto *U : Load->users()) |
| 5091 | WorkList.push_back(cast<Instruction>(U)); |
| 5092 | |
| 5093 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 5094 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 5095 | APInt DemandBits(BitWidth, 0); |
| 5096 | APInt WidestAndBits(BitWidth, 0); |
| 5097 | |
| 5098 | while (!WorkList.empty()) { |
| 5099 | Instruction *I = WorkList.back(); |
| 5100 | WorkList.pop_back(); |
| 5101 | |
| 5102 | // Break use-def graph loops. |
| 5103 | if (!Visited.insert(I).second) |
| 5104 | continue; |
| 5105 | |
| 5106 | // For a PHI node, push all of its users. |
| 5107 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 5108 | for (auto *U : Phi->users()) |
| 5109 | WorkList.push_back(cast<Instruction>(U)); |
| 5110 | continue; |
| 5111 | } |
| 5112 | |
| 5113 | switch (I->getOpcode()) { |
| 5114 | case llvm::Instruction::And: { |
| 5115 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5116 | if (!AndC) |
| 5117 | return false; |
| 5118 | APInt AndBits = AndC->getValue(); |
| 5119 | DemandBits |= AndBits; |
| 5120 | // Keep track of the widest and mask we see. |
| 5121 | if (AndBits.ugt(WidestAndBits)) |
| 5122 | WidestAndBits = AndBits; |
| 5123 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 5124 | AndsToMaybeRemove.push_back(I); |
| 5125 | break; |
| 5126 | } |
| 5127 | |
| 5128 | case llvm::Instruction::Shl: { |
| 5129 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5130 | if (!ShlC) |
| 5131 | return false; |
| 5132 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
Craig Topper | fc947bc | 2017-04-18 17:14:21 +0000 | [diff] [blame] | 5133 | DemandBits.setLowBits(BitWidth - ShiftAmt); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5134 | break; |
| 5135 | } |
| 5136 | |
| 5137 | case llvm::Instruction::Trunc: { |
| 5138 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 5139 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
Craig Topper | fc947bc | 2017-04-18 17:14:21 +0000 | [diff] [blame] | 5140 | DemandBits.setLowBits(TruncBitWidth); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5141 | break; |
| 5142 | } |
| 5143 | |
| 5144 | default: |
| 5145 | return false; |
| 5146 | } |
| 5147 | } |
| 5148 | |
| 5149 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 5150 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 5151 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 5152 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 5153 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 5154 | // followed by an AND. |
| 5155 | // TODO: Look into removing this restriction by fixing backends to either |
| 5156 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 5157 | // a single instruction. |
| 5158 | // |
| 5159 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 5160 | // mask, since these are the only ands that will be removed by isel. |
Craig Topper | d33ee1b | 2017-04-03 16:34:59 +0000 | [diff] [blame] | 5161 | if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5162 | WidestAndBits != DemandBits) |
| 5163 | return false; |
| 5164 | |
| 5165 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 5166 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 5167 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 5168 | |
| 5169 | // Reject cases that won't be matched as extloads. |
| 5170 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 5171 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 5172 | return false; |
| 5173 | |
| 5174 | IRBuilder<> Builder(Load->getNextNode()); |
| 5175 | auto *NewAnd = dyn_cast<Instruction>( |
| 5176 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5177 | // Mark this instruction as "inserted by CGP", so that other |
| 5178 | // optimizations don't touch it. |
| 5179 | InsertedInsts.insert(NewAnd); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5180 | |
| 5181 | // Replace all uses of load with new and (except for the use of load in the |
| 5182 | // new and itself). |
| 5183 | Load->replaceAllUsesWith(NewAnd); |
| 5184 | NewAnd->setOperand(0, Load); |
| 5185 | |
| 5186 | // Remove any and instructions that are now redundant. |
| 5187 | for (auto *And : AndsToMaybeRemove) |
| 5188 | // Check that the and mask is the same as the one we decided to put on the |
| 5189 | // new and. |
| 5190 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 5191 | And->replaceAllUsesWith(NewAnd); |
| 5192 | if (&*CurInstIterator == And) |
| 5193 | CurInstIterator = std::next(And->getIterator()); |
| 5194 | And->eraseFromParent(); |
| 5195 | ++NumAndUses; |
| 5196 | } |
| 5197 | |
| 5198 | ++NumAndsAdded; |
| 5199 | return true; |
| 5200 | } |
| 5201 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5202 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 5203 | /// that is only used once. |
| 5204 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 5205 | auto *I = dyn_cast<Instruction>(V); |
| 5206 | // If it's safe to speculatively execute, then it should not have side |
| 5207 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 5208 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 5209 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5210 | } |
| 5211 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 5212 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5213 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5214 | const TargetLowering *TLI, |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5215 | SelectInst *SI) { |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5216 | // If even a predictable select is cheap, then a branch can't be cheaper. |
| 5217 | if (!TLI->isPredictableSelectExpensive()) |
| 5218 | return false; |
| 5219 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5220 | // FIXME: This should use the same heuristics as IfConversion to determine |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5221 | // whether a select is better represented as a branch. |
| 5222 | |
| 5223 | // If metadata tells us that the select condition is obviously predictable, |
| 5224 | // then we want to replace the select with a branch. |
| 5225 | uint64_t TrueWeight, FalseWeight; |
| 5226 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { |
| 5227 | uint64_t Max = std::max(TrueWeight, FalseWeight); |
| 5228 | uint64_t Sum = TrueWeight + FalseWeight; |
Sanjay Patel | c7b91e6 | 2016-05-09 17:31:55 +0000 | [diff] [blame] | 5229 | if (Sum != 0) { |
| 5230 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); |
| 5231 | if (Probability > TLI->getPredictableBranchThreshold()) |
| 5232 | return true; |
| 5233 | } |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5234 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5235 | |
| 5236 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 5237 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 5238 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 5239 | // comparison condition. If the compare has more than one use, there's |
| 5240 | // 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] | 5241 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5242 | return false; |
| 5243 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5244 | // If either operand of the select is expensive and only needed on one side |
| 5245 | // of the select, we should form a branch. |
| 5246 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 5247 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 5248 | return true; |
| 5249 | |
| 5250 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5251 | } |
| 5252 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5253 | /// If \p isTrue is true, return the true value of \p SI, otherwise return |
| 5254 | /// false value of \p SI. If the true/false value of \p SI is defined by any |
| 5255 | /// select instructions in \p Selects, look through the defining select |
| 5256 | /// instruction until the true/false value is not defined in \p Selects. |
| 5257 | static Value *getTrueOrFalseValue( |
| 5258 | SelectInst *SI, bool isTrue, |
| 5259 | const SmallPtrSet<const Instruction *, 2> &Selects) { |
| 5260 | Value *V; |
| 5261 | |
| 5262 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); |
| 5263 | DefSI = dyn_cast<SelectInst>(V)) { |
Dehao Chen | c32d712 | 2016-09-12 20:29:54 +0000 | [diff] [blame] | 5264 | assert(DefSI->getCondition() == SI->getCondition() && |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5265 | "The condition of DefSI does not match with SI"); |
| 5266 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); |
| 5267 | } |
| 5268 | return V; |
| 5269 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5270 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5271 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 5272 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5273 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5274 | // Find all consecutive select instructions that share the same condition. |
| 5275 | SmallVector<SelectInst *, 2> ASI; |
| 5276 | ASI.push_back(SI); |
| 5277 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); |
| 5278 | It != SI->getParent()->end(); ++It) { |
| 5279 | SelectInst *I = dyn_cast<SelectInst>(&*It); |
| 5280 | if (I && SI->getCondition() == I->getCondition()) { |
| 5281 | ASI.push_back(I); |
| 5282 | } else { |
| 5283 | break; |
| 5284 | } |
| 5285 | } |
| 5286 | |
| 5287 | SelectInst *LastSI = ASI.back(); |
| 5288 | // Increment the current iterator to skip all the rest of select instructions |
| 5289 | // because they will be either "not lowered" or "all lowered" to branch. |
| 5290 | CurInstIterator = std::next(LastSI->getIterator()); |
| 5291 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5292 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 5293 | |
| 5294 | // Can we convert the 'select' to CF ? |
Sanjay Patel | a31b0c0 | 2016-04-26 00:47:39 +0000 | [diff] [blame] | 5295 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond || |
| 5296 | SI->getMetadata(LLVMContext::MD_unpredictable)) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5297 | return false; |
| 5298 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5299 | TargetLowering::SelectSupportKind SelectKind; |
| 5300 | if (VectorCond) |
| 5301 | SelectKind = TargetLowering::VectorMaskSelect; |
| 5302 | else if (SI->getType()->isVectorTy()) |
| 5303 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 5304 | else |
| 5305 | SelectKind = TargetLowering::ScalarValSelect; |
| 5306 | |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5307 | if (TLI->isSelectSupported(SelectKind) && |
| 5308 | !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) |
| 5309 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5310 | |
| 5311 | ModifiedDT = true; |
| 5312 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5313 | // Transform a sequence like this: |
| 5314 | // start: |
| 5315 | // %cmp = cmp uge i32 %a, %b |
| 5316 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 5317 | // |
| 5318 | // Into: |
| 5319 | // start: |
| 5320 | // %cmp = cmp uge i32 %a, %b |
| 5321 | // br i1 %cmp, label %select.true, label %select.false |
| 5322 | // select.true: |
| 5323 | // br label %select.end |
| 5324 | // select.false: |
| 5325 | // br label %select.end |
| 5326 | // select.end: |
| 5327 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 5328 | // |
| 5329 | // In addition, we may sink instructions that produce %c or %d from |
| 5330 | // the entry block into the destination(s) of the new branch. |
| 5331 | // If the true or false blocks do not contain a sunken instruction, that |
| 5332 | // block and its branch may be optimized away. In that case, one side of the |
| 5333 | // first branch will point directly to select.end, and the corresponding PHI |
| 5334 | // predecessor block will be the start block. |
| 5335 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5336 | // First, we split the block containing the select into 2 blocks. |
| 5337 | BasicBlock *StartBlock = SI->getParent(); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5338 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5339 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5340 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5341 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5342 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5343 | |
| 5344 | // These are the new basic blocks for the conditional branch. |
| 5345 | // At least one will become an actual new basic block. |
| 5346 | BasicBlock *TrueBlock = nullptr; |
| 5347 | BasicBlock *FalseBlock = nullptr; |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5348 | BranchInst *TrueBranch = nullptr; |
| 5349 | BranchInst *FalseBranch = nullptr; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5350 | |
| 5351 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 5352 | // them speculatively. |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5353 | for (SelectInst *SI : ASI) { |
| 5354 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 5355 | if (TrueBlock == nullptr) { |
| 5356 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 5357 | EndBlock->getParent(), EndBlock); |
| 5358 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 5359 | } |
| 5360 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 5361 | TrueInst->moveBefore(TrueBranch); |
| 5362 | } |
| 5363 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 5364 | if (FalseBlock == nullptr) { |
| 5365 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 5366 | EndBlock->getParent(), EndBlock); |
| 5367 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 5368 | } |
| 5369 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 5370 | FalseInst->moveBefore(FalseBranch); |
| 5371 | } |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5372 | } |
| 5373 | |
| 5374 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 5375 | // for a new input value to the PHI. |
| 5376 | if (TrueBlock == FalseBlock) { |
| 5377 | assert(TrueBlock == nullptr && |
| 5378 | "Unexpected basic block transform while optimizing select"); |
| 5379 | |
| 5380 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 5381 | EndBlock->getParent(), EndBlock); |
| 5382 | BranchInst::Create(EndBlock, FalseBlock); |
| 5383 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5384 | |
| 5385 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5386 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 5387 | // of the condition, it means that side of the branch goes to the end block |
| 5388 | // directly and the path originates from the start block from the point of |
| 5389 | // view of the new PHI. |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5390 | BasicBlock *TT, *FT; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5391 | if (TrueBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5392 | TT = EndBlock; |
| 5393 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5394 | TrueBlock = StartBlock; |
| 5395 | } else if (FalseBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5396 | TT = TrueBlock; |
| 5397 | FT = EndBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5398 | FalseBlock = StartBlock; |
| 5399 | } else { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5400 | TT = TrueBlock; |
| 5401 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5402 | } |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5403 | IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5404 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5405 | SmallPtrSet<const Instruction *, 2> INS; |
| 5406 | INS.insert(ASI.begin(), ASI.end()); |
| 5407 | // Use reverse iterator because later select may use the value of the |
| 5408 | // earlier select, and we need to propagate value through earlier select |
| 5409 | // to get the PHI operand. |
| 5410 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { |
| 5411 | SelectInst *SI = *It; |
| 5412 | // The select itself is replaced with a PHI Node. |
| 5413 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
| 5414 | PN->takeName(SI); |
| 5415 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); |
| 5416 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5417 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5418 | SI->replaceAllUsesWith(PN); |
| 5419 | SI->eraseFromParent(); |
| 5420 | INS.erase(SI); |
| 5421 | ++NumSelectsExpanded; |
| 5422 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5423 | |
| 5424 | // Instruct OptimizeBlock to skip to the next block. |
| 5425 | CurInstIterator = StartBlock->end(); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5426 | return true; |
| 5427 | } |
| 5428 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 5429 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5430 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 5431 | int SplatElem = -1; |
| 5432 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 5433 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 5434 | return false; |
| 5435 | SplatElem = Mask[i]; |
| 5436 | } |
| 5437 | |
| 5438 | return true; |
| 5439 | } |
| 5440 | |
| 5441 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 5442 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 5443 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 5444 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5445 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5446 | BasicBlock *DefBB = SVI->getParent(); |
| 5447 | |
| 5448 | // Only do this xform if variable vector shifts are particularly expensive. |
| 5449 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 5450 | return false; |
| 5451 | |
| 5452 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 5453 | // constant splat. |
| 5454 | if (!isBroadcastShuffle(SVI)) |
| 5455 | return false; |
| 5456 | |
| 5457 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 5458 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 5459 | |
| 5460 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5461 | for (User *U : SVI->users()) { |
| 5462 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5463 | |
| 5464 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5465 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5466 | if (UserBB == DefBB) continue; |
| 5467 | |
| 5468 | // 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] | 5469 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5470 | |
| 5471 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 5472 | // already have a copy. |
| 5473 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 5474 | |
| 5475 | if (!InsertedShuffle) { |
| 5476 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5477 | assert(InsertPt != UserBB->end()); |
| 5478 | InsertedShuffle = |
| 5479 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 5480 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5481 | } |
| 5482 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5483 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5484 | MadeChange = true; |
| 5485 | } |
| 5486 | |
| 5487 | // If we removed all uses, nuke the shuffle. |
| 5488 | if (SVI->use_empty()) { |
| 5489 | SVI->eraseFromParent(); |
| 5490 | MadeChange = true; |
| 5491 | } |
| 5492 | |
| 5493 | return MadeChange; |
| 5494 | } |
| 5495 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5496 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 5497 | if (!TLI || !DL) |
| 5498 | return false; |
| 5499 | |
| 5500 | Value *Cond = SI->getCondition(); |
| 5501 | Type *OldType = Cond->getType(); |
| 5502 | LLVMContext &Context = Cond->getContext(); |
| 5503 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 5504 | unsigned RegWidth = RegType.getSizeInBits(); |
| 5505 | |
| 5506 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 5507 | return false; |
| 5508 | |
| 5509 | // If the register width is greater than the type width, expand the condition |
| 5510 | // of the switch instruction and each case constant to the width of the |
| 5511 | // register. By widening the type of the switch condition, subsequent |
| 5512 | // comparisons (for case comparisons) will not need to be extended to the |
| 5513 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 5514 | // where N is the number of cases in the switch. |
| 5515 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 5516 | |
| 5517 | // Zero-extend the switch condition and case constants unless the switch |
| 5518 | // condition is a function argument that is already being sign-extended. |
| 5519 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 5520 | // everything instead. |
| 5521 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 5522 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 5523 | if (Arg->hasSExtAttr()) |
| 5524 | ExtType = Instruction::SExt; |
| 5525 | |
| 5526 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 5527 | ExtInst->insertBefore(SI); |
| 5528 | SI->setCondition(ExtInst); |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 5529 | for (auto Case : SI->cases()) { |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5530 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 5531 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 5532 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 5533 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 5534 | } |
| 5535 | |
| 5536 | return true; |
| 5537 | } |
| 5538 | |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 5539 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5540 | namespace { |
| 5541 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 5542 | /// This class is used to move downward extractelement transition. |
| 5543 | /// E.g., |
| 5544 | /// a = vector_op <2 x i32> |
| 5545 | /// b = extractelement <2 x i32> a, i32 0 |
| 5546 | /// c = scalar_op b |
| 5547 | /// store c |
| 5548 | /// |
| 5549 | /// => |
| 5550 | /// a = vector_op <2 x i32> |
| 5551 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 5552 | /// * d = extractelement <2 x i32> c, i32 0 |
| 5553 | /// * store d |
| 5554 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 5555 | /// transition. |
| 5556 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5557 | /// DataLayout associated with the current module. |
| 5558 | const DataLayout &DL; |
| 5559 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5560 | /// Used to perform some checks on the legality of vector operations. |
| 5561 | const TargetLowering &TLI; |
| 5562 | |
| 5563 | /// Used to estimated the cost of the promoted chain. |
| 5564 | const TargetTransformInfo &TTI; |
| 5565 | |
| 5566 | /// The transition being moved downwards. |
| 5567 | Instruction *Transition; |
| 5568 | /// The sequence of instructions to be promoted. |
| 5569 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 5570 | /// Cost of combining a store and an extract. |
| 5571 | unsigned StoreExtractCombineCost; |
| 5572 | /// Instruction that will be combined with the transition. |
| 5573 | Instruction *CombineInst; |
| 5574 | |
| 5575 | /// \brief The instruction that represents the current end of the transition. |
| 5576 | /// Since we are faking the promotion until we reach the end of the chain |
| 5577 | /// of computation, we need a way to get the current end of the transition. |
| 5578 | Instruction *getEndOfTransition() const { |
| 5579 | if (InstsToBePromoted.empty()) |
| 5580 | return Transition; |
| 5581 | return InstsToBePromoted.back(); |
| 5582 | } |
| 5583 | |
| 5584 | /// \brief Return the index of the original value in the transition. |
| 5585 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 5586 | /// c, is at index 0. |
| 5587 | unsigned getTransitionOriginalValueIdx() const { |
| 5588 | assert(isa<ExtractElementInst>(Transition) && |
| 5589 | "Other kind of transitions are not supported yet"); |
| 5590 | return 0; |
| 5591 | } |
| 5592 | |
| 5593 | /// \brief Return the index of the index in the transition. |
| 5594 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 5595 | /// is at index 1. |
| 5596 | unsigned getTransitionIdx() const { |
| 5597 | assert(isa<ExtractElementInst>(Transition) && |
| 5598 | "Other kind of transitions are not supported yet"); |
| 5599 | return 1; |
| 5600 | } |
| 5601 | |
| 5602 | /// \brief Get the type of the transition. |
| 5603 | /// This is the type of the original value. |
| 5604 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 5605 | /// transition is <2 x i32>. |
| 5606 | Type *getTransitionType() const { |
| 5607 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 5608 | } |
| 5609 | |
| 5610 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 5611 | /// I.e., we have the following sequence: |
| 5612 | /// Def = Transition <ty1> a to <ty2> |
| 5613 | /// b = ToBePromoted <ty2> Def, ... |
| 5614 | /// => |
| 5615 | /// b = ToBePromoted <ty1> a, ... |
| 5616 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 5617 | void promoteImpl(Instruction *ToBePromoted); |
| 5618 | |
| 5619 | /// \brief Check whether or not it is profitable to promote all the |
| 5620 | /// instructions enqueued to be promoted. |
| 5621 | bool isProfitableToPromote() { |
| 5622 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5623 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 5624 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 5625 | : -1; |
| 5626 | Type *PromotedType = getTransitionType(); |
| 5627 | |
| 5628 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 5629 | unsigned AS = ST->getPointerAddressSpace(); |
| 5630 | unsigned Align = ST->getAlignment(); |
| 5631 | // Check if this store is supported. |
| 5632 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5633 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 5634 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5635 | // If this is not supported, there is no way we can combine |
| 5636 | // the extract with the store. |
| 5637 | return false; |
| 5638 | } |
| 5639 | |
| 5640 | // The scalar chain of computation has to pay for the transition |
| 5641 | // scalar to vector. |
| 5642 | // The vector chain has to account for the combining cost. |
| 5643 | uint64_t ScalarCost = |
| 5644 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 5645 | uint64_t VectorCost = StoreExtractCombineCost; |
| 5646 | for (const auto &Inst : InstsToBePromoted) { |
| 5647 | // Compute the cost. |
| 5648 | // By construction, all instructions being promoted are arithmetic ones. |
| 5649 | // Moreover, one argument is a constant that can be viewed as a splat |
| 5650 | // constant. |
| 5651 | Value *Arg0 = Inst->getOperand(0); |
| 5652 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 5653 | isa<ConstantFP>(Arg0); |
| 5654 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 5655 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5656 | : TargetTransformInfo::OK_AnyValue; |
| 5657 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 5658 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5659 | : TargetTransformInfo::OK_AnyValue; |
| 5660 | ScalarCost += TTI.getArithmeticInstrCost( |
| 5661 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 5662 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 5663 | Arg0OVK, Arg1OVK); |
| 5664 | } |
| 5665 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 5666 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 5667 | return ScalarCost > VectorCost; |
| 5668 | } |
| 5669 | |
| 5670 | /// \brief Generate a constant vector with \p Val with the same |
| 5671 | /// number of elements as the transition. |
| 5672 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 5673 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5674 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 5675 | /// otherwise we generate a vector with as many undef as possible: |
| 5676 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 5677 | /// used at the index of the extract. |
| 5678 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 5679 | unsigned ExtractIdx = UINT_MAX; |
| 5680 | if (!UseSplat) { |
| 5681 | // If we cannot determine where the constant must be, we have to |
| 5682 | // use a splat constant. |
| 5683 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 5684 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 5685 | ExtractIdx = CstVal->getSExtValue(); |
| 5686 | else |
| 5687 | UseSplat = true; |
| 5688 | } |
| 5689 | |
| 5690 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 5691 | if (UseSplat) |
| 5692 | return ConstantVector::getSplat(End, Val); |
| 5693 | |
| 5694 | SmallVector<Constant *, 4> ConstVec; |
| 5695 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 5696 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 5697 | if (Idx == ExtractIdx) |
| 5698 | ConstVec.push_back(Val); |
| 5699 | else |
| 5700 | ConstVec.push_back(UndefVal); |
| 5701 | } |
| 5702 | return ConstantVector::get(ConstVec); |
| 5703 | } |
| 5704 | |
| 5705 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 5706 | /// in \p Use can trigger undefined behavior. |
| 5707 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 5708 | unsigned OperandIdx) { |
| 5709 | // This is not safe to introduce undef when the operand is on |
| 5710 | // the right hand side of a division-like instruction. |
| 5711 | if (OperandIdx != 1) |
| 5712 | return false; |
| 5713 | switch (Use->getOpcode()) { |
| 5714 | default: |
| 5715 | return false; |
| 5716 | case Instruction::SDiv: |
| 5717 | case Instruction::UDiv: |
| 5718 | case Instruction::SRem: |
| 5719 | case Instruction::URem: |
| 5720 | return true; |
| 5721 | case Instruction::FDiv: |
| 5722 | case Instruction::FRem: |
| 5723 | return !Use->hasNoNaNs(); |
| 5724 | } |
| 5725 | llvm_unreachable(nullptr); |
| 5726 | } |
| 5727 | |
| 5728 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5729 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 5730 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 5731 | unsigned CombineCost) |
| 5732 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5733 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 5734 | assert(Transition && "Do not know how to promote null"); |
| 5735 | } |
| 5736 | |
| 5737 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 5738 | bool canPromote(const Instruction *ToBePromoted) const { |
| 5739 | // We could support CastInst too. |
| 5740 | return isa<BinaryOperator>(ToBePromoted); |
| 5741 | } |
| 5742 | |
| 5743 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 5744 | /// by moving downward the transition through. |
| 5745 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 5746 | // Promote only if all the operands can be statically expanded. |
| 5747 | // Indeed, we do not want to introduce any new kind of transitions. |
| 5748 | for (const Use &U : ToBePromoted->operands()) { |
| 5749 | const Value *Val = U.get(); |
| 5750 | if (Val == getEndOfTransition()) { |
| 5751 | // If the use is a division and the transition is on the rhs, |
| 5752 | // we cannot promote the operation, otherwise we may create a |
| 5753 | // division by zero. |
| 5754 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 5755 | return false; |
| 5756 | continue; |
| 5757 | } |
| 5758 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 5759 | !isa<ConstantFP>(Val)) |
| 5760 | return false; |
| 5761 | } |
| 5762 | // Check that the resulting operation is legal. |
| 5763 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 5764 | if (!ISDOpcode) |
| 5765 | return false; |
| 5766 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 5767 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5768 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5769 | } |
| 5770 | |
| 5771 | /// \brief Check whether or not \p Use can be combined |
| 5772 | /// with the transition. |
| 5773 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 5774 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 5775 | |
| 5776 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 5777 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 5778 | InstsToBePromoted.push_back(ToBePromoted); |
| 5779 | } |
| 5780 | |
| 5781 | /// \brief Set the instruction that will be combined with the transition. |
| 5782 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 5783 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 5784 | CombineInst = ToBeCombined; |
| 5785 | } |
| 5786 | |
| 5787 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 5788 | /// is profitable. |
| 5789 | /// \return True if the promotion happened, false otherwise. |
| 5790 | bool promote() { |
| 5791 | // Check if there is something to promote. |
| 5792 | // Right now, if we do not have anything to combine with, |
| 5793 | // we assume the promotion is not profitable. |
| 5794 | if (InstsToBePromoted.empty() || !CombineInst) |
| 5795 | return false; |
| 5796 | |
| 5797 | // Check cost. |
| 5798 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 5799 | return false; |
| 5800 | |
| 5801 | // Promote. |
| 5802 | for (auto &ToBePromoted : InstsToBePromoted) |
| 5803 | promoteImpl(ToBePromoted); |
| 5804 | InstsToBePromoted.clear(); |
| 5805 | return true; |
| 5806 | } |
| 5807 | }; |
| 5808 | } // End of anonymous namespace. |
| 5809 | |
| 5810 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 5811 | // At this point, we know that all the operands of ToBePromoted but Def |
| 5812 | // can be statically promoted. |
| 5813 | // For Def, we need to use its parameter in ToBePromoted: |
| 5814 | // b = ToBePromoted ty1 a |
| 5815 | // Def = Transition ty1 b to ty2 |
| 5816 | // Move the transition down. |
| 5817 | // 1. Replace all uses of the promoted operation by the transition. |
| 5818 | // = ... b => = ... Def. |
| 5819 | assert(ToBePromoted->getType() == Transition->getType() && |
| 5820 | "The type of the result of the transition does not match " |
| 5821 | "the final type"); |
| 5822 | ToBePromoted->replaceAllUsesWith(Transition); |
| 5823 | // 2. Update the type of the uses. |
| 5824 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 5825 | Type *TransitionTy = getTransitionType(); |
| 5826 | ToBePromoted->mutateType(TransitionTy); |
| 5827 | // 3. Update all the operands of the promoted operation with promoted |
| 5828 | // operands. |
| 5829 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 5830 | for (Use &U : ToBePromoted->operands()) { |
| 5831 | Value *Val = U.get(); |
| 5832 | Value *NewVal = nullptr; |
| 5833 | if (Val == Transition) |
| 5834 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5835 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 5836 | isa<ConstantFP>(Val)) { |
| 5837 | // Use a splat constant if it is not safe to use undef. |
| 5838 | NewVal = getConstantVector( |
| 5839 | cast<Constant>(Val), |
| 5840 | isa<UndefValue>(Val) || |
| 5841 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 5842 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 5843 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 5844 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5845 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 5846 | } |
| 5847 | Transition->removeFromParent(); |
| 5848 | Transition->insertAfter(ToBePromoted); |
| 5849 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 5850 | } |
| 5851 | |
| 5852 | /// Some targets can do store(extractelement) with one instruction. |
| 5853 | /// Try to push the extractelement towards the stores when the target |
| 5854 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5855 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5856 | unsigned CombineCost = UINT_MAX; |
| 5857 | if (DisableStoreExtract || !TLI || |
| 5858 | (!StressStoreExtract && |
| 5859 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 5860 | Inst->getOperand(1), CombineCost))) |
| 5861 | return false; |
| 5862 | |
| 5863 | // At this point we know that Inst is a vector to scalar transition. |
| 5864 | // Try to move it down the def-use chain, until: |
| 5865 | // - We can combine the transition with its single use |
| 5866 | // => we got rid of the transition. |
| 5867 | // - We escape the current basic block |
| 5868 | // => we would need to check that we are moving it at a cheaper place and |
| 5869 | // we do not do that for now. |
| 5870 | BasicBlock *Parent = Inst->getParent(); |
| 5871 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5872 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5873 | // If the transition has more than one use, assume this is not going to be |
| 5874 | // beneficial. |
| 5875 | while (Inst->hasOneUse()) { |
| 5876 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 5877 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 5878 | |
| 5879 | if (ToBePromoted->getParent() != Parent) { |
| 5880 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 5881 | << ToBePromoted->getParent()->getName() |
| 5882 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 5883 | return false; |
| 5884 | } |
| 5885 | |
| 5886 | if (VPH.canCombine(ToBePromoted)) { |
| 5887 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 5888 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 5889 | VPH.recordCombineInstruction(ToBePromoted); |
| 5890 | bool Changed = VPH.promote(); |
| 5891 | NumStoreExtractExposed += Changed; |
| 5892 | return Changed; |
| 5893 | } |
| 5894 | |
| 5895 | DEBUG(dbgs() << "Try promoting.\n"); |
| 5896 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 5897 | return false; |
| 5898 | |
| 5899 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 5900 | |
| 5901 | VPH.enqueueForPromotion(ToBePromoted); |
| 5902 | Inst = ToBePromoted; |
| 5903 | } |
| 5904 | return false; |
| 5905 | } |
| 5906 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 5907 | /// For the instruction sequence of store below, F and I values |
| 5908 | /// are bundled together as an i64 value before being stored into memory. |
| 5909 | /// Sometimes it is more efficent to generate separate stores for F and I, |
| 5910 | /// which can remove the bitwise instructions or sink them to colder places. |
| 5911 | /// |
| 5912 | /// (store (or (zext (bitcast F to i32) to i64), |
| 5913 | /// (shl (zext I to i64), 32)), addr) --> |
| 5914 | /// (store F, addr) and (store I, addr+4) |
| 5915 | /// |
| 5916 | /// Similarly, splitting for other merged store can also be beneficial, like: |
| 5917 | /// For pair of {i32, i32}, i64 store --> two i32 stores. |
| 5918 | /// For pair of {i32, i16}, i64 store --> two i32 stores. |
| 5919 | /// For pair of {i16, i16}, i32 store --> two i16 stores. |
| 5920 | /// For pair of {i16, i8}, i32 store --> two i16 stores. |
| 5921 | /// For pair of {i8, i8}, i16 store --> two i8 stores. |
| 5922 | /// |
| 5923 | /// We allow each target to determine specifically which kind of splitting is |
| 5924 | /// supported. |
| 5925 | /// |
| 5926 | /// The store patterns are commonly seen from the simple code snippet below |
| 5927 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. |
| 5928 | /// void goo(const std::pair<int, float> &); |
| 5929 | /// hoo() { |
| 5930 | /// ... |
| 5931 | /// goo(std::make_pair(tmp, ftmp)); |
| 5932 | /// ... |
| 5933 | /// } |
| 5934 | /// |
| 5935 | /// Although we already have similar splitting in DAG Combine, we duplicate |
| 5936 | /// it in CodeGenPrepare to catch the case in which pattern is across |
| 5937 | /// multiple BBs. The logic in DAG Combine is kept to catch case generated |
| 5938 | /// during code expansion. |
| 5939 | static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, |
| 5940 | const TargetLowering &TLI) { |
| 5941 | // Handle simple but common cases only. |
| 5942 | Type *StoreType = SI.getValueOperand()->getType(); |
| 5943 | if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) || |
| 5944 | DL.getTypeSizeInBits(StoreType) == 0) |
| 5945 | return false; |
| 5946 | |
| 5947 | unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; |
| 5948 | Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); |
| 5949 | if (DL.getTypeStoreSizeInBits(SplitStoreType) != |
| 5950 | DL.getTypeSizeInBits(SplitStoreType)) |
| 5951 | return false; |
| 5952 | |
| 5953 | // Match the following patterns: |
| 5954 | // (store (or (zext LValue to i64), |
| 5955 | // (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 5956 | // or |
| 5957 | // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 5958 | // (zext LValue to i64), |
| 5959 | // Expect both operands of OR and the first operand of SHL have only |
| 5960 | // one use. |
| 5961 | Value *LValue, *HValue; |
| 5962 | if (!match(SI.getValueOperand(), |
| 5963 | m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), |
| 5964 | m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), |
| 5965 | m_SpecificInt(HalfValBitSize)))))) |
| 5966 | return false; |
| 5967 | |
| 5968 | // Check LValue and HValue are int with size less or equal than 32. |
| 5969 | if (!LValue->getType()->isIntegerTy() || |
| 5970 | DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || |
| 5971 | !HValue->getType()->isIntegerTy() || |
| 5972 | DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) |
| 5973 | return false; |
| 5974 | |
| 5975 | // If LValue/HValue is a bitcast instruction, use the EVT before bitcast |
| 5976 | // as the input of target query. |
| 5977 | auto *LBC = dyn_cast<BitCastInst>(LValue); |
| 5978 | auto *HBC = dyn_cast<BitCastInst>(HValue); |
| 5979 | EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) |
| 5980 | : EVT::getEVT(LValue->getType()); |
| 5981 | EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) |
| 5982 | : EVT::getEVT(HValue->getType()); |
| 5983 | if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) |
| 5984 | return false; |
| 5985 | |
| 5986 | // Start to split store. |
| 5987 | IRBuilder<> Builder(SI.getContext()); |
| 5988 | Builder.SetInsertPoint(&SI); |
| 5989 | |
| 5990 | // If LValue/HValue is a bitcast in another BB, create a new one in current |
| 5991 | // BB so it may be merged with the splitted stores by dag combiner. |
| 5992 | if (LBC && LBC->getParent() != SI.getParent()) |
| 5993 | LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); |
| 5994 | if (HBC && HBC->getParent() != SI.getParent()) |
| 5995 | HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); |
| 5996 | |
| 5997 | auto CreateSplitStore = [&](Value *V, bool Upper) { |
| 5998 | V = Builder.CreateZExtOrBitCast(V, SplitStoreType); |
| 5999 | Value *Addr = Builder.CreateBitCast( |
| 6000 | SI.getOperand(1), |
| 6001 | SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); |
| 6002 | if (Upper) |
| 6003 | Addr = Builder.CreateGEP( |
| 6004 | SplitStoreType, Addr, |
| 6005 | ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); |
| 6006 | Builder.CreateAlignedStore( |
| 6007 | V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment()); |
| 6008 | }; |
| 6009 | |
| 6010 | CreateSplitStore(LValue, false); |
| 6011 | CreateSplitStore(HValue, true); |
| 6012 | |
| 6013 | // Delete the old store. |
| 6014 | SI.eraseFromParent(); |
| 6015 | return true; |
| 6016 | } |
| 6017 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6018 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 6019 | // Bail out if we inserted the instruction to prevent optimizations from |
| 6020 | // stepping on each other's toes. |
| 6021 | if (InsertedInsts.count(I)) |
| 6022 | return false; |
| 6023 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6024 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 6025 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 6026 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 6027 | // trivial PHI, go ahead and zap it here. |
Daniel Berlin | 4d0fe64 | 2017-04-28 19:55:38 +0000 | [diff] [blame] | 6028 | if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6029 | P->replaceAllUsesWith(V); |
| 6030 | P->eraseFromParent(); |
| 6031 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6032 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6033 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6034 | return false; |
| 6035 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6036 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6037 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6038 | // If the source of the cast is a constant, then this should have |
| 6039 | // already been constant folded. The only reason NOT to constant fold |
| 6040 | // it is if something (e.g. LSR) was careful to place the constant |
| 6041 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 6042 | // the address of globals out of a loop). If this is the case, we don't |
| 6043 | // want to forward-subst the cast. |
| 6044 | if (isa<Constant>(CI->getOperand(0))) |
| 6045 | return false; |
| 6046 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6047 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6048 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6049 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6050 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6051 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 6052 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6053 | if (TLI && |
| 6054 | TLI->getTypeAction(CI->getContext(), |
| 6055 | TLI->getValueType(*DL, CI->getType())) == |
| 6056 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6057 | return SinkCast(CI); |
| 6058 | } else { |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 6059 | bool MadeChange = optimizeExt(I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6060 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6061 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6062 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6063 | return false; |
| 6064 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6065 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6066 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 6067 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 6068 | return OptimizeCmpExpression(CI, TLI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6069 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6070 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6071 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6072 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6073 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6074 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6075 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 6076 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6077 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 6078 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6079 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6080 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6081 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6082 | if (TLI && splitMergedValStore(*SI, *DL, *TLI)) |
| 6083 | return true; |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6084 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6085 | if (TLI) { |
| 6086 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6087 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6088 | SI->getOperand(0)->getType(), AS); |
| 6089 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6090 | return false; |
| 6091 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6092 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 6093 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
| 6094 | unsigned AS = RMW->getPointerAddressSpace(); |
| 6095 | return optimizeMemoryInst(I, RMW->getPointerOperand(), |
| 6096 | RMW->getType(), AS); |
| 6097 | } |
| 6098 | |
| 6099 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { |
| 6100 | unsigned AS = CmpX->getPointerAddressSpace(); |
| 6101 | return optimizeMemoryInst(I, CmpX->getPointerOperand(), |
| 6102 | CmpX->getCompareOperand()->getType(), AS); |
| 6103 | } |
| 6104 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6105 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 6106 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 6107 | if (BinOp && (BinOp->getOpcode() == Instruction::And) && |
| 6108 | EnableAndCmpSinking && TLI) |
| 6109 | return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); |
| 6110 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6111 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 6112 | BinOp->getOpcode() == Instruction::LShr)) { |
| 6113 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 6114 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6115 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6116 | |
| 6117 | return false; |
| 6118 | } |
| 6119 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6120 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6121 | if (GEPI->hasAllZeroIndices()) { |
| 6122 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 6123 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 6124 | GEPI->getName(), GEPI); |
| 6125 | GEPI->replaceAllUsesWith(NC); |
| 6126 | GEPI->eraseFromParent(); |
| 6127 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6128 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6129 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6130 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6131 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6132 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6133 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6134 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6135 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6136 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6137 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6138 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6139 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6140 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6141 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6142 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 6143 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 6144 | return optimizeSwitchInst(Switch); |
| 6145 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6146 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6147 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6148 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6149 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6150 | } |
| 6151 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6152 | /// Given an OR instruction, check to see if this is a bitreverse |
| 6153 | /// idiom. If so, insert the new intrinsic and return true. |
| 6154 | static bool makeBitReverse(Instruction &I, const DataLayout &DL, |
| 6155 | const TargetLowering &TLI) { |
| 6156 | if (!I.getType()->isIntegerTy() || |
| 6157 | !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, |
| 6158 | TLI.getValueType(DL, I.getType(), true))) |
| 6159 | return false; |
| 6160 | |
| 6161 | SmallVector<Instruction*, 4> Insts; |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 6162 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6163 | return false; |
| 6164 | Instruction *LastInst = Insts.back(); |
| 6165 | I.replaceAllUsesWith(LastInst); |
| 6166 | RecursivelyDeleteTriviallyDeadInstructions(&I); |
| 6167 | return true; |
| 6168 | } |
| 6169 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6170 | // In this pass we look for GEP and cast instructions that are used |
| 6171 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 6172 | // selection. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6173 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 6174 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 6175 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 6176 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 6177 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6178 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 6179 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6180 | if (ModifiedDT) |
| 6181 | return true; |
| 6182 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 6183 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6184 | bool MadeBitReverse = true; |
| 6185 | while (TLI && MadeBitReverse) { |
| 6186 | MadeBitReverse = false; |
| 6187 | for (auto &I : reverse(BB)) { |
| 6188 | if (makeBitReverse(I, *DL, *TLI)) { |
| 6189 | MadeBitReverse = MadeChange = true; |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 6190 | ModifiedDT = true; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6191 | break; |
| 6192 | } |
| 6193 | } |
| 6194 | } |
James Molloy | 3ef84c4 | 2016-01-15 10:36:01 +0000 | [diff] [blame] | 6195 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Junmo Park | 7d6c5f1 | 2016-01-28 09:42:39 +0000 | [diff] [blame] | 6196 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6197 | return MadeChange; |
| 6198 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6199 | |
| 6200 | // 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] | 6201 | // 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] | 6202 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6203 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6204 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6205 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 6206 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6207 | 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] | 6208 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6209 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 6210 | // Leave dbg.values that refer to an alloca alone. These |
| 6211 | // instrinsics describe the address of a variable (= the alloca) |
| 6212 | // being taken. They should not be moved next to the alloca |
| 6213 | // (and to the beginning of the scope), but rather stay close to |
| 6214 | // where said address is used. |
| 6215 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6216 | PrevNonDbgInst = Insn; |
| 6217 | continue; |
| 6218 | } |
| 6219 | |
| 6220 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 6221 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 6222 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 6223 | // after it. |
| 6224 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 6225 | continue; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6226 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 6227 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 6228 | if (isa<PHINode>(VI)) |
| 6229 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 6230 | else |
| 6231 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6232 | MadeChange = true; |
| 6233 | ++NumDbgValueMoved; |
| 6234 | } |
| 6235 | } |
| 6236 | } |
| 6237 | return MadeChange; |
| 6238 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 6239 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6240 | /// \brief Scale down both weights to fit into uint32_t. |
| 6241 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 6242 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 6243 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 6244 | NewTrue = NewTrue / Scale; |
| 6245 | NewFalse = NewFalse / Scale; |
| 6246 | } |
| 6247 | |
| 6248 | /// \brief Some targets prefer to split a conditional branch like: |
| 6249 | /// \code |
| 6250 | /// %0 = icmp ne i32 %a, 0 |
| 6251 | /// %1 = icmp ne i32 %b, 0 |
| 6252 | /// %or.cond = or i1 %0, %1 |
| 6253 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 6254 | /// \endcode |
| 6255 | /// into multiple branch instructions like: |
| 6256 | /// \code |
| 6257 | /// bb1: |
| 6258 | /// %0 = icmp ne i32 %a, 0 |
| 6259 | /// br i1 %0, label %TrueBB, label %bb2 |
| 6260 | /// bb2: |
| 6261 | /// %1 = icmp ne i32 %b, 0 |
| 6262 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 6263 | /// \endcode |
| 6264 | /// This usually allows instruction selection to do even further optimizations |
| 6265 | /// and combine the compare with the branch instruction. Currently this is |
| 6266 | /// applied for targets which have "cheap" jump instructions. |
| 6267 | /// |
| 6268 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 6269 | /// |
| 6270 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6271 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6272 | return false; |
| 6273 | |
| 6274 | bool MadeChange = false; |
| 6275 | for (auto &BB : F) { |
| 6276 | // Does this BB end with the following? |
| 6277 | // %cond1 = icmp|fcmp|binary instruction ... |
| 6278 | // %cond2 = icmp|fcmp|binary instruction ... |
| 6279 | // %cond.or = or|and i1 %cond1, cond2 |
| 6280 | // br i1 %cond.or label %dest1, label %dest2" |
| 6281 | BinaryOperator *LogicOp; |
| 6282 | BasicBlock *TBB, *FBB; |
| 6283 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 6284 | continue; |
| 6285 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 6286 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 6287 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 6288 | continue; |
| 6289 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6290 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6291 | Value *Cond1, *Cond2; |
| 6292 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 6293 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6294 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6295 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 6296 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6297 | Opc = Instruction::Or; |
| 6298 | else |
| 6299 | continue; |
| 6300 | |
| 6301 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 6302 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 6303 | continue; |
| 6304 | |
| 6305 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 6306 | |
| 6307 | // Create a new BB. |
Duncan P. N. Exon Smith | a848c47 | 2016-02-21 19:52:15 +0000 | [diff] [blame] | 6308 | auto TmpBB = |
| 6309 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", |
| 6310 | BB.getParent(), BB.getNextNode()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6311 | |
| 6312 | // Update original basic block by using the first condition directly by the |
| 6313 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6314 | Br1->setCondition(Cond1); |
| 6315 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6316 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6317 | // Depending on the conditon we have to either replace the true or the false |
| 6318 | // successor of the original branch instruction. |
| 6319 | if (Opc == Instruction::And) |
| 6320 | Br1->setSuccessor(0, TmpBB); |
| 6321 | else |
| 6322 | Br1->setSuccessor(1, TmpBB); |
| 6323 | |
| 6324 | // Fill in the new basic block. |
| 6325 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6326 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 6327 | I->removeFromParent(); |
| 6328 | I->insertBefore(Br2); |
| 6329 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6330 | |
| 6331 | // Update PHI nodes in both successors. The original BB needs to be |
| 6332 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 6333 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 6334 | // incoming edge to the PHI nodes, because both branch instructions target |
| 6335 | // now the same successor. Depending on the original branch condition |
| 6336 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 6337 | // we perform the correct update for the PHI nodes. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6338 | // This doesn't change the successor order of the just created branch |
| 6339 | // instruction (or any other instruction). |
| 6340 | if (Opc == Instruction::Or) |
| 6341 | std::swap(TBB, FBB); |
| 6342 | |
| 6343 | // Replace the old BB with the new BB. |
| 6344 | for (auto &I : *TBB) { |
| 6345 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6346 | if (!PN) |
| 6347 | break; |
| 6348 | int i; |
| 6349 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 6350 | PN->setIncomingBlock(i, TmpBB); |
| 6351 | } |
| 6352 | |
| 6353 | // Add another incoming edge form the new BB. |
| 6354 | for (auto &I : *FBB) { |
| 6355 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6356 | if (!PN) |
| 6357 | break; |
| 6358 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 6359 | PN->addIncoming(Val, TmpBB); |
| 6360 | } |
| 6361 | |
| 6362 | // Update the branch weights (from SelectionDAGBuilder:: |
| 6363 | // FindMergedConditions). |
| 6364 | if (Opc == Instruction::Or) { |
| 6365 | // Codegen X | Y as: |
| 6366 | // BB1: |
| 6367 | // jmp_if_X TBB |
| 6368 | // jmp TmpBB |
| 6369 | // TmpBB: |
| 6370 | // jmp_if_Y TBB |
| 6371 | // jmp FBB |
| 6372 | // |
| 6373 | |
| 6374 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 6375 | // The requirement is that |
| 6376 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 6377 | // = TrueProb for orignal BB. |
| 6378 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6379 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 6380 | // assumes that |
| 6381 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 6382 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 6383 | // TmpBB, but the math is more complicated. |
| 6384 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6385 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6386 | uint64_t NewTrueWeight = TrueWeight; |
| 6387 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 6388 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6389 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6390 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6391 | |
| 6392 | NewTrueWeight = TrueWeight; |
| 6393 | NewFalseWeight = 2 * FalseWeight; |
| 6394 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6395 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6396 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6397 | } |
| 6398 | } else { |
| 6399 | // Codegen X & Y as: |
| 6400 | // BB1: |
| 6401 | // jmp_if_X TmpBB |
| 6402 | // jmp FBB |
| 6403 | // TmpBB: |
| 6404 | // jmp_if_Y TBB |
| 6405 | // jmp FBB |
| 6406 | // |
| 6407 | // This requires creation of TmpBB after CurBB. |
| 6408 | |
| 6409 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 6410 | // The requirement is that |
| 6411 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 6412 | // = FalseProb for orignal BB. |
| 6413 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6414 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 6415 | // assumes that |
| 6416 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 6417 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6418 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6419 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 6420 | uint64_t NewFalseWeight = FalseWeight; |
| 6421 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6422 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6423 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6424 | |
| 6425 | NewTrueWeight = 2 * TrueWeight; |
| 6426 | NewFalseWeight = FalseWeight; |
| 6427 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6428 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6429 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6430 | } |
| 6431 | } |
| 6432 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6433 | // 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] | 6434 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6435 | ModifiedDT = true; |
| 6436 | |
| 6437 | MadeChange = true; |
| 6438 | |
| 6439 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 6440 | TmpBB->dump()); |
| 6441 | } |
| 6442 | return MadeChange; |
| 6443 | } |