| File: | src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/CodeGen/CodeGenPrepare.cpp |
| Warning: | line 2360, column 10 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 1 | //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// | ||||
| 2 | // | ||||
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
| 4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
| 6 | // | ||||
| 7 | //===----------------------------------------------------------------------===// | ||||
| 8 | // | ||||
| 9 | // This pass munges the code in the input function to better prepare it for | ||||
| 10 | // SelectionDAG-based code generation. This works around limitations in it's | ||||
| 11 | // basic-block-at-a-time approach. It should eventually be removed. | ||||
| 12 | // | ||||
| 13 | //===----------------------------------------------------------------------===// | ||||
| 14 | |||||
| 15 | #include "llvm/ADT/APInt.h" | ||||
| 16 | #include "llvm/ADT/ArrayRef.h" | ||||
| 17 | #include "llvm/ADT/DenseMap.h" | ||||
| 18 | #include "llvm/ADT/MapVector.h" | ||||
| 19 | #include "llvm/ADT/PointerIntPair.h" | ||||
| 20 | #include "llvm/ADT/STLExtras.h" | ||||
| 21 | #include "llvm/ADT/SmallPtrSet.h" | ||||
| 22 | #include "llvm/ADT/SmallVector.h" | ||||
| 23 | #include "llvm/ADT/Statistic.h" | ||||
| 24 | #include "llvm/Analysis/BlockFrequencyInfo.h" | ||||
| 25 | #include "llvm/Analysis/BranchProbabilityInfo.h" | ||||
| 26 | #include "llvm/Analysis/ConstantFolding.h" | ||||
| 27 | #include "llvm/Analysis/InstructionSimplify.h" | ||||
| 28 | #include "llvm/Analysis/LoopInfo.h" | ||||
| 29 | #include "llvm/Analysis/MemoryBuiltins.h" | ||||
| 30 | #include "llvm/Analysis/ProfileSummaryInfo.h" | ||||
| 31 | #include "llvm/Analysis/TargetLibraryInfo.h" | ||||
| 32 | #include "llvm/Analysis/TargetTransformInfo.h" | ||||
| 33 | #include "llvm/Analysis/ValueTracking.h" | ||||
| 34 | #include "llvm/Analysis/VectorUtils.h" | ||||
| 35 | #include "llvm/CodeGen/Analysis.h" | ||||
| 36 | #include "llvm/CodeGen/ISDOpcodes.h" | ||||
| 37 | #include "llvm/CodeGen/SelectionDAGNodes.h" | ||||
| 38 | #include "llvm/CodeGen/TargetLowering.h" | ||||
| 39 | #include "llvm/CodeGen/TargetPassConfig.h" | ||||
| 40 | #include "llvm/CodeGen/TargetSubtargetInfo.h" | ||||
| 41 | #include "llvm/CodeGen/ValueTypes.h" | ||||
| 42 | #include "llvm/Config/llvm-config.h" | ||||
| 43 | #include "llvm/IR/Argument.h" | ||||
| 44 | #include "llvm/IR/Attributes.h" | ||||
| 45 | #include "llvm/IR/BasicBlock.h" | ||||
| 46 | #include "llvm/IR/Constant.h" | ||||
| 47 | #include "llvm/IR/Constants.h" | ||||
| 48 | #include "llvm/IR/DataLayout.h" | ||||
| 49 | #include "llvm/IR/DebugInfo.h" | ||||
| 50 | #include "llvm/IR/DerivedTypes.h" | ||||
| 51 | #include "llvm/IR/Dominators.h" | ||||
| 52 | #include "llvm/IR/Function.h" | ||||
| 53 | #include "llvm/IR/GetElementPtrTypeIterator.h" | ||||
| 54 | #include "llvm/IR/GlobalValue.h" | ||||
| 55 | #include "llvm/IR/GlobalVariable.h" | ||||
| 56 | #include "llvm/IR/IRBuilder.h" | ||||
| 57 | #include "llvm/IR/InlineAsm.h" | ||||
| 58 | #include "llvm/IR/InstrTypes.h" | ||||
| 59 | #include "llvm/IR/Instruction.h" | ||||
| 60 | #include "llvm/IR/Instructions.h" | ||||
| 61 | #include "llvm/IR/IntrinsicInst.h" | ||||
| 62 | #include "llvm/IR/Intrinsics.h" | ||||
| 63 | #include "llvm/IR/IntrinsicsAArch64.h" | ||||
| 64 | #include "llvm/IR/LLVMContext.h" | ||||
| 65 | #include "llvm/IR/MDBuilder.h" | ||||
| 66 | #include "llvm/IR/Module.h" | ||||
| 67 | #include "llvm/IR/Operator.h" | ||||
| 68 | #include "llvm/IR/PatternMatch.h" | ||||
| 69 | #include "llvm/IR/Statepoint.h" | ||||
| 70 | #include "llvm/IR/Type.h" | ||||
| 71 | #include "llvm/IR/Use.h" | ||||
| 72 | #include "llvm/IR/User.h" | ||||
| 73 | #include "llvm/IR/Value.h" | ||||
| 74 | #include "llvm/IR/ValueHandle.h" | ||||
| 75 | #include "llvm/IR/ValueMap.h" | ||||
| 76 | #include "llvm/InitializePasses.h" | ||||
| 77 | #include "llvm/Pass.h" | ||||
| 78 | #include "llvm/Support/BlockFrequency.h" | ||||
| 79 | #include "llvm/Support/BranchProbability.h" | ||||
| 80 | #include "llvm/Support/Casting.h" | ||||
| 81 | #include "llvm/Support/CommandLine.h" | ||||
| 82 | #include "llvm/Support/Compiler.h" | ||||
| 83 | #include "llvm/Support/Debug.h" | ||||
| 84 | #include "llvm/Support/ErrorHandling.h" | ||||
| 85 | #include "llvm/Support/MachineValueType.h" | ||||
| 86 | #include "llvm/Support/MathExtras.h" | ||||
| 87 | #include "llvm/Support/raw_ostream.h" | ||||
| 88 | #include "llvm/Target/TargetMachine.h" | ||||
| 89 | #include "llvm/Target/TargetOptions.h" | ||||
| 90 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" | ||||
| 91 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" | ||||
| 92 | #include "llvm/Transforms/Utils/Local.h" | ||||
| 93 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" | ||||
| 94 | #include "llvm/Transforms/Utils/SizeOpts.h" | ||||
| 95 | #include <algorithm> | ||||
| 96 | #include <cassert> | ||||
| 97 | #include <cstdint> | ||||
| 98 | #include <iterator> | ||||
| 99 | #include <limits> | ||||
| 100 | #include <memory> | ||||
| 101 | #include <utility> | ||||
| 102 | #include <vector> | ||||
| 103 | |||||
| 104 | using namespace llvm; | ||||
| 105 | using namespace llvm::PatternMatch; | ||||
| 106 | |||||
| 107 | #define DEBUG_TYPE"codegenprepare" "codegenprepare" | ||||
| 108 | |||||
| 109 | STATISTIC(NumBlocksElim, "Number of blocks eliminated")static llvm::Statistic NumBlocksElim = {"codegenprepare", "NumBlocksElim" , "Number of blocks eliminated"}; | ||||
| 110 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated")static llvm::Statistic NumPHIsElim = {"codegenprepare", "NumPHIsElim" , "Number of trivial PHIs eliminated"}; | ||||
| 111 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts")static llvm::Statistic NumGEPsElim = {"codegenprepare", "NumGEPsElim" , "Number of GEPs converted to casts"}; | ||||
| 112 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses" , "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps" } | ||||
| 113 | "sunken Cmps")static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses" , "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps" }; | ||||
| 114 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses" , "Number of uses of Cast expressions replaced with uses " "of sunken Casts" } | ||||
| 115 | "of sunken Casts")static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses" , "Number of uses of Cast expressions replaced with uses " "of sunken Casts" }; | ||||
| 116 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts" , "Number of memory instructions whose address " "computations were sunk" } | ||||
| 117 | "computations were sunk")static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts" , "Number of memory instructions whose address " "computations were sunk" }; | ||||
| 118 | STATISTIC(NumMemoryInstsPhiCreated,static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare" , "NumMemoryInstsPhiCreated", "Number of phis created when address " "computations were sunk to memory instructions"} | ||||
| 119 | "Number of phis created when address "static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare" , "NumMemoryInstsPhiCreated", "Number of phis created when address " "computations were sunk to memory instructions"} | ||||
| 120 | "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare" , "NumMemoryInstsPhiCreated", "Number of phis created when address " "computations were sunk to memory instructions"}; | ||||
| 121 | STATISTIC(NumMemoryInstsSelectCreated,static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare" , "NumMemoryInstsSelectCreated", "Number of select created when address " "computations were sunk to memory instructions"} | ||||
| 122 | "Number of select created when address "static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare" , "NumMemoryInstsSelectCreated", "Number of select created when address " "computations were sunk to memory instructions"} | ||||
| 123 | "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare" , "NumMemoryInstsSelectCreated", "Number of select created when address " "computations were sunk to memory instructions"}; | ||||
| 124 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads")static llvm::Statistic NumExtsMoved = {"codegenprepare", "NumExtsMoved" , "Number of [s|z]ext instructions combined with loads"}; | ||||
| 125 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized")static llvm::Statistic NumExtUses = {"codegenprepare", "NumExtUses" , "Number of uses of [s|z]ext instructions optimized"}; | ||||
| 126 | STATISTIC(NumAndsAdded,static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded" , "Number of and mask instructions added to form ext loads"} | ||||
| 127 | "Number of and mask instructions added to form ext loads")static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded" , "Number of and mask instructions added to form ext loads"}; | ||||
| 128 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized")static llvm::Statistic NumAndUses = {"codegenprepare", "NumAndUses" , "Number of uses of and mask instructions optimized"}; | ||||
| 129 | STATISTIC(NumRetsDup, "Number of return instructions duplicated")static llvm::Statistic NumRetsDup = {"codegenprepare", "NumRetsDup" , "Number of return instructions duplicated"}; | ||||
| 130 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved")static llvm::Statistic NumDbgValueMoved = {"codegenprepare", "NumDbgValueMoved" , "Number of debug value instructions moved"}; | ||||
| 131 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches")static llvm::Statistic NumSelectsExpanded = {"codegenprepare" , "NumSelectsExpanded", "Number of selects turned into branches" }; | ||||
| 132 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed")static llvm::Statistic NumStoreExtractExposed = {"codegenprepare" , "NumStoreExtractExposed", "Number of store(extractelement) exposed" }; | ||||
| 133 | |||||
| 134 | static cl::opt<bool> DisableBranchOpts( | ||||
| 135 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), | ||||
| 136 | cl::desc("Disable branch optimizations in CodeGenPrepare")); | ||||
| 137 | |||||
| 138 | static cl::opt<bool> | ||||
| 139 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), | ||||
| 140 | cl::desc("Disable GC optimizations in CodeGenPrepare")); | ||||
| 141 | |||||
| 142 | static cl::opt<bool> DisableSelectToBranch( | ||||
| 143 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), | ||||
| 144 | cl::desc("Disable select to branch conversion.")); | ||||
| 145 | |||||
| 146 | static cl::opt<bool> AddrSinkUsingGEPs( | ||||
| 147 | "addr-sink-using-gep", cl::Hidden, cl::init(true), | ||||
| 148 | cl::desc("Address sinking in CGP using GEPs.")); | ||||
| 149 | |||||
| 150 | static cl::opt<bool> EnableAndCmpSinking( | ||||
| 151 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), | ||||
| 152 | cl::desc("Enable sinkinig and/cmp into branches.")); | ||||
| 153 | |||||
| 154 | static cl::opt<bool> DisableStoreExtract( | ||||
| 155 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), | ||||
| 156 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); | ||||
| 157 | |||||
| 158 | static cl::opt<bool> StressStoreExtract( | ||||
| 159 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), | ||||
| 160 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); | ||||
| 161 | |||||
| 162 | static cl::opt<bool> DisableExtLdPromotion( | ||||
| 163 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), | ||||
| 164 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " | ||||
| 165 | "CodeGenPrepare")); | ||||
| 166 | |||||
| 167 | static cl::opt<bool> StressExtLdPromotion( | ||||
| 168 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), | ||||
| 169 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " | ||||
| 170 | "optimization in CodeGenPrepare")); | ||||
| 171 | |||||
| 172 | static cl::opt<bool> DisablePreheaderProtect( | ||||
| 173 | "disable-preheader-prot", cl::Hidden, cl::init(false), | ||||
| 174 | cl::desc("Disable protection against removing loop preheaders")); | ||||
| 175 | |||||
| 176 | static cl::opt<bool> ProfileGuidedSectionPrefix( | ||||
| 177 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, | ||||
| 178 | cl::desc("Use profile info to add section prefix for hot/cold functions")); | ||||
| 179 | |||||
| 180 | static cl::opt<bool> ProfileUnknownInSpecialSection( | ||||
| 181 | "profile-unknown-in-special-section", cl::Hidden, cl::init(false), | ||||
| 182 | cl::ZeroOrMore, | ||||
| 183 | cl::desc("In profiling mode like sampleFDO, if a function doesn't have " | ||||
| 184 | "profile, we cannot tell the function is cold for sure because " | ||||
| 185 | "it may be a function newly added without ever being sampled. " | ||||
| 186 | "With the flag enabled, compiler can put such profile unknown " | ||||
| 187 | "functions into a special section, so runtime system can choose " | ||||
| 188 | "to handle it in a different way than .text section, to save " | ||||
| 189 | "RAM for example. ")); | ||||
| 190 | |||||
| 191 | static cl::opt<unsigned> FreqRatioToSkipMerge( | ||||
| 192 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), | ||||
| 193 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " | ||||
| 194 | "(frequency of destination block) is greater than this ratio")); | ||||
| 195 | |||||
| 196 | static cl::opt<bool> ForceSplitStore( | ||||
| 197 | "force-split-store", cl::Hidden, cl::init(false), | ||||
| 198 | cl::desc("Force store splitting no matter what the target query says.")); | ||||
| 199 | |||||
| 200 | static cl::opt<bool> | ||||
| 201 | EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, | ||||
| 202 | cl::desc("Enable merging of redundant sexts when one is dominating" | ||||
| 203 | " the other."), cl::init(true)); | ||||
| 204 | |||||
| 205 | static cl::opt<bool> DisableComplexAddrModes( | ||||
| 206 | "disable-complex-addr-modes", cl::Hidden, cl::init(false), | ||||
| 207 | cl::desc("Disables combining addressing modes with different parts " | ||||
| 208 | "in optimizeMemoryInst.")); | ||||
| 209 | |||||
| 210 | static cl::opt<bool> | ||||
| 211 | AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), | ||||
| 212 | cl::desc("Allow creation of Phis in Address sinking.")); | ||||
| 213 | |||||
| 214 | static cl::opt<bool> | ||||
| 215 | AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), | ||||
| 216 | cl::desc("Allow creation of selects in Address sinking.")); | ||||
| 217 | |||||
| 218 | static cl::opt<bool> AddrSinkCombineBaseReg( | ||||
| 219 | "addr-sink-combine-base-reg", cl::Hidden, cl::init(true), | ||||
| 220 | cl::desc("Allow combining of BaseReg field in Address sinking.")); | ||||
| 221 | |||||
| 222 | static cl::opt<bool> AddrSinkCombineBaseGV( | ||||
| 223 | "addr-sink-combine-base-gv", cl::Hidden, cl::init(true), | ||||
| 224 | cl::desc("Allow combining of BaseGV field in Address sinking.")); | ||||
| 225 | |||||
| 226 | static cl::opt<bool> AddrSinkCombineBaseOffs( | ||||
| 227 | "addr-sink-combine-base-offs", cl::Hidden, cl::init(true), | ||||
| 228 | cl::desc("Allow combining of BaseOffs field in Address sinking.")); | ||||
| 229 | |||||
| 230 | static cl::opt<bool> AddrSinkCombineScaledReg( | ||||
| 231 | "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), | ||||
| 232 | cl::desc("Allow combining of ScaledReg field in Address sinking.")); | ||||
| 233 | |||||
| 234 | static cl::opt<bool> | ||||
| 235 | EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, | ||||
| 236 | cl::init(true), | ||||
| 237 | cl::desc("Enable splitting large offset of GEP.")); | ||||
| 238 | |||||
| 239 | static cl::opt<bool> EnableICMP_EQToICMP_ST( | ||||
| 240 | "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false), | ||||
| 241 | cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion.")); | ||||
| 242 | |||||
| 243 | static cl::opt<bool> | ||||
| 244 | VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false), | ||||
| 245 | cl::desc("Enable BFI update verification for " | ||||
| 246 | "CodeGenPrepare.")); | ||||
| 247 | |||||
| 248 | static cl::opt<bool> OptimizePhiTypes( | ||||
| 249 | "cgp-optimize-phi-types", cl::Hidden, cl::init(false), | ||||
| 250 | cl::desc("Enable converting phi types in CodeGenPrepare")); | ||||
| 251 | |||||
| 252 | namespace { | ||||
| 253 | |||||
| 254 | enum ExtType { | ||||
| 255 | ZeroExtension, // Zero extension has been seen. | ||||
| 256 | SignExtension, // Sign extension has been seen. | ||||
| 257 | BothExtension // This extension type is used if we saw sext after | ||||
| 258 | // ZeroExtension had been set, or if we saw zext after | ||||
| 259 | // SignExtension had been set. It makes the type | ||||
| 260 | // information of a promoted instruction invalid. | ||||
| 261 | }; | ||||
| 262 | |||||
| 263 | using SetOfInstrs = SmallPtrSet<Instruction *, 16>; | ||||
| 264 | using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>; | ||||
| 265 | using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>; | ||||
| 266 | using SExts = SmallVector<Instruction *, 16>; | ||||
| 267 | using ValueToSExts = DenseMap<Value *, SExts>; | ||||
| 268 | |||||
| 269 | class TypePromotionTransaction; | ||||
| 270 | |||||
| 271 | class CodeGenPrepare : public FunctionPass { | ||||
| 272 | const TargetMachine *TM = nullptr; | ||||
| 273 | const TargetSubtargetInfo *SubtargetInfo; | ||||
| 274 | const TargetLowering *TLI = nullptr; | ||||
| 275 | const TargetRegisterInfo *TRI; | ||||
| 276 | const TargetTransformInfo *TTI = nullptr; | ||||
| 277 | const TargetLibraryInfo *TLInfo; | ||||
| 278 | const LoopInfo *LI; | ||||
| 279 | std::unique_ptr<BlockFrequencyInfo> BFI; | ||||
| 280 | std::unique_ptr<BranchProbabilityInfo> BPI; | ||||
| 281 | ProfileSummaryInfo *PSI; | ||||
| 282 | |||||
| 283 | /// As we scan instructions optimizing them, this is the next instruction | ||||
| 284 | /// to optimize. Transforms that can invalidate this should update it. | ||||
| 285 | BasicBlock::iterator CurInstIterator; | ||||
| 286 | |||||
| 287 | /// Keeps track of non-local addresses that have been sunk into a block. | ||||
| 288 | /// This allows us to avoid inserting duplicate code for blocks with | ||||
| 289 | /// multiple load/stores of the same address. The usage of WeakTrackingVH | ||||
| 290 | /// enables SunkAddrs to be treated as a cache whose entries can be | ||||
| 291 | /// invalidated if a sunken address computation has been erased. | ||||
| 292 | ValueMap<Value*, WeakTrackingVH> SunkAddrs; | ||||
| 293 | |||||
| 294 | /// Keeps track of all instructions inserted for the current function. | ||||
| 295 | SetOfInstrs InsertedInsts; | ||||
| 296 | |||||
| 297 | /// Keeps track of the type of the related instruction before their | ||||
| 298 | /// promotion for the current function. | ||||
| 299 | InstrToOrigTy PromotedInsts; | ||||
| 300 | |||||
| 301 | /// Keep track of instructions removed during promotion. | ||||
| 302 | SetOfInstrs RemovedInsts; | ||||
| 303 | |||||
| 304 | /// Keep track of sext chains based on their initial value. | ||||
| 305 | DenseMap<Value *, Instruction *> SeenChainsForSExt; | ||||
| 306 | |||||
| 307 | /// Keep track of GEPs accessing the same data structures such as structs or | ||||
| 308 | /// arrays that are candidates to be split later because of their large | ||||
| 309 | /// size. | ||||
| 310 | MapVector< | ||||
| 311 | AssertingVH<Value>, | ||||
| 312 | SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>> | ||||
| 313 | LargeOffsetGEPMap; | ||||
| 314 | |||||
| 315 | /// Keep track of new GEP base after splitting the GEPs having large offset. | ||||
| 316 | SmallSet<AssertingVH<Value>, 2> NewGEPBases; | ||||
| 317 | |||||
| 318 | /// Map serial numbers to Large offset GEPs. | ||||
| 319 | DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID; | ||||
| 320 | |||||
| 321 | /// Keep track of SExt promoted. | ||||
| 322 | ValueToSExts ValToSExtendedUses; | ||||
| 323 | |||||
| 324 | /// True if the function has the OptSize attribute. | ||||
| 325 | bool OptSize; | ||||
| 326 | |||||
| 327 | /// DataLayout for the Function being processed. | ||||
| 328 | const DataLayout *DL = nullptr; | ||||
| 329 | |||||
| 330 | /// Building the dominator tree can be expensive, so we only build it | ||||
| 331 | /// lazily and update it when required. | ||||
| 332 | std::unique_ptr<DominatorTree> DT; | ||||
| 333 | |||||
| 334 | public: | ||||
| 335 | static char ID; // Pass identification, replacement for typeid | ||||
| 336 | |||||
| 337 | CodeGenPrepare() : FunctionPass(ID) { | ||||
| 338 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); | ||||
| 339 | } | ||||
| 340 | |||||
| 341 | bool runOnFunction(Function &F) override; | ||||
| 342 | |||||
| 343 | StringRef getPassName() const override { return "CodeGen Prepare"; } | ||||
| 344 | |||||
| 345 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||
| 346 | // FIXME: When we can selectively preserve passes, preserve the domtree. | ||||
| 347 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); | ||||
| 348 | AU.addRequired<TargetLibraryInfoWrapperPass>(); | ||||
| 349 | AU.addRequired<TargetPassConfig>(); | ||||
| 350 | AU.addRequired<TargetTransformInfoWrapperPass>(); | ||||
| 351 | AU.addRequired<LoopInfoWrapperPass>(); | ||||
| 352 | } | ||||
| 353 | |||||
| 354 | private: | ||||
| 355 | template <typename F> | ||||
| 356 | void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) { | ||||
| 357 | // Substituting can cause recursive simplifications, which can invalidate | ||||
| 358 | // our iterator. Use a WeakTrackingVH to hold onto it in case this | ||||
| 359 | // happens. | ||||
| 360 | Value *CurValue = &*CurInstIterator; | ||||
| 361 | WeakTrackingVH IterHandle(CurValue); | ||||
| 362 | |||||
| 363 | f(); | ||||
| 364 | |||||
| 365 | // If the iterator instruction was recursively deleted, start over at the | ||||
| 366 | // start of the block. | ||||
| 367 | if (IterHandle != CurValue) { | ||||
| 368 | CurInstIterator = BB->begin(); | ||||
| 369 | SunkAddrs.clear(); | ||||
| 370 | } | ||||
| 371 | } | ||||
| 372 | |||||
| 373 | // Get the DominatorTree, building if necessary. | ||||
| 374 | DominatorTree &getDT(Function &F) { | ||||
| 375 | if (!DT) | ||||
| 376 | DT = std::make_unique<DominatorTree>(F); | ||||
| 377 | return *DT; | ||||
| 378 | } | ||||
| 379 | |||||
| 380 | void removeAllAssertingVHReferences(Value *V); | ||||
| 381 | bool eliminateAssumptions(Function &F); | ||||
| 382 | bool eliminateFallThrough(Function &F); | ||||
| 383 | bool eliminateMostlyEmptyBlocks(Function &F); | ||||
| 384 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); | ||||
| 385 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; | ||||
| 386 | void eliminateMostlyEmptyBlock(BasicBlock *BB); | ||||
| 387 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, | ||||
| 388 | bool isPreheader); | ||||
| 389 | bool makeBitReverse(Instruction &I); | ||||
| 390 | bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT); | ||||
| 391 | bool optimizeInst(Instruction *I, bool &ModifiedDT); | ||||
| 392 | bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, | ||||
| 393 | Type *AccessTy, unsigned AddrSpace); | ||||
| 394 | bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr); | ||||
| 395 | bool optimizeInlineAsmInst(CallInst *CS); | ||||
| 396 | bool optimizeCallInst(CallInst *CI, bool &ModifiedDT); | ||||
| 397 | bool optimizeExt(Instruction *&I); | ||||
| 398 | bool optimizeExtUses(Instruction *I); | ||||
| 399 | bool optimizeLoadExt(LoadInst *Load); | ||||
| 400 | bool optimizeShiftInst(BinaryOperator *BO); | ||||
| 401 | bool optimizeFunnelShift(IntrinsicInst *Fsh); | ||||
| 402 | bool optimizeSelectInst(SelectInst *SI); | ||||
| 403 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI); | ||||
| 404 | bool optimizeSwitchInst(SwitchInst *SI); | ||||
| 405 | bool optimizeExtractElementInst(Instruction *Inst); | ||||
| 406 | bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT); | ||||
| 407 | bool fixupDbgValue(Instruction *I); | ||||
| 408 | bool placeDbgValues(Function &F); | ||||
| 409 | bool placePseudoProbes(Function &F); | ||||
| 410 | bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, | ||||
| 411 | LoadInst *&LI, Instruction *&Inst, bool HasPromoted); | ||||
| 412 | bool tryToPromoteExts(TypePromotionTransaction &TPT, | ||||
| 413 | const SmallVectorImpl<Instruction *> &Exts, | ||||
| 414 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, | ||||
| 415 | unsigned CreatedInstsCost = 0); | ||||
| 416 | bool mergeSExts(Function &F); | ||||
| 417 | bool splitLargeGEPOffsets(); | ||||
| 418 | bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited, | ||||
| 419 | SmallPtrSetImpl<Instruction *> &DeletedInstrs); | ||||
| 420 | bool optimizePhiTypes(Function &F); | ||||
| 421 | bool performAddressTypePromotion( | ||||
| 422 | Instruction *&Inst, | ||||
| 423 | bool AllowPromotionWithoutCommonHeader, | ||||
| 424 | bool HasPromoted, TypePromotionTransaction &TPT, | ||||
| 425 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); | ||||
| 426 | bool splitBranchCondition(Function &F, bool &ModifiedDT); | ||||
| 427 | bool simplifyOffsetableRelocate(GCStatepointInst &I); | ||||
| 428 | |||||
| 429 | bool tryToSinkFreeOperands(Instruction *I); | ||||
| 430 | bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, | ||||
| 431 | Value *Arg1, CmpInst *Cmp, | ||||
| 432 | Intrinsic::ID IID); | ||||
| 433 | bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT); | ||||
| 434 | bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT); | ||||
| 435 | bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT); | ||||
| 436 | void verifyBFIUpdates(Function &F); | ||||
| 437 | }; | ||||
| 438 | |||||
| 439 | } // end anonymous namespace | ||||
| 440 | |||||
| 441 | char CodeGenPrepare::ID = 0; | ||||
| 442 | |||||
| 443 | INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,static void *initializeCodeGenPreparePassOnce(PassRegistry & Registry) { | ||||
| 444 | "Optimize for code generation", false, false)static void *initializeCodeGenPreparePassOnce(PassRegistry & Registry) { | ||||
| 445 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry); | ||||
| 446 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)initializeProfileSummaryInfoWrapperPassPass(Registry); | ||||
| 447 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry); | ||||
| 448 | INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)initializeTargetPassConfigPass(Registry); | ||||
| 449 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry); | ||||
| 450 | INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,PassInfo *PI = new PassInfo( "Optimize for code generation", "codegenprepare" , &CodeGenPrepare::ID, PassInfo::NormalCtor_t(callDefaultCtor <CodeGenPrepare>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeCodeGenPreparePassFlag ; void llvm::initializeCodeGenPreparePass(PassRegistry &Registry ) { llvm::call_once(InitializeCodeGenPreparePassFlag, initializeCodeGenPreparePassOnce , std::ref(Registry)); } | ||||
| 451 | "Optimize for code generation", false, false)PassInfo *PI = new PassInfo( "Optimize for code generation", "codegenprepare" , &CodeGenPrepare::ID, PassInfo::NormalCtor_t(callDefaultCtor <CodeGenPrepare>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeCodeGenPreparePassFlag ; void llvm::initializeCodeGenPreparePass(PassRegistry &Registry ) { llvm::call_once(InitializeCodeGenPreparePassFlag, initializeCodeGenPreparePassOnce , std::ref(Registry)); } | ||||
| 452 | |||||
| 453 | FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); } | ||||
| 454 | |||||
| 455 | bool CodeGenPrepare::runOnFunction(Function &F) { | ||||
| 456 | if (skipFunction(F)) | ||||
| 457 | return false; | ||||
| 458 | |||||
| 459 | DL = &F.getParent()->getDataLayout(); | ||||
| 460 | |||||
| 461 | bool EverMadeChange = false; | ||||
| 462 | // Clear per function information. | ||||
| 463 | InsertedInsts.clear(); | ||||
| 464 | PromotedInsts.clear(); | ||||
| 465 | |||||
| 466 | TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); | ||||
| 467 | SubtargetInfo = TM->getSubtargetImpl(F); | ||||
| 468 | TLI = SubtargetInfo->getTargetLowering(); | ||||
| 469 | TRI = SubtargetInfo->getRegisterInfo(); | ||||
| 470 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); | ||||
| 471 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); | ||||
| 472 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); | ||||
| 473 | BPI.reset(new BranchProbabilityInfo(F, *LI)); | ||||
| 474 | BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI)); | ||||
| 475 | PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); | ||||
| 476 | OptSize = F.hasOptSize(); | ||||
| 477 | if (ProfileGuidedSectionPrefix) { | ||||
| 478 | // The hot attribute overwrites profile count based hotness while profile | ||||
| 479 | // counts based hotness overwrite the cold attribute. | ||||
| 480 | // This is a conservative behabvior. | ||||
| 481 | if (F.hasFnAttribute(Attribute::Hot) || | ||||
| 482 | PSI->isFunctionHotInCallGraph(&F, *BFI)) | ||||
| 483 | F.setSectionPrefix("hot"); | ||||
| 484 | // If PSI shows this function is not hot, we will placed the function | ||||
| 485 | // into unlikely section if (1) PSI shows this is a cold function, or | ||||
| 486 | // (2) the function has a attribute of cold. | ||||
| 487 | else if (PSI->isFunctionColdInCallGraph(&F, *BFI) || | ||||
| 488 | F.hasFnAttribute(Attribute::Cold)) | ||||
| 489 | F.setSectionPrefix("unlikely"); | ||||
| 490 | else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() && | ||||
| 491 | PSI->isFunctionHotnessUnknown(F)) | ||||
| 492 | F.setSectionPrefix("unknown"); | ||||
| 493 | } | ||||
| 494 | |||||
| 495 | /// This optimization identifies DIV instructions that can be | ||||
| 496 | /// profitably bypassed and carried out with a shorter, faster divide. | ||||
| 497 | if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) { | ||||
| 498 | const DenseMap<unsigned int, unsigned int> &BypassWidths = | ||||
| 499 | TLI->getBypassSlowDivWidths(); | ||||
| 500 | BasicBlock* BB = &*F.begin(); | ||||
| 501 | while (BB != nullptr) { | ||||
| 502 | // bypassSlowDivision may create new BBs, but we don't want to reapply the | ||||
| 503 | // optimization to those blocks. | ||||
| 504 | BasicBlock* Next = BB->getNextNode(); | ||||
| 505 | // F.hasOptSize is already checked in the outer if statement. | ||||
| 506 | if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) | ||||
| 507 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); | ||||
| 508 | BB = Next; | ||||
| 509 | } | ||||
| 510 | } | ||||
| 511 | |||||
| 512 | // Get rid of @llvm.assume builtins before attempting to eliminate empty | ||||
| 513 | // blocks, since there might be blocks that only contain @llvm.assume calls | ||||
| 514 | // (plus arguments that we can get rid of). | ||||
| 515 | EverMadeChange |= eliminateAssumptions(F); | ||||
| 516 | |||||
| 517 | // Eliminate blocks that contain only PHI nodes and an | ||||
| 518 | // unconditional branch. | ||||
| 519 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); | ||||
| 520 | |||||
| 521 | bool ModifiedDT = false; | ||||
| 522 | if (!DisableBranchOpts) | ||||
| 523 | EverMadeChange |= splitBranchCondition(F, ModifiedDT); | ||||
| 524 | |||||
| 525 | // Split some critical edges where one of the sources is an indirect branch, | ||||
| 526 | // to help generate sane code for PHIs involving such edges. | ||||
| 527 | EverMadeChange |= SplitIndirectBrCriticalEdges(F); | ||||
| 528 | |||||
| 529 | bool MadeChange = true; | ||||
| 530 | while (MadeChange) { | ||||
| 531 | MadeChange = false; | ||||
| 532 | DT.reset(); | ||||
| 533 | for (Function::iterator I = F.begin(); I != F.end(); ) { | ||||
| 534 | BasicBlock *BB = &*I++; | ||||
| 535 | bool ModifiedDTOnIteration = false; | ||||
| 536 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); | ||||
| 537 | |||||
| 538 | // Restart BB iteration if the dominator tree of the Function was changed | ||||
| 539 | if (ModifiedDTOnIteration) | ||||
| 540 | break; | ||||
| 541 | } | ||||
| 542 | if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) | ||||
| 543 | MadeChange |= mergeSExts(F); | ||||
| 544 | if (!LargeOffsetGEPMap.empty()) | ||||
| 545 | MadeChange |= splitLargeGEPOffsets(); | ||||
| 546 | MadeChange |= optimizePhiTypes(F); | ||||
| 547 | |||||
| 548 | if (MadeChange) | ||||
| 549 | eliminateFallThrough(F); | ||||
| 550 | |||||
| 551 | // Really free removed instructions during promotion. | ||||
| 552 | for (Instruction *I : RemovedInsts) | ||||
| 553 | I->deleteValue(); | ||||
| 554 | |||||
| 555 | EverMadeChange |= MadeChange; | ||||
| 556 | SeenChainsForSExt.clear(); | ||||
| 557 | ValToSExtendedUses.clear(); | ||||
| 558 | RemovedInsts.clear(); | ||||
| 559 | LargeOffsetGEPMap.clear(); | ||||
| 560 | LargeOffsetGEPID.clear(); | ||||
| 561 | } | ||||
| 562 | |||||
| 563 | NewGEPBases.clear(); | ||||
| 564 | SunkAddrs.clear(); | ||||
| 565 | |||||
| 566 | if (!DisableBranchOpts) { | ||||
| 567 | MadeChange = false; | ||||
| 568 | // Use a set vector to get deterministic iteration order. The order the | ||||
| 569 | // blocks are removed may affect whether or not PHI nodes in successors | ||||
| 570 | // are removed. | ||||
| 571 | SmallSetVector<BasicBlock*, 8> WorkList; | ||||
| 572 | for (BasicBlock &BB : F) { | ||||
| 573 | SmallVector<BasicBlock *, 2> Successors(successors(&BB)); | ||||
| 574 | MadeChange |= ConstantFoldTerminator(&BB, true); | ||||
| 575 | if (!MadeChange) continue; | ||||
| 576 | |||||
| 577 | for (BasicBlock *Succ : Successors) | ||||
| 578 | if (pred_empty(Succ)) | ||||
| 579 | WorkList.insert(Succ); | ||||
| 580 | } | ||||
| 581 | |||||
| 582 | // Delete the dead blocks and any of their dead successors. | ||||
| 583 | MadeChange |= !WorkList.empty(); | ||||
| 584 | while (!WorkList.empty()) { | ||||
| 585 | BasicBlock *BB = WorkList.pop_back_val(); | ||||
| 586 | SmallVector<BasicBlock*, 2> Successors(successors(BB)); | ||||
| 587 | |||||
| 588 | DeleteDeadBlock(BB); | ||||
| 589 | |||||
| 590 | for (BasicBlock *Succ : Successors) | ||||
| 591 | if (pred_empty(Succ)) | ||||
| 592 | WorkList.insert(Succ); | ||||
| 593 | } | ||||
| 594 | |||||
| 595 | // Merge pairs of basic blocks with unconditional branches, connected by | ||||
| 596 | // a single edge. | ||||
| 597 | if (EverMadeChange || MadeChange) | ||||
| 598 | MadeChange |= eliminateFallThrough(F); | ||||
| 599 | |||||
| 600 | EverMadeChange |= MadeChange; | ||||
| 601 | } | ||||
| 602 | |||||
| 603 | if (!DisableGCOpts) { | ||||
| 604 | SmallVector<GCStatepointInst *, 2> Statepoints; | ||||
| 605 | for (BasicBlock &BB : F) | ||||
| 606 | for (Instruction &I : BB) | ||||
| 607 | if (auto *SP = dyn_cast<GCStatepointInst>(&I)) | ||||
| 608 | Statepoints.push_back(SP); | ||||
| 609 | for (auto &I : Statepoints) | ||||
| 610 | EverMadeChange |= simplifyOffsetableRelocate(*I); | ||||
| 611 | } | ||||
| 612 | |||||
| 613 | // Do this last to clean up use-before-def scenarios introduced by other | ||||
| 614 | // preparatory transforms. | ||||
| 615 | EverMadeChange |= placeDbgValues(F); | ||||
| 616 | EverMadeChange |= placePseudoProbes(F); | ||||
| 617 | |||||
| 618 | #ifndef NDEBUG1 | ||||
| 619 | if (VerifyBFIUpdates) | ||||
| 620 | verifyBFIUpdates(F); | ||||
| 621 | #endif | ||||
| 622 | |||||
| 623 | return EverMadeChange; | ||||
| 624 | } | ||||
| 625 | |||||
| 626 | bool CodeGenPrepare::eliminateAssumptions(Function &F) { | ||||
| 627 | bool MadeChange = false; | ||||
| 628 | for (BasicBlock &BB : F) { | ||||
| 629 | CurInstIterator = BB.begin(); | ||||
| 630 | while (CurInstIterator != BB.end()) { | ||||
| 631 | Instruction *I = &*(CurInstIterator++); | ||||
| 632 | if (auto *Assume = dyn_cast<AssumeInst>(I)) { | ||||
| 633 | MadeChange = true; | ||||
| 634 | Value *Operand = Assume->getOperand(0); | ||||
| 635 | Assume->eraseFromParent(); | ||||
| 636 | |||||
| 637 | resetIteratorIfInvalidatedWhileCalling(&BB, [&]() { | ||||
| 638 | RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr); | ||||
| 639 | }); | ||||
| 640 | } | ||||
| 641 | } | ||||
| 642 | } | ||||
| 643 | return MadeChange; | ||||
| 644 | } | ||||
| 645 | |||||
| 646 | /// An instruction is about to be deleted, so remove all references to it in our | ||||
| 647 | /// GEP-tracking data strcutures. | ||||
| 648 | void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) { | ||||
| 649 | LargeOffsetGEPMap.erase(V); | ||||
| 650 | NewGEPBases.erase(V); | ||||
| 651 | |||||
| 652 | auto GEP = dyn_cast<GetElementPtrInst>(V); | ||||
| 653 | if (!GEP) | ||||
| 654 | return; | ||||
| 655 | |||||
| 656 | LargeOffsetGEPID.erase(GEP); | ||||
| 657 | |||||
| 658 | auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand()); | ||||
| 659 | if (VecI == LargeOffsetGEPMap.end()) | ||||
| 660 | return; | ||||
| 661 | |||||
| 662 | auto &GEPVector = VecI->second; | ||||
| 663 | const auto &I = | ||||
| 664 | llvm::find_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; }); | ||||
| 665 | if (I == GEPVector.end()) | ||||
| 666 | return; | ||||
| 667 | |||||
| 668 | GEPVector.erase(I); | ||||
| 669 | if (GEPVector.empty()) | ||||
| 670 | LargeOffsetGEPMap.erase(VecI); | ||||
| 671 | } | ||||
| 672 | |||||
| 673 | // Verify BFI has been updated correctly by recomputing BFI and comparing them. | ||||
| 674 | void LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) CodeGenPrepare::verifyBFIUpdates(Function &F) { | ||||
| 675 | DominatorTree NewDT(F); | ||||
| 676 | LoopInfo NewLI(NewDT); | ||||
| 677 | BranchProbabilityInfo NewBPI(F, NewLI, TLInfo); | ||||
| 678 | BlockFrequencyInfo NewBFI(F, NewBPI, NewLI); | ||||
| 679 | NewBFI.verifyMatch(*BFI); | ||||
| 680 | } | ||||
| 681 | |||||
| 682 | /// Merge basic blocks which are connected by a single edge, where one of the | ||||
| 683 | /// basic blocks has a single successor pointing to the other basic block, | ||||
| 684 | /// which has a single predecessor. | ||||
| 685 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { | ||||
| 686 | bool Changed = false; | ||||
| 687 | // Scan all of the blocks in the function, except for the entry block. | ||||
| 688 | // Use a temporary array to avoid iterator being invalidated when | ||||
| 689 | // deleting blocks. | ||||
| 690 | SmallVector<WeakTrackingVH, 16> Blocks; | ||||
| 691 | for (auto &Block : llvm::drop_begin(F)) | ||||
| 692 | Blocks.push_back(&Block); | ||||
| 693 | |||||
| 694 | SmallSet<WeakTrackingVH, 16> Preds; | ||||
| 695 | for (auto &Block : Blocks) { | ||||
| 696 | auto *BB = cast_or_null<BasicBlock>(Block); | ||||
| 697 | if (!BB) | ||||
| 698 | continue; | ||||
| 699 | // If the destination block has a single pred, then this is a trivial | ||||
| 700 | // edge, just collapse it. | ||||
| 701 | BasicBlock *SinglePred = BB->getSinglePredecessor(); | ||||
| 702 | |||||
| 703 | // Don't merge if BB's address is taken. | ||||
| 704 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; | ||||
| 705 | |||||
| 706 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); | ||||
| 707 | if (Term && !Term->isConditional()) { | ||||
| 708 | Changed = true; | ||||
| 709 | LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n")do { } while (false); | ||||
| 710 | |||||
| 711 | // Merge BB into SinglePred and delete it. | ||||
| 712 | MergeBlockIntoPredecessor(BB); | ||||
| 713 | Preds.insert(SinglePred); | ||||
| 714 | } | ||||
| 715 | } | ||||
| 716 | |||||
| 717 | // (Repeatedly) merging blocks into their predecessors can create redundant | ||||
| 718 | // debug intrinsics. | ||||
| 719 | for (auto &Pred : Preds) | ||||
| 720 | if (auto *BB = cast_or_null<BasicBlock>(Pred)) | ||||
| 721 | RemoveRedundantDbgInstrs(BB); | ||||
| 722 | |||||
| 723 | return Changed; | ||||
| 724 | } | ||||
| 725 | |||||
| 726 | /// Find a destination block from BB if BB is mergeable empty block. | ||||
| 727 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { | ||||
| 728 | // If this block doesn't end with an uncond branch, ignore it. | ||||
| 729 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); | ||||
| 730 | if (!BI || !BI->isUnconditional()) | ||||
| 731 | return nullptr; | ||||
| 732 | |||||
| 733 | // If the instruction before the branch (skipping debug info) isn't a phi | ||||
| 734 | // node, then other stuff is happening here. | ||||
| 735 | BasicBlock::iterator BBI = BI->getIterator(); | ||||
| 736 | if (BBI != BB->begin()) { | ||||
| 737 | --BBI; | ||||
| 738 | while (isa<DbgInfoIntrinsic>(BBI)) { | ||||
| 739 | if (BBI == BB->begin()) | ||||
| 740 | break; | ||||
| 741 | --BBI; | ||||
| 742 | } | ||||
| 743 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) | ||||
| 744 | return nullptr; | ||||
| 745 | } | ||||
| 746 | |||||
| 747 | // Do not break infinite loops. | ||||
| 748 | BasicBlock *DestBB = BI->getSuccessor(0); | ||||
| 749 | if (DestBB == BB) | ||||
| 750 | return nullptr; | ||||
| 751 | |||||
| 752 | if (!canMergeBlocks(BB, DestBB)) | ||||
| 753 | DestBB = nullptr; | ||||
| 754 | |||||
| 755 | return DestBB; | ||||
| 756 | } | ||||
| 757 | |||||
| 758 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an | ||||
| 759 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split | ||||
| 760 | /// edges in ways that are non-optimal for isel. Start by eliminating these | ||||
| 761 | /// blocks so we can split them the way we want them. | ||||
| 762 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { | ||||
| 763 | SmallPtrSet<BasicBlock *, 16> Preheaders; | ||||
| 764 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); | ||||
| 765 | while (!LoopList.empty()) { | ||||
| 766 | Loop *L = LoopList.pop_back_val(); | ||||
| 767 | llvm::append_range(LoopList, *L); | ||||
| 768 | if (BasicBlock *Preheader = L->getLoopPreheader()) | ||||
| 769 | Preheaders.insert(Preheader); | ||||
| 770 | } | ||||
| 771 | |||||
| 772 | bool MadeChange = false; | ||||
| 773 | // Copy blocks into a temporary array to avoid iterator invalidation issues | ||||
| 774 | // as we remove them. | ||||
| 775 | // Note that this intentionally skips the entry block. | ||||
| 776 | SmallVector<WeakTrackingVH, 16> Blocks; | ||||
| 777 | for (auto &Block : llvm::drop_begin(F)) | ||||
| 778 | Blocks.push_back(&Block); | ||||
| 779 | |||||
| 780 | for (auto &Block : Blocks) { | ||||
| 781 | BasicBlock *BB = cast_or_null<BasicBlock>(Block); | ||||
| 782 | if (!BB) | ||||
| 783 | continue; | ||||
| 784 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); | ||||
| 785 | if (!DestBB || | ||||
| 786 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) | ||||
| 787 | continue; | ||||
| 788 | |||||
| 789 | eliminateMostlyEmptyBlock(BB); | ||||
| 790 | MadeChange = true; | ||||
| 791 | } | ||||
| 792 | return MadeChange; | ||||
| 793 | } | ||||
| 794 | |||||
| 795 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, | ||||
| 796 | BasicBlock *DestBB, | ||||
| 797 | bool isPreheader) { | ||||
| 798 | // Do not delete loop preheaders if doing so would create a critical edge. | ||||
| 799 | // Loop preheaders can be good locations to spill registers. If the | ||||
| 800 | // preheader is deleted and we create a critical edge, registers may be | ||||
| 801 | // spilled in the loop body instead. | ||||
| 802 | if (!DisablePreheaderProtect && isPreheader && | ||||
| 803 | !(BB->getSinglePredecessor() && | ||||
| 804 | BB->getSinglePredecessor()->getSingleSuccessor())) | ||||
| 805 | return false; | ||||
| 806 | |||||
| 807 | // Skip merging if the block's successor is also a successor to any callbr | ||||
| 808 | // that leads to this block. | ||||
| 809 | // FIXME: Is this really needed? Is this a correctness issue? | ||||
| 810 | for (BasicBlock *Pred : predecessors(BB)) { | ||||
| 811 | if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator())) | ||||
| 812 | for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i) | ||||
| 813 | if (DestBB == CBI->getSuccessor(i)) | ||||
| 814 | return false; | ||||
| 815 | } | ||||
| 816 | |||||
| 817 | // Try to skip merging if the unique predecessor of BB is terminated by a | ||||
| 818 | // switch or indirect branch instruction, and BB is used as an incoming block | ||||
| 819 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to | ||||
| 820 | // add COPY instructions in the predecessor of BB instead of BB (if it is not | ||||
| 821 | // merged). Note that the critical edge created by merging such blocks wont be | ||||
| 822 | // split in MachineSink because the jump table is not analyzable. By keeping | ||||
| 823 | // such empty block (BB), ISel will place COPY instructions in BB, not in the | ||||
| 824 | // predecessor of BB. | ||||
| 825 | BasicBlock *Pred = BB->getUniquePredecessor(); | ||||
| 826 | if (!Pred || | ||||
| 827 | !(isa<SwitchInst>(Pred->getTerminator()) || | ||||
| 828 | isa<IndirectBrInst>(Pred->getTerminator()))) | ||||
| 829 | return true; | ||||
| 830 | |||||
| 831 | if (BB->getTerminator() != BB->getFirstNonPHIOrDbg()) | ||||
| 832 | return true; | ||||
| 833 | |||||
| 834 | // We use a simple cost heuristic which determine skipping merging is | ||||
| 835 | // profitable if the cost of skipping merging is less than the cost of | ||||
| 836 | // merging : Cost(skipping merging) < Cost(merging BB), where the | ||||
| 837 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and | ||||
| 838 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). | ||||
| 839 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : | ||||
| 840 | // Freq(Pred) / Freq(BB) > 2. | ||||
| 841 | // Note that if there are multiple empty blocks sharing the same incoming | ||||
| 842 | // value for the PHIs in the DestBB, we consider them together. In such | ||||
| 843 | // case, Cost(merging BB) will be the sum of their frequencies. | ||||
| 844 | |||||
| 845 | if (!isa<PHINode>(DestBB->begin())) | ||||
| 846 | return true; | ||||
| 847 | |||||
| 848 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; | ||||
| 849 | |||||
| 850 | // Find all other incoming blocks from which incoming values of all PHIs in | ||||
| 851 | // DestBB are the same as the ones from BB. | ||||
| 852 | for (BasicBlock *DestBBPred : predecessors(DestBB)) { | ||||
| 853 | if (DestBBPred == BB) | ||||
| 854 | continue; | ||||
| 855 | |||||
| 856 | if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) { | ||||
| 857 | return DestPN.getIncomingValueForBlock(BB) == | ||||
| 858 | DestPN.getIncomingValueForBlock(DestBBPred); | ||||
| 859 | })) | ||||
| 860 | SameIncomingValueBBs.insert(DestBBPred); | ||||
| 861 | } | ||||
| 862 | |||||
| 863 | // See if all BB's incoming values are same as the value from Pred. In this | ||||
| 864 | // case, no reason to skip merging because COPYs are expected to be place in | ||||
| 865 | // Pred already. | ||||
| 866 | if (SameIncomingValueBBs.count(Pred)) | ||||
| 867 | return true; | ||||
| 868 | |||||
| 869 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); | ||||
| 870 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); | ||||
| 871 | |||||
| 872 | for (auto *SameValueBB : SameIncomingValueBBs) | ||||
| 873 | if (SameValueBB->getUniquePredecessor() == Pred && | ||||
| 874 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) | ||||
| 875 | BBFreq += BFI->getBlockFreq(SameValueBB); | ||||
| 876 | |||||
| 877 | return PredFreq.getFrequency() <= | ||||
| 878 | BBFreq.getFrequency() * FreqRatioToSkipMerge; | ||||
| 879 | } | ||||
| 880 | |||||
| 881 | /// Return true if we can merge BB into DestBB if there is a single | ||||
| 882 | /// unconditional branch between them, and BB contains no other non-phi | ||||
| 883 | /// instructions. | ||||
| 884 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, | ||||
| 885 | const BasicBlock *DestBB) const { | ||||
| 886 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in | ||||
| 887 | // the successor. If there are more complex condition (e.g. preheaders), | ||||
| 888 | // don't mess around with them. | ||||
| 889 | for (const PHINode &PN : BB->phis()) { | ||||
| 890 | for (const User *U : PN.users()) { | ||||
| 891 | const Instruction *UI = cast<Instruction>(U); | ||||
| 892 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) | ||||
| 893 | return false; | ||||
| 894 | // If User is inside DestBB block and it is a PHINode then check | ||||
| 895 | // incoming value. If incoming value is not from BB then this is | ||||
| 896 | // a complex condition (e.g. preheaders) we want to avoid here. | ||||
| 897 | if (UI->getParent() == DestBB) { | ||||
| 898 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) | ||||
| 899 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { | ||||
| 900 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); | ||||
| 901 | if (Insn && Insn->getParent() == BB && | ||||
| 902 | Insn->getParent() != UPN->getIncomingBlock(I)) | ||||
| 903 | return false; | ||||
| 904 | } | ||||
| 905 | } | ||||
| 906 | } | ||||
| 907 | } | ||||
| 908 | |||||
| 909 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB | ||||
| 910 | // and DestBB may have conflicting incoming values for the block. If so, we | ||||
| 911 | // can't merge the block. | ||||
| 912 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); | ||||
| 913 | if (!DestBBPN) return true; // no conflict. | ||||
| 914 | |||||
| 915 | // Collect the preds of BB. | ||||
| 916 | SmallPtrSet<const BasicBlock*, 16> BBPreds; | ||||
| 917 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { | ||||
| 918 | // It is faster to get preds from a PHI than with pred_iterator. | ||||
| 919 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) | ||||
| 920 | BBPreds.insert(BBPN->getIncomingBlock(i)); | ||||
| 921 | } else { | ||||
| 922 | BBPreds.insert(pred_begin(BB), pred_end(BB)); | ||||
| 923 | } | ||||
| 924 | |||||
| 925 | // Walk the preds of DestBB. | ||||
| 926 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { | ||||
| 927 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); | ||||
| 928 | if (BBPreds.count(Pred)) { // Common predecessor? | ||||
| 929 | for (const PHINode &PN : DestBB->phis()) { | ||||
| 930 | const Value *V1 = PN.getIncomingValueForBlock(Pred); | ||||
| 931 | const Value *V2 = PN.getIncomingValueForBlock(BB); | ||||
| 932 | |||||
| 933 | // If V2 is a phi node in BB, look up what the mapped value will be. | ||||
| 934 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) | ||||
| 935 | if (V2PN->getParent() == BB) | ||||
| 936 | V2 = V2PN->getIncomingValueForBlock(Pred); | ||||
| 937 | |||||
| 938 | // If there is a conflict, bail out. | ||||
| 939 | if (V1 != V2) return false; | ||||
| 940 | } | ||||
| 941 | } | ||||
| 942 | } | ||||
| 943 | |||||
| 944 | return true; | ||||
| 945 | } | ||||
| 946 | |||||
| 947 | /// Eliminate a basic block that has only phi's and an unconditional branch in | ||||
| 948 | /// it. | ||||
| 949 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { | ||||
| 950 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); | ||||
| 951 | BasicBlock *DestBB = BI->getSuccessor(0); | ||||
| 952 | |||||
| 953 | LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"do { } while (false) | ||||
| 954 | << *BB << *DestBB)do { } while (false); | ||||
| 955 | |||||
| 956 | // If the destination block has a single pred, then this is a trivial edge, | ||||
| 957 | // just collapse it. | ||||
| 958 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { | ||||
| 959 | if (SinglePred != DestBB) { | ||||
| 960 | assert(SinglePred == BB &&((void)0) | ||||
| 961 | "Single predecessor not the same as predecessor")((void)0); | ||||
| 962 | // Merge DestBB into SinglePred/BB and delete it. | ||||
| 963 | MergeBlockIntoPredecessor(DestBB); | ||||
| 964 | // Note: BB(=SinglePred) will not be deleted on this path. | ||||
| 965 | // DestBB(=its single successor) is the one that was deleted. | ||||
| 966 | LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n")do { } while (false); | ||||
| 967 | return; | ||||
| 968 | } | ||||
| 969 | } | ||||
| 970 | |||||
| 971 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB | ||||
| 972 | // to handle the new incoming edges it is about to have. | ||||
| 973 | for (PHINode &PN : DestBB->phis()) { | ||||
| 974 | // Remove the incoming value for BB, and remember it. | ||||
| 975 | Value *InVal = PN.removeIncomingValue(BB, false); | ||||
| 976 | |||||
| 977 | // Two options: either the InVal is a phi node defined in BB or it is some | ||||
| 978 | // value that dominates BB. | ||||
| 979 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); | ||||
| 980 | if (InValPhi && InValPhi->getParent() == BB) { | ||||
| 981 | // Add all of the input values of the input PHI as inputs of this phi. | ||||
| 982 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) | ||||
| 983 | PN.addIncoming(InValPhi->getIncomingValue(i), | ||||
| 984 | InValPhi->getIncomingBlock(i)); | ||||
| 985 | } else { | ||||
| 986 | // Otherwise, add one instance of the dominating value for each edge that | ||||
| 987 | // we will be adding. | ||||
| 988 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { | ||||
| 989 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) | ||||
| 990 | PN.addIncoming(InVal, BBPN->getIncomingBlock(i)); | ||||
| 991 | } else { | ||||
| 992 | for (BasicBlock *Pred : predecessors(BB)) | ||||
| 993 | PN.addIncoming(InVal, Pred); | ||||
| 994 | } | ||||
| 995 | } | ||||
| 996 | } | ||||
| 997 | |||||
| 998 | // The PHIs are now updated, change everything that refers to BB to use | ||||
| 999 | // DestBB and remove BB. | ||||
| 1000 | BB->replaceAllUsesWith(DestBB); | ||||
| 1001 | BB->eraseFromParent(); | ||||
| 1002 | ++NumBlocksElim; | ||||
| 1003 | |||||
| 1004 | LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n")do { } while (false); | ||||
| 1005 | } | ||||
| 1006 | |||||
| 1007 | // Computes a map of base pointer relocation instructions to corresponding | ||||
| 1008 | // derived pointer relocation instructions given a vector of all relocate calls | ||||
| 1009 | static void computeBaseDerivedRelocateMap( | ||||
| 1010 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, | ||||
| 1011 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> | ||||
| 1012 | &RelocateInstMap) { | ||||
| 1013 | // Collect information in two maps: one primarily for locating the base object | ||||
| 1014 | // while filling the second map; the second map is the final structure holding | ||||
| 1015 | // a mapping between Base and corresponding Derived relocate calls | ||||
| 1016 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; | ||||
| 1017 | for (auto *ThisRelocate : AllRelocateCalls) { | ||||
| 1018 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), | ||||
| 1019 | ThisRelocate->getDerivedPtrIndex()); | ||||
| 1020 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); | ||||
| 1021 | } | ||||
| 1022 | for (auto &Item : RelocateIdxMap) { | ||||
| 1023 | std::pair<unsigned, unsigned> Key = Item.first; | ||||
| 1024 | if (Key.first == Key.second) | ||||
| 1025 | // Base relocation: nothing to insert | ||||
| 1026 | continue; | ||||
| 1027 | |||||
| 1028 | GCRelocateInst *I = Item.second; | ||||
| 1029 | auto BaseKey = std::make_pair(Key.first, Key.first); | ||||
| 1030 | |||||
| 1031 | // We're iterating over RelocateIdxMap so we cannot modify it. | ||||
| 1032 | auto MaybeBase = RelocateIdxMap.find(BaseKey); | ||||
| 1033 | if (MaybeBase == RelocateIdxMap.end()) | ||||
| 1034 | // TODO: We might want to insert a new base object relocate and gep off | ||||
| 1035 | // that, if there are enough derived object relocates. | ||||
| 1036 | continue; | ||||
| 1037 | |||||
| 1038 | RelocateInstMap[MaybeBase->second].push_back(I); | ||||
| 1039 | } | ||||
| 1040 | } | ||||
| 1041 | |||||
| 1042 | // Accepts a GEP and extracts the operands into a vector provided they're all | ||||
| 1043 | // small integer constants | ||||
| 1044 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, | ||||
| 1045 | SmallVectorImpl<Value *> &OffsetV) { | ||||
| 1046 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { | ||||
| 1047 | // Only accept small constant integer operands | ||||
| 1048 | auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); | ||||
| 1049 | if (!Op || Op->getZExtValue() > 20) | ||||
| 1050 | return false; | ||||
| 1051 | } | ||||
| 1052 | |||||
| 1053 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) | ||||
| 1054 | OffsetV.push_back(GEP->getOperand(i)); | ||||
| 1055 | return true; | ||||
| 1056 | } | ||||
| 1057 | |||||
| 1058 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to | ||||
| 1059 | // replace, computes a replacement, and affects it. | ||||
| 1060 | static bool | ||||
| 1061 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, | ||||
| 1062 | const SmallVectorImpl<GCRelocateInst *> &Targets) { | ||||
| 1063 | bool MadeChange = false; | ||||
| 1064 | // We must ensure the relocation of derived pointer is defined after | ||||
| 1065 | // relocation of base pointer. If we find a relocation corresponding to base | ||||
| 1066 | // defined earlier than relocation of base then we move relocation of base | ||||
| 1067 | // right before found relocation. We consider only relocation in the same | ||||
| 1068 | // basic block as relocation of base. Relocations from other basic block will | ||||
| 1069 | // be skipped by optimization and we do not care about them. | ||||
| 1070 | for (auto R = RelocatedBase->getParent()->getFirstInsertionPt(); | ||||
| 1071 | &*R != RelocatedBase; ++R) | ||||
| 1072 | if (auto *RI = dyn_cast<GCRelocateInst>(R)) | ||||
| 1073 | if (RI->getStatepoint() == RelocatedBase->getStatepoint()) | ||||
| 1074 | if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) { | ||||
| 1075 | RelocatedBase->moveBefore(RI); | ||||
| 1076 | break; | ||||
| 1077 | } | ||||
| 1078 | |||||
| 1079 | for (GCRelocateInst *ToReplace : Targets) { | ||||
| 1080 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&((void)0) | ||||
| 1081 | "Not relocating a derived object of the original base object")((void)0); | ||||
| 1082 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { | ||||
| 1083 | // A duplicate relocate call. TODO: coalesce duplicates. | ||||
| 1084 | continue; | ||||
| 1085 | } | ||||
| 1086 | |||||
| 1087 | if (RelocatedBase->getParent() != ToReplace->getParent()) { | ||||
| 1088 | // Base and derived relocates are in different basic blocks. | ||||
| 1089 | // In this case transform is only valid when base dominates derived | ||||
| 1090 | // relocate. However it would be too expensive to check dominance | ||||
| 1091 | // for each such relocate, so we skip the whole transformation. | ||||
| 1092 | continue; | ||||
| 1093 | } | ||||
| 1094 | |||||
| 1095 | Value *Base = ToReplace->getBasePtr(); | ||||
| 1096 | auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); | ||||
| 1097 | if (!Derived || Derived->getPointerOperand() != Base) | ||||
| 1098 | continue; | ||||
| 1099 | |||||
| 1100 | SmallVector<Value *, 2> OffsetV; | ||||
| 1101 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) | ||||
| 1102 | continue; | ||||
| 1103 | |||||
| 1104 | // Create a Builder and replace the target callsite with a gep | ||||
| 1105 | assert(RelocatedBase->getNextNode() &&((void)0) | ||||
| 1106 | "Should always have one since it's not a terminator")((void)0); | ||||
| 1107 | |||||
| 1108 | // Insert after RelocatedBase | ||||
| 1109 | IRBuilder<> Builder(RelocatedBase->getNextNode()); | ||||
| 1110 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); | ||||
| 1111 | |||||
| 1112 | // If gc_relocate does not match the actual type, cast it to the right type. | ||||
| 1113 | // In theory, there must be a bitcast after gc_relocate if the type does not | ||||
| 1114 | // match, and we should reuse it to get the derived pointer. But it could be | ||||
| 1115 | // cases like this: | ||||
| 1116 | // bb1: | ||||
| 1117 | // ... | ||||
| 1118 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) | ||||
| 1119 | // br label %merge | ||||
| 1120 | // | ||||
| 1121 | // bb2: | ||||
| 1122 | // ... | ||||
| 1123 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) | ||||
| 1124 | // br label %merge | ||||
| 1125 | // | ||||
| 1126 | // merge: | ||||
| 1127 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] | ||||
| 1128 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* | ||||
| 1129 | // | ||||
| 1130 | // In this case, we can not find the bitcast any more. So we insert a new bitcast | ||||
| 1131 | // no matter there is already one or not. In this way, we can handle all cases, and | ||||
| 1132 | // the extra bitcast should be optimized away in later passes. | ||||
| 1133 | Value *ActualRelocatedBase = RelocatedBase; | ||||
| 1134 | if (RelocatedBase->getType() != Base->getType()) { | ||||
| 1135 | ActualRelocatedBase = | ||||
| 1136 | Builder.CreateBitCast(RelocatedBase, Base->getType()); | ||||
| 1137 | } | ||||
| 1138 | Value *Replacement = Builder.CreateGEP( | ||||
| 1139 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); | ||||
| 1140 | Replacement->takeName(ToReplace); | ||||
| 1141 | // If the newly generated derived pointer's type does not match the original derived | ||||
| 1142 | // pointer's type, cast the new derived pointer to match it. Same reasoning as above. | ||||
| 1143 | Value *ActualReplacement = Replacement; | ||||
| 1144 | if (Replacement->getType() != ToReplace->getType()) { | ||||
| 1145 | ActualReplacement = | ||||
| 1146 | Builder.CreateBitCast(Replacement, ToReplace->getType()); | ||||
| 1147 | } | ||||
| 1148 | ToReplace->replaceAllUsesWith(ActualReplacement); | ||||
| 1149 | ToReplace->eraseFromParent(); | ||||
| 1150 | |||||
| 1151 | MadeChange = true; | ||||
| 1152 | } | ||||
| 1153 | return MadeChange; | ||||
| 1154 | } | ||||
| 1155 | |||||
| 1156 | // Turns this: | ||||
| 1157 | // | ||||
| 1158 | // %base = ... | ||||
| 1159 | // %ptr = gep %base + 15 | ||||
| 1160 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) | ||||
| 1161 | // %base' = relocate(%tok, i32 4, i32 4) | ||||
| 1162 | // %ptr' = relocate(%tok, i32 4, i32 5) | ||||
| 1163 | // %val = load %ptr' | ||||
| 1164 | // | ||||
| 1165 | // into this: | ||||
| 1166 | // | ||||
| 1167 | // %base = ... | ||||
| 1168 | // %ptr = gep %base + 15 | ||||
| 1169 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) | ||||
| 1170 | // %base' = gc.relocate(%tok, i32 4, i32 4) | ||||
| 1171 | // %ptr' = gep %base' + 15 | ||||
| 1172 | // %val = load %ptr' | ||||
| 1173 | bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) { | ||||
| 1174 | bool MadeChange = false; | ||||
| 1175 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; | ||||
| 1176 | for (auto *U : I.users()) | ||||
| 1177 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) | ||||
| 1178 | // Collect all the relocate calls associated with a statepoint | ||||
| 1179 | AllRelocateCalls.push_back(Relocate); | ||||
| 1180 | |||||
| 1181 | // We need at least one base pointer relocation + one derived pointer | ||||
| 1182 | // relocation to mangle | ||||
| 1183 | if (AllRelocateCalls.size() < 2) | ||||
| 1184 | return false; | ||||
| 1185 | |||||
| 1186 | // RelocateInstMap is a mapping from the base relocate instruction to the | ||||
| 1187 | // corresponding derived relocate instructions | ||||
| 1188 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; | ||||
| 1189 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); | ||||
| 1190 | if (RelocateInstMap.empty()) | ||||
| 1191 | return false; | ||||
| 1192 | |||||
| 1193 | for (auto &Item : RelocateInstMap) | ||||
| 1194 | // Item.first is the RelocatedBase to offset against | ||||
| 1195 | // Item.second is the vector of Targets to replace | ||||
| 1196 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); | ||||
| 1197 | return MadeChange; | ||||
| 1198 | } | ||||
| 1199 | |||||
| 1200 | /// Sink the specified cast instruction into its user blocks. | ||||
| 1201 | static bool SinkCast(CastInst *CI) { | ||||
| 1202 | BasicBlock *DefBB = CI->getParent(); | ||||
| 1203 | |||||
| 1204 | /// InsertedCasts - Only insert a cast in each block once. | ||||
| 1205 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; | ||||
| 1206 | |||||
| 1207 | bool MadeChange = false; | ||||
| 1208 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); | ||||
| 1209 | UI != E; ) { | ||||
| 1210 | Use &TheUse = UI.getUse(); | ||||
| 1211 | Instruction *User = cast<Instruction>(*UI); | ||||
| 1212 | |||||
| 1213 | // Figure out which BB this cast is used in. For PHI's this is the | ||||
| 1214 | // appropriate predecessor block. | ||||
| 1215 | BasicBlock *UserBB = User->getParent(); | ||||
| 1216 | if (PHINode *PN = dyn_cast<PHINode>(User)) { | ||||
| 1217 | UserBB = PN->getIncomingBlock(TheUse); | ||||
| 1218 | } | ||||
| 1219 | |||||
| 1220 | // Preincrement use iterator so we don't invalidate it. | ||||
| 1221 | ++UI; | ||||
| 1222 | |||||
| 1223 | // The first insertion point of a block containing an EH pad is after the | ||||
| 1224 | // pad. If the pad is the user, we cannot sink the cast past the pad. | ||||
| 1225 | if (User->isEHPad()) | ||||
| 1226 | continue; | ||||
| 1227 | |||||
| 1228 | // If the block selected to receive the cast is an EH pad that does not | ||||
| 1229 | // allow non-PHI instructions before the terminator, we can't sink the | ||||
| 1230 | // cast. | ||||
| 1231 | if (UserBB->getTerminator()->isEHPad()) | ||||
| 1232 | continue; | ||||
| 1233 | |||||
| 1234 | // If this user is in the same block as the cast, don't change the cast. | ||||
| 1235 | if (UserBB == DefBB) continue; | ||||
| 1236 | |||||
| 1237 | // If we have already inserted a cast into this block, use it. | ||||
| 1238 | CastInst *&InsertedCast = InsertedCasts[UserBB]; | ||||
| 1239 | |||||
| 1240 | if (!InsertedCast) { | ||||
| 1241 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
| 1242 | assert(InsertPt != UserBB->end())((void)0); | ||||
| 1243 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), | ||||
| 1244 | CI->getType(), "", &*InsertPt); | ||||
| 1245 | InsertedCast->setDebugLoc(CI->getDebugLoc()); | ||||
| 1246 | } | ||||
| 1247 | |||||
| 1248 | // Replace a use of the cast with a use of the new cast. | ||||
| 1249 | TheUse = InsertedCast; | ||||
| 1250 | MadeChange = true; | ||||
| 1251 | ++NumCastUses; | ||||
| 1252 | } | ||||
| 1253 | |||||
| 1254 | // If we removed all uses, nuke the cast. | ||||
| 1255 | if (CI->use_empty()) { | ||||
| 1256 | salvageDebugInfo(*CI); | ||||
| 1257 | CI->eraseFromParent(); | ||||
| 1258 | MadeChange = true; | ||||
| 1259 | } | ||||
| 1260 | |||||
| 1261 | return MadeChange; | ||||
| 1262 | } | ||||
| 1263 | |||||
| 1264 | /// If the specified cast instruction is a noop copy (e.g. it's casting from | ||||
| 1265 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to | ||||
| 1266 | /// reduce the number of virtual registers that must be created and coalesced. | ||||
| 1267 | /// | ||||
| 1268 | /// Return true if any changes are made. | ||||
| 1269 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, | ||||
| 1270 | const DataLayout &DL) { | ||||
| 1271 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition | ||||
| 1272 | // than sinking only nop casts, but is helpful on some platforms. | ||||
| 1273 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { | ||||
| 1274 | if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(), | ||||
| 1275 | ASC->getDestAddressSpace())) | ||||
| 1276 | return false; | ||||
| 1277 | } | ||||
| 1278 | |||||
| 1279 | // If this is a noop copy, | ||||
| 1280 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); | ||||
| 1281 | EVT DstVT = TLI.getValueType(DL, CI->getType()); | ||||
| 1282 | |||||
| 1283 | // This is an fp<->int conversion? | ||||
| 1284 | if (SrcVT.isInteger() != DstVT.isInteger()) | ||||
| 1285 | return false; | ||||
| 1286 | |||||
| 1287 | // If this is an extension, it will be a zero or sign extension, which | ||||
| 1288 | // isn't a noop. | ||||
| 1289 | if (SrcVT.bitsLT(DstVT)) return false; | ||||
| 1290 | |||||
| 1291 | // If these values will be promoted, find out what they will be promoted | ||||
| 1292 | // to. This helps us consider truncates on PPC as noop copies when they | ||||
| 1293 | // are. | ||||
| 1294 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == | ||||
| 1295 | TargetLowering::TypePromoteInteger) | ||||
| 1296 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); | ||||
| 1297 | if (TLI.getTypeAction(CI->getContext(), DstVT) == | ||||
| 1298 | TargetLowering::TypePromoteInteger) | ||||
| 1299 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); | ||||
| 1300 | |||||
| 1301 | // If, after promotion, these are the same types, this is a noop copy. | ||||
| 1302 | if (SrcVT != DstVT) | ||||
| 1303 | return false; | ||||
| 1304 | |||||
| 1305 | return SinkCast(CI); | ||||
| 1306 | } | ||||
| 1307 | |||||
| 1308 | // Match a simple increment by constant operation. Note that if a sub is | ||||
| 1309 | // matched, the step is negated (as if the step had been canonicalized to | ||||
| 1310 | // an add, even though we leave the instruction alone.) | ||||
| 1311 | bool matchIncrement(const Instruction* IVInc, Instruction *&LHS, | ||||
| 1312 | Constant *&Step) { | ||||
| 1313 | if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) || | ||||
| 1314 | match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>( | ||||
| 1315 | m_Instruction(LHS), m_Constant(Step))))) | ||||
| 1316 | return true; | ||||
| 1317 | if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) || | ||||
| 1318 | match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>( | ||||
| 1319 | m_Instruction(LHS), m_Constant(Step))))) { | ||||
| 1320 | Step = ConstantExpr::getNeg(Step); | ||||
| 1321 | return true; | ||||
| 1322 | } | ||||
| 1323 | return false; | ||||
| 1324 | } | ||||
| 1325 | |||||
| 1326 | /// If given \p PN is an inductive variable with value IVInc coming from the | ||||
| 1327 | /// backedge, and on each iteration it gets increased by Step, return pair | ||||
| 1328 | /// <IVInc, Step>. Otherwise, return None. | ||||
| 1329 | static Optional<std::pair<Instruction *, Constant *> > | ||||
| 1330 | getIVIncrement(const PHINode *PN, const LoopInfo *LI) { | ||||
| 1331 | const Loop *L = LI->getLoopFor(PN->getParent()); | ||||
| 1332 | if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch()) | ||||
| 1333 | return None; | ||||
| 1334 | auto *IVInc = | ||||
| 1335 | dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch())); | ||||
| 1336 | if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L) | ||||
| 1337 | return None; | ||||
| 1338 | Instruction *LHS = nullptr; | ||||
| 1339 | Constant *Step = nullptr; | ||||
| 1340 | if (matchIncrement(IVInc, LHS, Step) && LHS == PN) | ||||
| 1341 | return std::make_pair(IVInc, Step); | ||||
| 1342 | return None; | ||||
| 1343 | } | ||||
| 1344 | |||||
| 1345 | static bool isIVIncrement(const Value *V, const LoopInfo *LI) { | ||||
| 1346 | auto *I = dyn_cast<Instruction>(V); | ||||
| 1347 | if (!I) | ||||
| 1348 | return false; | ||||
| 1349 | Instruction *LHS = nullptr; | ||||
| 1350 | Constant *Step = nullptr; | ||||
| 1351 | if (!matchIncrement(I, LHS, Step)) | ||||
| 1352 | return false; | ||||
| 1353 | if (auto *PN = dyn_cast<PHINode>(LHS)) | ||||
| 1354 | if (auto IVInc = getIVIncrement(PN, LI)) | ||||
| 1355 | return IVInc->first == I; | ||||
| 1356 | return false; | ||||
| 1357 | } | ||||
| 1358 | |||||
| 1359 | bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO, | ||||
| 1360 | Value *Arg0, Value *Arg1, | ||||
| 1361 | CmpInst *Cmp, | ||||
| 1362 | Intrinsic::ID IID) { | ||||
| 1363 | auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) { | ||||
| 1364 | if (!isIVIncrement(BO, LI)) | ||||
| 1365 | return false; | ||||
| 1366 | const Loop *L = LI->getLoopFor(BO->getParent()); | ||||
| 1367 | assert(L && "L should not be null after isIVIncrement()")((void)0); | ||||
| 1368 | // Do not risk on moving increment into a child loop. | ||||
| 1369 | if (LI->getLoopFor(Cmp->getParent()) != L) | ||||
| 1370 | return false; | ||||
| 1371 | |||||
| 1372 | // Finally, we need to ensure that the insert point will dominate all | ||||
| 1373 | // existing uses of the increment. | ||||
| 1374 | |||||
| 1375 | auto &DT = getDT(*BO->getParent()->getParent()); | ||||
| 1376 | if (DT.dominates(Cmp->getParent(), BO->getParent())) | ||||
| 1377 | // If we're moving up the dom tree, all uses are trivially dominated. | ||||
| 1378 | // (This is the common case for code produced by LSR.) | ||||
| 1379 | return true; | ||||
| 1380 | |||||
| 1381 | // Otherwise, special case the single use in the phi recurrence. | ||||
| 1382 | return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch()); | ||||
| 1383 | }; | ||||
| 1384 | if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) { | ||||
| 1385 | // We used to use a dominator tree here to allow multi-block optimization. | ||||
| 1386 | // But that was problematic because: | ||||
| 1387 | // 1. It could cause a perf regression by hoisting the math op into the | ||||
| 1388 | // critical path. | ||||
| 1389 | // 2. It could cause a perf regression by creating a value that was live | ||||
| 1390 | // across multiple blocks and increasing register pressure. | ||||
| 1391 | // 3. Use of a dominator tree could cause large compile-time regression. | ||||
| 1392 | // This is because we recompute the DT on every change in the main CGP | ||||
| 1393 | // run-loop. The recomputing is probably unnecessary in many cases, so if | ||||
| 1394 | // that was fixed, using a DT here would be ok. | ||||
| 1395 | // | ||||
| 1396 | // There is one important particular case we still want to handle: if BO is | ||||
| 1397 | // the IV increment. Important properties that make it profitable: | ||||
| 1398 | // - We can speculate IV increment anywhere in the loop (as long as the | ||||
| 1399 | // indvar Phi is its only user); | ||||
| 1400 | // - Upon computing Cmp, we effectively compute something equivalent to the | ||||
| 1401 | // IV increment (despite it loops differently in the IR). So moving it up | ||||
| 1402 | // to the cmp point does not really increase register pressure. | ||||
| 1403 | return false; | ||||
| 1404 | } | ||||
| 1405 | |||||
| 1406 | // We allow matching the canonical IR (add X, C) back to (usubo X, -C). | ||||
| 1407 | if (BO->getOpcode() == Instruction::Add && | ||||
| 1408 | IID == Intrinsic::usub_with_overflow) { | ||||
| 1409 | assert(isa<Constant>(Arg1) && "Unexpected input for usubo")((void)0); | ||||
| 1410 | Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1)); | ||||
| 1411 | } | ||||
| 1412 | |||||
| 1413 | // Insert at the first instruction of the pair. | ||||
| 1414 | Instruction *InsertPt = nullptr; | ||||
| 1415 | for (Instruction &Iter : *Cmp->getParent()) { | ||||
| 1416 | // If BO is an XOR, it is not guaranteed that it comes after both inputs to | ||||
| 1417 | // the overflow intrinsic are defined. | ||||
| 1418 | if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) { | ||||
| 1419 | InsertPt = &Iter; | ||||
| 1420 | break; | ||||
| 1421 | } | ||||
| 1422 | } | ||||
| 1423 | assert(InsertPt != nullptr && "Parent block did not contain cmp or binop")((void)0); | ||||
| 1424 | |||||
| 1425 | IRBuilder<> Builder(InsertPt); | ||||
| 1426 | Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1); | ||||
| 1427 | if (BO->getOpcode() != Instruction::Xor) { | ||||
| 1428 | Value *Math = Builder.CreateExtractValue(MathOV, 0, "math"); | ||||
| 1429 | BO->replaceAllUsesWith(Math); | ||||
| 1430 | } else | ||||
| 1431 | assert(BO->hasOneUse() &&((void)0) | ||||
| 1432 | "Patterns with XOr should use the BO only in the compare")((void)0); | ||||
| 1433 | Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov"); | ||||
| 1434 | Cmp->replaceAllUsesWith(OV); | ||||
| 1435 | Cmp->eraseFromParent(); | ||||
| 1436 | BO->eraseFromParent(); | ||||
| 1437 | return true; | ||||
| 1438 | } | ||||
| 1439 | |||||
| 1440 | /// Match special-case patterns that check for unsigned add overflow. | ||||
| 1441 | static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, | ||||
| 1442 | BinaryOperator *&Add) { | ||||
| 1443 | // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val) | ||||
| 1444 | // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero) | ||||
| 1445 | Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); | ||||
| 1446 | |||||
| 1447 | // We are not expecting non-canonical/degenerate code. Just bail out. | ||||
| 1448 | if (isa<Constant>(A)) | ||||
| 1449 | return false; | ||||
| 1450 | |||||
| 1451 | ICmpInst::Predicate Pred = Cmp->getPredicate(); | ||||
| 1452 | if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes())) | ||||
| 1453 | B = ConstantInt::get(B->getType(), 1); | ||||
| 1454 | else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) | ||||
| 1455 | B = ConstantInt::get(B->getType(), -1); | ||||
| 1456 | else | ||||
| 1457 | return false; | ||||
| 1458 | |||||
| 1459 | // Check the users of the variable operand of the compare looking for an add | ||||
| 1460 | // with the adjusted constant. | ||||
| 1461 | for (User *U : A->users()) { | ||||
| 1462 | if (match(U, m_Add(m_Specific(A), m_Specific(B)))) { | ||||
| 1463 | Add = cast<BinaryOperator>(U); | ||||
| 1464 | return true; | ||||
| 1465 | } | ||||
| 1466 | } | ||||
| 1467 | return false; | ||||
| 1468 | } | ||||
| 1469 | |||||
| 1470 | /// Try to combine the compare into a call to the llvm.uadd.with.overflow | ||||
| 1471 | /// intrinsic. Return true if any changes were made. | ||||
| 1472 | bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp, | ||||
| 1473 | bool &ModifiedDT) { | ||||
| 1474 | Value *A, *B; | ||||
| 1475 | BinaryOperator *Add; | ||||
| 1476 | if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) { | ||||
| 1477 | if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add)) | ||||
| 1478 | return false; | ||||
| 1479 | // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases. | ||||
| 1480 | A = Add->getOperand(0); | ||||
| 1481 | B = Add->getOperand(1); | ||||
| 1482 | } | ||||
| 1483 | |||||
| 1484 | if (!TLI->shouldFormOverflowOp(ISD::UADDO, | ||||
| 1485 | TLI->getValueType(*DL, Add->getType()), | ||||
| 1486 | Add->hasNUsesOrMore(2))) | ||||
| 1487 | return false; | ||||
| 1488 | |||||
| 1489 | // We don't want to move around uses of condition values this late, so we | ||||
| 1490 | // check if it is legal to create the call to the intrinsic in the basic | ||||
| 1491 | // block containing the icmp. | ||||
| 1492 | if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse()) | ||||
| 1493 | return false; | ||||
| 1494 | |||||
| 1495 | if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp, | ||||
| 1496 | Intrinsic::uadd_with_overflow)) | ||||
| 1497 | return false; | ||||
| 1498 | |||||
| 1499 | // Reset callers - do not crash by iterating over a dead instruction. | ||||
| 1500 | ModifiedDT = true; | ||||
| 1501 | return true; | ||||
| 1502 | } | ||||
| 1503 | |||||
| 1504 | bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp, | ||||
| 1505 | bool &ModifiedDT) { | ||||
| 1506 | // We are not expecting non-canonical/degenerate code. Just bail out. | ||||
| 1507 | Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); | ||||
| 1508 | if (isa<Constant>(A) && isa<Constant>(B)) | ||||
| 1509 | return false; | ||||
| 1510 | |||||
| 1511 | // Convert (A u> B) to (A u< B) to simplify pattern matching. | ||||
| 1512 | ICmpInst::Predicate Pred = Cmp->getPredicate(); | ||||
| 1513 | if (Pred == ICmpInst::ICMP_UGT) { | ||||
| 1514 | std::swap(A, B); | ||||
| 1515 | Pred = ICmpInst::ICMP_ULT; | ||||
| 1516 | } | ||||
| 1517 | // Convert special-case: (A == 0) is the same as (A u< 1). | ||||
| 1518 | if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) { | ||||
| 1519 | B = ConstantInt::get(B->getType(), 1); | ||||
| 1520 | Pred = ICmpInst::ICMP_ULT; | ||||
| 1521 | } | ||||
| 1522 | // Convert special-case: (A != 0) is the same as (0 u< A). | ||||
| 1523 | if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) { | ||||
| 1524 | std::swap(A, B); | ||||
| 1525 | Pred = ICmpInst::ICMP_ULT; | ||||
| 1526 | } | ||||
| 1527 | if (Pred != ICmpInst::ICMP_ULT) | ||||
| 1528 | return false; | ||||
| 1529 | |||||
| 1530 | // Walk the users of a variable operand of a compare looking for a subtract or | ||||
| 1531 | // add with that same operand. Also match the 2nd operand of the compare to | ||||
| 1532 | // the add/sub, but that may be a negated constant operand of an add. | ||||
| 1533 | Value *CmpVariableOperand = isa<Constant>(A) ? B : A; | ||||
| 1534 | BinaryOperator *Sub = nullptr; | ||||
| 1535 | for (User *U : CmpVariableOperand->users()) { | ||||
| 1536 | // A - B, A u< B --> usubo(A, B) | ||||
| 1537 | if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) { | ||||
| 1538 | Sub = cast<BinaryOperator>(U); | ||||
| 1539 | break; | ||||
| 1540 | } | ||||
| 1541 | |||||
| 1542 | // A + (-C), A u< C (canonicalized form of (sub A, C)) | ||||
| 1543 | const APInt *CmpC, *AddC; | ||||
| 1544 | if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) && | ||||
| 1545 | match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) { | ||||
| 1546 | Sub = cast<BinaryOperator>(U); | ||||
| 1547 | break; | ||||
| 1548 | } | ||||
| 1549 | } | ||||
| 1550 | if (!Sub) | ||||
| 1551 | return false; | ||||
| 1552 | |||||
| 1553 | if (!TLI->shouldFormOverflowOp(ISD::USUBO, | ||||
| 1554 | TLI->getValueType(*DL, Sub->getType()), | ||||
| 1555 | Sub->hasNUsesOrMore(2))) | ||||
| 1556 | return false; | ||||
| 1557 | |||||
| 1558 | if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1), | ||||
| 1559 | Cmp, Intrinsic::usub_with_overflow)) | ||||
| 1560 | return false; | ||||
| 1561 | |||||
| 1562 | // Reset callers - do not crash by iterating over a dead instruction. | ||||
| 1563 | ModifiedDT = true; | ||||
| 1564 | return true; | ||||
| 1565 | } | ||||
| 1566 | |||||
| 1567 | /// Sink the given CmpInst into user blocks to reduce the number of virtual | ||||
| 1568 | /// registers that must be created and coalesced. This is a clear win except on | ||||
| 1569 | /// targets with multiple condition code registers (PowerPC), where it might | ||||
| 1570 | /// lose; some adjustment may be wanted there. | ||||
| 1571 | /// | ||||
| 1572 | /// Return true if any changes are made. | ||||
| 1573 | static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) { | ||||
| 1574 | if (TLI.hasMultipleConditionRegisters()) | ||||
| 1575 | return false; | ||||
| 1576 | |||||
| 1577 | // Avoid sinking soft-FP comparisons, since this can move them into a loop. | ||||
| 1578 | if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp)) | ||||
| 1579 | return false; | ||||
| 1580 | |||||
| 1581 | // Only insert a cmp in each block once. | ||||
| 1582 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; | ||||
| 1583 | |||||
| 1584 | bool MadeChange = false; | ||||
| 1585 | for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end(); | ||||
| 1586 | UI != E; ) { | ||||
| 1587 | Use &TheUse = UI.getUse(); | ||||
| 1588 | Instruction *User = cast<Instruction>(*UI); | ||||
| 1589 | |||||
| 1590 | // Preincrement use iterator so we don't invalidate it. | ||||
| 1591 | ++UI; | ||||
| 1592 | |||||
| 1593 | // Don't bother for PHI nodes. | ||||
| 1594 | if (isa<PHINode>(User)) | ||||
| 1595 | continue; | ||||
| 1596 | |||||
| 1597 | // Figure out which BB this cmp is used in. | ||||
| 1598 | BasicBlock *UserBB = User->getParent(); | ||||
| 1599 | BasicBlock *DefBB = Cmp->getParent(); | ||||
| 1600 | |||||
| 1601 | // If this user is in the same block as the cmp, don't change the cmp. | ||||
| 1602 | if (UserBB == DefBB) continue; | ||||
| 1603 | |||||
| 1604 | // If we have already inserted a cmp into this block, use it. | ||||
| 1605 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; | ||||
| 1606 | |||||
| 1607 | if (!InsertedCmp) { | ||||
| 1608 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
| 1609 | assert(InsertPt != UserBB->end())((void)0); | ||||
| 1610 | InsertedCmp = | ||||
| 1611 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), | ||||
| 1612 | Cmp->getOperand(0), Cmp->getOperand(1), "", | ||||
| 1613 | &*InsertPt); | ||||
| 1614 | // Propagate the debug info. | ||||
| 1615 | InsertedCmp->setDebugLoc(Cmp->getDebugLoc()); | ||||
| 1616 | } | ||||
| 1617 | |||||
| 1618 | // Replace a use of the cmp with a use of the new cmp. | ||||
| 1619 | TheUse = InsertedCmp; | ||||
| 1620 | MadeChange = true; | ||||
| 1621 | ++NumCmpUses; | ||||
| 1622 | } | ||||
| 1623 | |||||
| 1624 | // If we removed all uses, nuke the cmp. | ||||
| 1625 | if (Cmp->use_empty()) { | ||||
| 1626 | Cmp->eraseFromParent(); | ||||
| 1627 | MadeChange = true; | ||||
| 1628 | } | ||||
| 1629 | |||||
| 1630 | return MadeChange; | ||||
| 1631 | } | ||||
| 1632 | |||||
| 1633 | /// For pattern like: | ||||
| 1634 | /// | ||||
| 1635 | /// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB) | ||||
| 1636 | /// ... | ||||
| 1637 | /// DomBB: | ||||
| 1638 | /// ... | ||||
| 1639 | /// br DomCond, TrueBB, CmpBB | ||||
| 1640 | /// CmpBB: (with DomBB being the single predecessor) | ||||
| 1641 | /// ... | ||||
| 1642 | /// Cmp = icmp eq CmpOp0, CmpOp1 | ||||
| 1643 | /// ... | ||||
| 1644 | /// | ||||
| 1645 | /// It would use two comparison on targets that lowering of icmp sgt/slt is | ||||
| 1646 | /// different from lowering of icmp eq (PowerPC). This function try to convert | ||||
| 1647 | /// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'. | ||||
| 1648 | /// After that, DomCond and Cmp can use the same comparison so reduce one | ||||
| 1649 | /// comparison. | ||||
| 1650 | /// | ||||
| 1651 | /// Return true if any changes are made. | ||||
| 1652 | static bool foldICmpWithDominatingICmp(CmpInst *Cmp, | ||||
| 1653 | const TargetLowering &TLI) { | ||||
| 1654 | if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp()) | ||||
| 1655 | return false; | ||||
| 1656 | |||||
| 1657 | ICmpInst::Predicate Pred = Cmp->getPredicate(); | ||||
| 1658 | if (Pred != ICmpInst::ICMP_EQ) | ||||
| 1659 | return false; | ||||
| 1660 | |||||
| 1661 | // If icmp eq has users other than BranchInst and SelectInst, converting it to | ||||
| 1662 | // icmp slt/sgt would introduce more redundant LLVM IR. | ||||
| 1663 | for (User *U : Cmp->users()) { | ||||
| 1664 | if (isa<BranchInst>(U)) | ||||
| 1665 | continue; | ||||
| 1666 | if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp) | ||||
| 1667 | continue; | ||||
| 1668 | return false; | ||||
| 1669 | } | ||||
| 1670 | |||||
| 1671 | // This is a cheap/incomplete check for dominance - just match a single | ||||
| 1672 | // predecessor with a conditional branch. | ||||
| 1673 | BasicBlock *CmpBB = Cmp->getParent(); | ||||
| 1674 | BasicBlock *DomBB = CmpBB->getSinglePredecessor(); | ||||
| 1675 | if (!DomBB) | ||||
| 1676 | return false; | ||||
| 1677 | |||||
| 1678 | // We want to ensure that the only way control gets to the comparison of | ||||
| 1679 | // interest is that a less/greater than comparison on the same operands is | ||||
| 1680 | // false. | ||||
| 1681 | Value *DomCond; | ||||
| 1682 | BasicBlock *TrueBB, *FalseBB; | ||||
| 1683 | if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB))) | ||||
| 1684 | return false; | ||||
| 1685 | if (CmpBB != FalseBB) | ||||
| 1686 | return false; | ||||
| 1687 | |||||
| 1688 | Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1); | ||||
| 1689 | ICmpInst::Predicate DomPred; | ||||
| 1690 | if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1)))) | ||||
| 1691 | return false; | ||||
| 1692 | if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT) | ||||
| 1693 | return false; | ||||
| 1694 | |||||
| 1695 | // Convert the equality comparison to the opposite of the dominating | ||||
| 1696 | // comparison and swap the direction for all branch/select users. | ||||
| 1697 | // We have conceptually converted: | ||||
| 1698 | // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>; | ||||
| 1699 | // to | ||||
| 1700 | // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>; | ||||
| 1701 | // And similarly for branches. | ||||
| 1702 | for (User *U : Cmp->users()) { | ||||
| 1703 | if (auto *BI = dyn_cast<BranchInst>(U)) { | ||||
| 1704 | assert(BI->isConditional() && "Must be conditional")((void)0); | ||||
| 1705 | BI->swapSuccessors(); | ||||
| 1706 | continue; | ||||
| 1707 | } | ||||
| 1708 | if (auto *SI = dyn_cast<SelectInst>(U)) { | ||||
| 1709 | // Swap operands | ||||
| 1710 | SI->swapValues(); | ||||
| 1711 | SI->swapProfMetadata(); | ||||
| 1712 | continue; | ||||
| 1713 | } | ||||
| 1714 | llvm_unreachable("Must be a branch or a select")__builtin_unreachable(); | ||||
| 1715 | } | ||||
| 1716 | Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred)); | ||||
| 1717 | return true; | ||||
| 1718 | } | ||||
| 1719 | |||||
| 1720 | bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) { | ||||
| 1721 | if (sinkCmpExpression(Cmp, *TLI)) | ||||
| 1722 | return true; | ||||
| 1723 | |||||
| 1724 | if (combineToUAddWithOverflow(Cmp, ModifiedDT)) | ||||
| 1725 | return true; | ||||
| 1726 | |||||
| 1727 | if (combineToUSubWithOverflow(Cmp, ModifiedDT)) | ||||
| 1728 | return true; | ||||
| 1729 | |||||
| 1730 | if (foldICmpWithDominatingICmp(Cmp, *TLI)) | ||||
| 1731 | return true; | ||||
| 1732 | |||||
| 1733 | return false; | ||||
| 1734 | } | ||||
| 1735 | |||||
| 1736 | /// Duplicate and sink the given 'and' instruction into user blocks where it is | ||||
| 1737 | /// used in a compare to allow isel to generate better code for targets where | ||||
| 1738 | /// this operation can be combined. | ||||
| 1739 | /// | ||||
| 1740 | /// Return true if any changes are made. | ||||
| 1741 | static bool sinkAndCmp0Expression(Instruction *AndI, | ||||
| 1742 | const TargetLowering &TLI, | ||||
| 1743 | SetOfInstrs &InsertedInsts) { | ||||
| 1744 | // Double-check that we're not trying to optimize an instruction that was | ||||
| 1745 | // already optimized by some other part of this pass. | ||||
| 1746 | assert(!InsertedInsts.count(AndI) &&((void)0) | ||||
| 1747 | "Attempting to optimize already optimized and instruction")((void)0); | ||||
| 1748 | (void) InsertedInsts; | ||||
| 1749 | |||||
| 1750 | // Nothing to do for single use in same basic block. | ||||
| 1751 | if (AndI->hasOneUse() && | ||||
| 1752 | AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) | ||||
| 1753 | return false; | ||||
| 1754 | |||||
| 1755 | // Try to avoid cases where sinking/duplicating is likely to increase register | ||||
| 1756 | // pressure. | ||||
| 1757 | if (!isa<ConstantInt>(AndI->getOperand(0)) && | ||||
| 1758 | !isa<ConstantInt>(AndI->getOperand(1)) && | ||||
| 1759 | AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) | ||||
| 1760 | return false; | ||||
| 1761 | |||||
| 1762 | for (auto *U : AndI->users()) { | ||||
| 1763 | Instruction *User = cast<Instruction>(U); | ||||
| 1764 | |||||
| 1765 | // Only sink 'and' feeding icmp with 0. | ||||
| 1766 | if (!isa<ICmpInst>(User)) | ||||
| 1767 | return false; | ||||
| 1768 | |||||
| 1769 | auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); | ||||
| 1770 | if (!CmpC || !CmpC->isZero()) | ||||
| 1771 | return false; | ||||
| 1772 | } | ||||
| 1773 | |||||
| 1774 | if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) | ||||
| 1775 | return false; | ||||
| 1776 | |||||
| 1777 | LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n")do { } while (false); | ||||
| 1778 | LLVM_DEBUG(AndI->getParent()->dump())do { } while (false); | ||||
| 1779 | |||||
| 1780 | // Push the 'and' into the same block as the icmp 0. There should only be | ||||
| 1781 | // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any | ||||
| 1782 | // others, so we don't need to keep track of which BBs we insert into. | ||||
| 1783 | for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); | ||||
| 1784 | UI != E; ) { | ||||
| 1785 | Use &TheUse = UI.getUse(); | ||||
| 1786 | Instruction *User = cast<Instruction>(*UI); | ||||
| 1787 | |||||
| 1788 | // Preincrement use iterator so we don't invalidate it. | ||||
| 1789 | ++UI; | ||||
| 1790 | |||||
| 1791 | LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n")do { } while (false); | ||||
| 1792 | |||||
| 1793 | // Keep the 'and' in the same place if the use is already in the same block. | ||||
| 1794 | Instruction *InsertPt = | ||||
| 1795 | User->getParent() == AndI->getParent() ? AndI : User; | ||||
| 1796 | Instruction *InsertedAnd = | ||||
| 1797 | BinaryOperator::Create(Instruction::And, AndI->getOperand(0), | ||||
| 1798 | AndI->getOperand(1), "", InsertPt); | ||||
| 1799 | // Propagate the debug info. | ||||
| 1800 | InsertedAnd->setDebugLoc(AndI->getDebugLoc()); | ||||
| 1801 | |||||
| 1802 | // Replace a use of the 'and' with a use of the new 'and'. | ||||
| 1803 | TheUse = InsertedAnd; | ||||
| 1804 | ++NumAndUses; | ||||
| 1805 | LLVM_DEBUG(User->getParent()->dump())do { } while (false); | ||||
| 1806 | } | ||||
| 1807 | |||||
| 1808 | // We removed all uses, nuke the and. | ||||
| 1809 | AndI->eraseFromParent(); | ||||
| 1810 | return true; | ||||
| 1811 | } | ||||
| 1812 | |||||
| 1813 | /// Check if the candidates could be combined with a shift instruction, which | ||||
| 1814 | /// includes: | ||||
| 1815 | /// 1. Truncate instruction | ||||
| 1816 | /// 2. And instruction and the imm is a mask of the low bits: | ||||
| 1817 | /// imm & (imm+1) == 0 | ||||
| 1818 | static bool isExtractBitsCandidateUse(Instruction *User) { | ||||
| 1819 | if (!isa<TruncInst>(User)) { | ||||
| 1820 | if (User->getOpcode() != Instruction::And || | ||||
| 1821 | !isa<ConstantInt>(User->getOperand(1))) | ||||
| 1822 | return false; | ||||
| 1823 | |||||
| 1824 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); | ||||
| 1825 | |||||
| 1826 | if ((Cimm & (Cimm + 1)).getBoolValue()) | ||||
| 1827 | return false; | ||||
| 1828 | } | ||||
| 1829 | return true; | ||||
| 1830 | } | ||||
| 1831 | |||||
| 1832 | /// Sink both shift and truncate instruction to the use of truncate's BB. | ||||
| 1833 | static bool | ||||
| 1834 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, | ||||
| 1835 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, | ||||
| 1836 | const TargetLowering &TLI, const DataLayout &DL) { | ||||
| 1837 | BasicBlock *UserBB = User->getParent(); | ||||
| 1838 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; | ||||
| 1839 | auto *TruncI = cast<TruncInst>(User); | ||||
| 1840 | bool MadeChange = false; | ||||
| 1841 | |||||
| 1842 | for (Value::user_iterator TruncUI = TruncI->user_begin(), | ||||
| 1843 | TruncE = TruncI->user_end(); | ||||
| 1844 | TruncUI != TruncE;) { | ||||
| 1845 | |||||
| 1846 | Use &TruncTheUse = TruncUI.getUse(); | ||||
| 1847 | Instruction *TruncUser = cast<Instruction>(*TruncUI); | ||||
| 1848 | // Preincrement use iterator so we don't invalidate it. | ||||
| 1849 | |||||
| 1850 | ++TruncUI; | ||||
| 1851 | |||||
| 1852 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); | ||||
| 1853 | if (!ISDOpcode) | ||||
| 1854 | continue; | ||||
| 1855 | |||||
| 1856 | // If the use is actually a legal node, there will not be an | ||||
| 1857 | // implicit truncate. | ||||
| 1858 | // FIXME: always querying the result type is just an | ||||
| 1859 | // approximation; some nodes' legality is determined by the | ||||
| 1860 | // operand or other means. There's no good way to find out though. | ||||
| 1861 | if (TLI.isOperationLegalOrCustom( | ||||
| 1862 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) | ||||
| 1863 | continue; | ||||
| 1864 | |||||
| 1865 | // Don't bother for PHI nodes. | ||||
| 1866 | if (isa<PHINode>(TruncUser)) | ||||
| 1867 | continue; | ||||
| 1868 | |||||
| 1869 | BasicBlock *TruncUserBB = TruncUser->getParent(); | ||||
| 1870 | |||||
| 1871 | if (UserBB == TruncUserBB) | ||||
| 1872 | continue; | ||||
| 1873 | |||||
| 1874 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; | ||||
| 1875 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; | ||||
| 1876 | |||||
| 1877 | if (!InsertedShift && !InsertedTrunc) { | ||||
| 1878 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); | ||||
| 1879 | assert(InsertPt != TruncUserBB->end())((void)0); | ||||
| 1880 | // Sink the shift | ||||
| 1881 | if (ShiftI->getOpcode() == Instruction::AShr) | ||||
| 1882 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, | ||||
| 1883 | "", &*InsertPt); | ||||
| 1884 | else | ||||
| 1885 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, | ||||
| 1886 | "", &*InsertPt); | ||||
| 1887 | InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); | ||||
| 1888 | |||||
| 1889 | // Sink the trunc | ||||
| 1890 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); | ||||
| 1891 | TruncInsertPt++; | ||||
| 1892 | assert(TruncInsertPt != TruncUserBB->end())((void)0); | ||||
| 1893 | |||||
| 1894 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, | ||||
| 1895 | TruncI->getType(), "", &*TruncInsertPt); | ||||
| 1896 | InsertedTrunc->setDebugLoc(TruncI->getDebugLoc()); | ||||
| 1897 | |||||
| 1898 | MadeChange = true; | ||||
| 1899 | |||||
| 1900 | TruncTheUse = InsertedTrunc; | ||||
| 1901 | } | ||||
| 1902 | } | ||||
| 1903 | return MadeChange; | ||||
| 1904 | } | ||||
| 1905 | |||||
| 1906 | /// Sink the shift *right* instruction into user blocks if the uses could | ||||
| 1907 | /// potentially be combined with this shift instruction and generate BitExtract | ||||
| 1908 | /// instruction. It will only be applied if the architecture supports BitExtract | ||||
| 1909 | /// instruction. Here is an example: | ||||
| 1910 | /// BB1: | ||||
| 1911 | /// %x.extract.shift = lshr i64 %arg1, 32 | ||||
| 1912 | /// BB2: | ||||
| 1913 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 | ||||
| 1914 | /// ==> | ||||
| 1915 | /// | ||||
| 1916 | /// BB2: | ||||
| 1917 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 | ||||
| 1918 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 | ||||
| 1919 | /// | ||||
| 1920 | /// CodeGen will recognize the pattern in BB2 and generate BitExtract | ||||
| 1921 | /// instruction. | ||||
| 1922 | /// Return true if any changes are made. | ||||
| 1923 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, | ||||
| 1924 | const TargetLowering &TLI, | ||||
| 1925 | const DataLayout &DL) { | ||||
| 1926 | BasicBlock *DefBB = ShiftI->getParent(); | ||||
| 1927 | |||||
| 1928 | /// Only insert instructions in each block once. | ||||
| 1929 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; | ||||
| 1930 | |||||
| 1931 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); | ||||
| 1932 | |||||
| 1933 | bool MadeChange = false; | ||||
| 1934 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); | ||||
| 1935 | UI != E;) { | ||||
| 1936 | Use &TheUse = UI.getUse(); | ||||
| 1937 | Instruction *User = cast<Instruction>(*UI); | ||||
| 1938 | // Preincrement use iterator so we don't invalidate it. | ||||
| 1939 | ++UI; | ||||
| 1940 | |||||
| 1941 | // Don't bother for PHI nodes. | ||||
| 1942 | if (isa<PHINode>(User)) | ||||
| 1943 | continue; | ||||
| 1944 | |||||
| 1945 | if (!isExtractBitsCandidateUse(User)) | ||||
| 1946 | continue; | ||||
| 1947 | |||||
| 1948 | BasicBlock *UserBB = User->getParent(); | ||||
| 1949 | |||||
| 1950 | if (UserBB == DefBB) { | ||||
| 1951 | // If the shift and truncate instruction are in the same BB. The use of | ||||
| 1952 | // the truncate(TruncUse) may still introduce another truncate if not | ||||
| 1953 | // legal. In this case, we would like to sink both shift and truncate | ||||
| 1954 | // instruction to the BB of TruncUse. | ||||
| 1955 | // for example: | ||||
| 1956 | // BB1: | ||||
| 1957 | // i64 shift.result = lshr i64 opnd, imm | ||||
| 1958 | // trunc.result = trunc shift.result to i16 | ||||
| 1959 | // | ||||
| 1960 | // BB2: | ||||
| 1961 | // ----> We will have an implicit truncate here if the architecture does | ||||
| 1962 | // not have i16 compare. | ||||
| 1963 | // cmp i16 trunc.result, opnd2 | ||||
| 1964 | // | ||||
| 1965 | if (isa<TruncInst>(User) && shiftIsLegal | ||||
| 1966 | // If the type of the truncate is legal, no truncate will be | ||||
| 1967 | // introduced in other basic blocks. | ||||
| 1968 | && | ||||
| 1969 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) | ||||
| 1970 | MadeChange = | ||||
| 1971 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); | ||||
| 1972 | |||||
| 1973 | continue; | ||||
| 1974 | } | ||||
| 1975 | // If we have already inserted a shift into this block, use it. | ||||
| 1976 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; | ||||
| 1977 | |||||
| 1978 | if (!InsertedShift) { | ||||
| 1979 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
| 1980 | assert(InsertPt != UserBB->end())((void)0); | ||||
| 1981 | |||||
| 1982 | if (ShiftI->getOpcode() == Instruction::AShr) | ||||
| 1983 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, | ||||
| 1984 | "", &*InsertPt); | ||||
| 1985 | else | ||||
| 1986 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, | ||||
| 1987 | "", &*InsertPt); | ||||
| 1988 | InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); | ||||
| 1989 | |||||
| 1990 | MadeChange = true; | ||||
| 1991 | } | ||||
| 1992 | |||||
| 1993 | // Replace a use of the shift with a use of the new shift. | ||||
| 1994 | TheUse = InsertedShift; | ||||
| 1995 | } | ||||
| 1996 | |||||
| 1997 | // If we removed all uses, or there are none, nuke the shift. | ||||
| 1998 | if (ShiftI->use_empty()) { | ||||
| 1999 | salvageDebugInfo(*ShiftI); | ||||
| 2000 | ShiftI->eraseFromParent(); | ||||
| 2001 | MadeChange = true; | ||||
| 2002 | } | ||||
| 2003 | |||||
| 2004 | return MadeChange; | ||||
| 2005 | } | ||||
| 2006 | |||||
| 2007 | /// If counting leading or trailing zeros is an expensive operation and a zero | ||||
| 2008 | /// input is defined, add a check for zero to avoid calling the intrinsic. | ||||
| 2009 | /// | ||||
| 2010 | /// We want to transform: | ||||
| 2011 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) | ||||
| 2012 | /// | ||||
| 2013 | /// into: | ||||
| 2014 | /// entry: | ||||
| 2015 | /// %cmpz = icmp eq i64 %A, 0 | ||||
| 2016 | /// br i1 %cmpz, label %cond.end, label %cond.false | ||||
| 2017 | /// cond.false: | ||||
| 2018 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) | ||||
| 2019 | /// br label %cond.end | ||||
| 2020 | /// cond.end: | ||||
| 2021 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] | ||||
| 2022 | /// | ||||
| 2023 | /// If the transform is performed, return true and set ModifiedDT to true. | ||||
| 2024 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, | ||||
| 2025 | const TargetLowering *TLI, | ||||
| 2026 | const DataLayout *DL, | ||||
| 2027 | bool &ModifiedDT) { | ||||
| 2028 | // If a zero input is undefined, it doesn't make sense to despeculate that. | ||||
| 2029 | if (match(CountZeros->getOperand(1), m_One())) | ||||
| 2030 | return false; | ||||
| 2031 | |||||
| 2032 | // If it's cheap to speculate, there's nothing to do. | ||||
| 2033 | auto IntrinsicID = CountZeros->getIntrinsicID(); | ||||
| 2034 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || | ||||
| 2035 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) | ||||
| 2036 | return false; | ||||
| 2037 | |||||
| 2038 | // Only handle legal scalar cases. Anything else requires too much work. | ||||
| 2039 | Type *Ty = CountZeros->getType(); | ||||
| 2040 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); | ||||
| 2041 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) | ||||
| 2042 | return false; | ||||
| 2043 | |||||
| 2044 | // Bail if the value is never zero. | ||||
| 2045 | if (llvm::isKnownNonZero(CountZeros->getOperand(0), *DL)) | ||||
| 2046 | return false; | ||||
| 2047 | |||||
| 2048 | // The intrinsic will be sunk behind a compare against zero and branch. | ||||
| 2049 | BasicBlock *StartBlock = CountZeros->getParent(); | ||||
| 2050 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); | ||||
| 2051 | |||||
| 2052 | // Create another block after the count zero intrinsic. A PHI will be added | ||||
| 2053 | // in this block to select the result of the intrinsic or the bit-width | ||||
| 2054 | // constant if the input to the intrinsic is zero. | ||||
| 2055 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); | ||||
| 2056 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); | ||||
| 2057 | |||||
| 2058 | // Set up a builder to create a compare, conditional branch, and PHI. | ||||
| 2059 | IRBuilder<> Builder(CountZeros->getContext()); | ||||
| 2060 | Builder.SetInsertPoint(StartBlock->getTerminator()); | ||||
| 2061 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); | ||||
| 2062 | |||||
| 2063 | // Replace the unconditional branch that was created by the first split with | ||||
| 2064 | // a compare against zero and a conditional branch. | ||||
| 2065 | Value *Zero = Constant::getNullValue(Ty); | ||||
| 2066 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); | ||||
| 2067 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); | ||||
| 2068 | StartBlock->getTerminator()->eraseFromParent(); | ||||
| 2069 | |||||
| 2070 | // Create a PHI in the end block to select either the output of the intrinsic | ||||
| 2071 | // or the bit width of the operand. | ||||
| 2072 | Builder.SetInsertPoint(&EndBlock->front()); | ||||
| 2073 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); | ||||
| 2074 | CountZeros->replaceAllUsesWith(PN); | ||||
| 2075 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); | ||||
| 2076 | PN->addIncoming(BitWidth, StartBlock); | ||||
| 2077 | PN->addIncoming(CountZeros, CallBlock); | ||||
| 2078 | |||||
| 2079 | // We are explicitly handling the zero case, so we can set the intrinsic's | ||||
| 2080 | // undefined zero argument to 'true'. This will also prevent reprocessing the | ||||
| 2081 | // intrinsic; we only despeculate when a zero input is defined. | ||||
| 2082 | CountZeros->setArgOperand(1, Builder.getTrue()); | ||||
| 2083 | ModifiedDT = true; | ||||
| 2084 | return true; | ||||
| 2085 | } | ||||
| 2086 | |||||
| 2087 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) { | ||||
| 2088 | BasicBlock *BB = CI->getParent(); | ||||
| 2089 | |||||
| 2090 | // Lower inline assembly if we can. | ||||
| 2091 | // If we found an inline asm expession, and if the target knows how to | ||||
| 2092 | // lower it to normal LLVM code, do so now. | ||||
| 2093 | if (CI->isInlineAsm()) { | ||||
| 2094 | if (TLI->ExpandInlineAsm(CI)) { | ||||
| 2095 | // Avoid invalidating the iterator. | ||||
| 2096 | CurInstIterator = BB->begin(); | ||||
| 2097 | // Avoid processing instructions out of order, which could cause | ||||
| 2098 | // reuse before a value is defined. | ||||
| 2099 | SunkAddrs.clear(); | ||||
| 2100 | return true; | ||||
| 2101 | } | ||||
| 2102 | // Sink address computing for memory operands into the block. | ||||
| 2103 | if (optimizeInlineAsmInst(CI)) | ||||
| 2104 | return true; | ||||
| 2105 | } | ||||
| 2106 | |||||
| 2107 | // Align the pointer arguments to this call if the target thinks it's a good | ||||
| 2108 | // idea | ||||
| 2109 | unsigned MinSize, PrefAlign; | ||||
| 2110 | if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { | ||||
| 2111 | for (auto &Arg : CI->arg_operands()) { | ||||
| 2112 | // We want to align both objects whose address is used directly and | ||||
| 2113 | // objects whose address is used in casts and GEPs, though it only makes | ||||
| 2114 | // sense for GEPs if the offset is a multiple of the desired alignment and | ||||
| 2115 | // if size - offset meets the size threshold. | ||||
| 2116 | if (!Arg->getType()->isPointerTy()) | ||||
| 2117 | continue; | ||||
| 2118 | APInt Offset(DL->getIndexSizeInBits( | ||||
| 2119 | cast<PointerType>(Arg->getType())->getAddressSpace()), | ||||
| 2120 | 0); | ||||
| 2121 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); | ||||
| 2122 | uint64_t Offset2 = Offset.getLimitedValue(); | ||||
| 2123 | if ((Offset2 & (PrefAlign-1)) != 0) | ||||
| 2124 | continue; | ||||
| 2125 | AllocaInst *AI; | ||||
| 2126 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && | ||||
| 2127 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) | ||||
| 2128 | AI->setAlignment(Align(PrefAlign)); | ||||
| 2129 | // Global variables can only be aligned if they are defined in this | ||||
| 2130 | // object (i.e. they are uniquely initialized in this object), and | ||||
| 2131 | // over-aligning global variables that have an explicit section is | ||||
| 2132 | // forbidden. | ||||
| 2133 | GlobalVariable *GV; | ||||
| 2134 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && | ||||
| 2135 | GV->getPointerAlignment(*DL) < PrefAlign && | ||||
| 2136 | DL->getTypeAllocSize(GV->getValueType()) >= | ||||
| 2137 | MinSize + Offset2) | ||||
| 2138 | GV->setAlignment(MaybeAlign(PrefAlign)); | ||||
| 2139 | } | ||||
| 2140 | // If this is a memcpy (or similar) then we may be able to improve the | ||||
| 2141 | // alignment | ||||
| 2142 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { | ||||
| 2143 | Align DestAlign = getKnownAlignment(MI->getDest(), *DL); | ||||
| 2144 | MaybeAlign MIDestAlign = MI->getDestAlign(); | ||||
| 2145 | if (!MIDestAlign || DestAlign > *MIDestAlign) | ||||
| 2146 | MI->setDestAlignment(DestAlign); | ||||
| 2147 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { | ||||
| 2148 | MaybeAlign MTISrcAlign = MTI->getSourceAlign(); | ||||
| 2149 | Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL); | ||||
| 2150 | if (!MTISrcAlign || SrcAlign > *MTISrcAlign) | ||||
| 2151 | MTI->setSourceAlignment(SrcAlign); | ||||
| 2152 | } | ||||
| 2153 | } | ||||
| 2154 | } | ||||
| 2155 | |||||
| 2156 | // If we have a cold call site, try to sink addressing computation into the | ||||
| 2157 | // cold block. This interacts with our handling for loads and stores to | ||||
| 2158 | // ensure that we can fold all uses of a potential addressing computation | ||||
| 2159 | // into their uses. TODO: generalize this to work over profiling data | ||||
| 2160 | if (CI->hasFnAttr(Attribute::Cold) && | ||||
| 2161 | !OptSize && !llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) | ||||
| 2162 | for (auto &Arg : CI->arg_operands()) { | ||||
| 2163 | if (!Arg->getType()->isPointerTy()) | ||||
| 2164 | continue; | ||||
| 2165 | unsigned AS = Arg->getType()->getPointerAddressSpace(); | ||||
| 2166 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); | ||||
| 2167 | } | ||||
| 2168 | |||||
| 2169 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); | ||||
| 2170 | if (II) { | ||||
| 2171 | switch (II->getIntrinsicID()) { | ||||
| 2172 | default: break; | ||||
| 2173 | case Intrinsic::assume: | ||||
| 2174 | llvm_unreachable("llvm.assume should have been removed already")__builtin_unreachable(); | ||||
| 2175 | case Intrinsic::experimental_widenable_condition: { | ||||
| 2176 | // Give up on future widening oppurtunties so that we can fold away dead | ||||
| 2177 | // paths and merge blocks before going into block-local instruction | ||||
| 2178 | // selection. | ||||
| 2179 | if (II->use_empty()) { | ||||
| 2180 | II->eraseFromParent(); | ||||
| 2181 | return true; | ||||
| 2182 | } | ||||
| 2183 | Constant *RetVal = ConstantInt::getTrue(II->getContext()); | ||||
| 2184 | resetIteratorIfInvalidatedWhileCalling(BB, [&]() { | ||||
| 2185 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); | ||||
| 2186 | }); | ||||
| 2187 | return true; | ||||
| 2188 | } | ||||
| 2189 | case Intrinsic::objectsize: | ||||
| 2190 | llvm_unreachable("llvm.objectsize.* should have been lowered already")__builtin_unreachable(); | ||||
| 2191 | case Intrinsic::is_constant: | ||||
| 2192 | llvm_unreachable("llvm.is.constant.* should have been lowered already")__builtin_unreachable(); | ||||
| 2193 | case Intrinsic::aarch64_stlxr: | ||||
| 2194 | case Intrinsic::aarch64_stxr: { | ||||
| 2195 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); | ||||
| 2196 | if (!ExtVal || !ExtVal->hasOneUse() || | ||||
| 2197 | ExtVal->getParent() == CI->getParent()) | ||||
| 2198 | return false; | ||||
| 2199 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. | ||||
| 2200 | ExtVal->moveBefore(CI); | ||||
| 2201 | // Mark this instruction as "inserted by CGP", so that other | ||||
| 2202 | // optimizations don't touch it. | ||||
| 2203 | InsertedInsts.insert(ExtVal); | ||||
| 2204 | return true; | ||||
| 2205 | } | ||||
| 2206 | |||||
| 2207 | case Intrinsic::launder_invariant_group: | ||||
| 2208 | case Intrinsic::strip_invariant_group: { | ||||
| 2209 | Value *ArgVal = II->getArgOperand(0); | ||||
| 2210 | auto it = LargeOffsetGEPMap.find(II); | ||||
| 2211 | if (it != LargeOffsetGEPMap.end()) { | ||||
| 2212 | // Merge entries in LargeOffsetGEPMap to reflect the RAUW. | ||||
| 2213 | // Make sure not to have to deal with iterator invalidation | ||||
| 2214 | // after possibly adding ArgVal to LargeOffsetGEPMap. | ||||
| 2215 | auto GEPs = std::move(it->second); | ||||
| 2216 | LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end()); | ||||
| 2217 | LargeOffsetGEPMap.erase(II); | ||||
| 2218 | } | ||||
| 2219 | |||||
| 2220 | II->replaceAllUsesWith(ArgVal); | ||||
| 2221 | II->eraseFromParent(); | ||||
| 2222 | return true; | ||||
| 2223 | } | ||||
| 2224 | case Intrinsic::cttz: | ||||
| 2225 | case Intrinsic::ctlz: | ||||
| 2226 | // If counting zeros is expensive, try to avoid it. | ||||
| 2227 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); | ||||
| 2228 | case Intrinsic::fshl: | ||||
| 2229 | case Intrinsic::fshr: | ||||
| 2230 | return optimizeFunnelShift(II); | ||||
| 2231 | case Intrinsic::dbg_value: | ||||
| 2232 | return fixupDbgValue(II); | ||||
| 2233 | case Intrinsic::vscale: { | ||||
| 2234 | // If datalayout has no special restrictions on vector data layout, | ||||
| 2235 | // replace `llvm.vscale` by an equivalent constant expression | ||||
| 2236 | // to benefit from cheap constant propagation. | ||||
| 2237 | Type *ScalableVectorTy = | ||||
| 2238 | VectorType::get(Type::getInt8Ty(II->getContext()), 1, true); | ||||
| 2239 | if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinSize() == 8) { | ||||
| 2240 | auto *Null = Constant::getNullValue(ScalableVectorTy->getPointerTo()); | ||||
| 2241 | auto *One = ConstantInt::getSigned(II->getType(), 1); | ||||
| 2242 | auto *CGep = | ||||
| 2243 | ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One); | ||||
| 2244 | II->replaceAllUsesWith(ConstantExpr::getPtrToInt(CGep, II->getType())); | ||||
| 2245 | II->eraseFromParent(); | ||||
| 2246 | return true; | ||||
| 2247 | } | ||||
| 2248 | break; | ||||
| 2249 | } | ||||
| 2250 | case Intrinsic::masked_gather: | ||||
| 2251 | return optimizeGatherScatterInst(II, II->getArgOperand(0)); | ||||
| 2252 | case Intrinsic::masked_scatter: | ||||
| 2253 | return optimizeGatherScatterInst(II, II->getArgOperand(1)); | ||||
| 2254 | } | ||||
| 2255 | |||||
| 2256 | SmallVector<Value *, 2> PtrOps; | ||||
| 2257 | Type *AccessTy; | ||||
| 2258 | if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) | ||||
| 2259 | while (!PtrOps.empty()) { | ||||
| 2260 | Value *PtrVal = PtrOps.pop_back_val(); | ||||
| 2261 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); | ||||
| 2262 | if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) | ||||
| 2263 | return true; | ||||
| 2264 | } | ||||
| 2265 | } | ||||
| 2266 | |||||
| 2267 | // From here on out we're working with named functions. | ||||
| 2268 | if (!CI->getCalledFunction()) return false; | ||||
| 2269 | |||||
| 2270 | // Lower all default uses of _chk calls. This is very similar | ||||
| 2271 | // to what InstCombineCalls does, but here we are only lowering calls | ||||
| 2272 | // to fortified library functions (e.g. __memcpy_chk) that have the default | ||||
| 2273 | // "don't know" as the objectsize. Anything else should be left alone. | ||||
| 2274 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); | ||||
| 2275 | IRBuilder<> Builder(CI); | ||||
| 2276 | if (Value *V = Simplifier.optimizeCall(CI, Builder)) { | ||||
| 2277 | CI->replaceAllUsesWith(V); | ||||
| 2278 | CI->eraseFromParent(); | ||||
| 2279 | return true; | ||||
| 2280 | } | ||||
| 2281 | |||||
| 2282 | return false; | ||||
| 2283 | } | ||||
| 2284 | |||||
| 2285 | /// Look for opportunities to duplicate return instructions to the predecessor | ||||
| 2286 | /// to enable tail call optimizations. The case it is currently looking for is: | ||||
| 2287 | /// @code | ||||
| 2288 | /// bb0: | ||||
| 2289 | /// %tmp0 = tail call i32 @f0() | ||||
| 2290 | /// br label %return | ||||
| 2291 | /// bb1: | ||||
| 2292 | /// %tmp1 = tail call i32 @f1() | ||||
| 2293 | /// br label %return | ||||
| 2294 | /// bb2: | ||||
| 2295 | /// %tmp2 = tail call i32 @f2() | ||||
| 2296 | /// br label %return | ||||
| 2297 | /// return: | ||||
| 2298 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] | ||||
| 2299 | /// ret i32 %retval | ||||
| 2300 | /// @endcode | ||||
| 2301 | /// | ||||
| 2302 | /// => | ||||
| 2303 | /// | ||||
| 2304 | /// @code | ||||
| 2305 | /// bb0: | ||||
| 2306 | /// %tmp0 = tail call i32 @f0() | ||||
| 2307 | /// ret i32 %tmp0 | ||||
| 2308 | /// bb1: | ||||
| 2309 | /// %tmp1 = tail call i32 @f1() | ||||
| 2310 | /// ret i32 %tmp1 | ||||
| 2311 | /// bb2: | ||||
| 2312 | /// %tmp2 = tail call i32 @f2() | ||||
| 2313 | /// ret i32 %tmp2 | ||||
| 2314 | /// @endcode | ||||
| 2315 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) { | ||||
| 2316 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); | ||||
| |||||
| 2317 | if (!RetI
| ||||
| 2318 | return false; | ||||
| 2319 | |||||
| 2320 | PHINode *PN = nullptr; | ||||
| 2321 | ExtractValueInst *EVI = nullptr; | ||||
| 2322 | BitCastInst *BCI = nullptr; | ||||
| 2323 | Value *V = RetI->getReturnValue(); | ||||
| 2324 | if (V
| ||||
| 2325 | BCI = dyn_cast<BitCastInst>(V); | ||||
| 2326 | if (BCI) | ||||
| 2327 | V = BCI->getOperand(0); | ||||
| 2328 | |||||
| 2329 | EVI = dyn_cast<ExtractValueInst>(V); | ||||
| 2330 | if (EVI) { | ||||
| 2331 | V = EVI->getOperand(0); | ||||
| 2332 | if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; })) | ||||
| 2333 | return false; | ||||
| 2334 | } | ||||
| 2335 | |||||
| 2336 | PN = dyn_cast<PHINode>(V); | ||||
| 2337 | if (!PN) | ||||
| 2338 | return false; | ||||
| 2339 | } | ||||
| 2340 | |||||
| 2341 | if (PN
| ||||
| 2342 | return false; | ||||
| 2343 | |||||
| 2344 | auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) { | ||||
| 2345 | const BitCastInst *BC = dyn_cast<BitCastInst>(Inst); | ||||
| 2346 | if (BC && BC->hasOneUse()) | ||||
| 2347 | Inst = BC->user_back(); | ||||
| 2348 | |||||
| 2349 | if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) | ||||
| 2350 | return II->getIntrinsicID() == Intrinsic::lifetime_end; | ||||
| 2351 | return false; | ||||
| 2352 | }; | ||||
| 2353 | |||||
| 2354 | // Make sure there are no instructions between the first instruction | ||||
| 2355 | // and return. | ||||
| 2356 | const Instruction *BI = BB->getFirstNonPHI(); | ||||
| 2357 | // Skip over debug and the bitcast. | ||||
| 2358 | while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI || | ||||
| 2359 | isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI)) | ||||
| 2360 | BI = BI->getNextNode(); | ||||
| |||||
| 2361 | if (BI != RetI) | ||||
| 2362 | return false; | ||||
| 2363 | |||||
| 2364 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail | ||||
| 2365 | /// call. | ||||
| 2366 | const Function *F = BB->getParent(); | ||||
| 2367 | SmallVector<BasicBlock*, 4> TailCallBBs; | ||||
| 2368 | if (PN) { | ||||
| 2369 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { | ||||
| 2370 | // Look through bitcasts. | ||||
| 2371 | Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts(); | ||||
| 2372 | CallInst *CI = dyn_cast<CallInst>(IncomingVal); | ||||
| 2373 | BasicBlock *PredBB = PN->getIncomingBlock(I); | ||||
| 2374 | // Make sure the phi value is indeed produced by the tail call. | ||||
| 2375 | if (CI && CI->hasOneUse() && CI->getParent() == PredBB && | ||||
| 2376 | TLI->mayBeEmittedAsTailCall(CI) && | ||||
| 2377 | attributesPermitTailCall(F, CI, RetI, *TLI)) | ||||
| 2378 | TailCallBBs.push_back(PredBB); | ||||
| 2379 | } | ||||
| 2380 | } else { | ||||
| 2381 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; | ||||
| 2382 | for (BasicBlock *Pred : predecessors(BB)) { | ||||
| 2383 | if (!VisitedBBs.insert(Pred).second) | ||||
| 2384 | continue; | ||||
| 2385 | if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) { | ||||
| 2386 | CallInst *CI = dyn_cast<CallInst>(I); | ||||
| 2387 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && | ||||
| 2388 | attributesPermitTailCall(F, CI, RetI, *TLI)) | ||||
| 2389 | TailCallBBs.push_back(Pred); | ||||
| 2390 | } | ||||
| 2391 | } | ||||
| 2392 | } | ||||
| 2393 | |||||
| 2394 | bool Changed = false; | ||||
| 2395 | for (auto const &TailCallBB : TailCallBBs) { | ||||
| 2396 | // Make sure the call instruction is followed by an unconditional branch to | ||||
| 2397 | // the return block. | ||||
| 2398 | BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator()); | ||||
| 2399 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) | ||||
| 2400 | continue; | ||||
| 2401 | |||||
| 2402 | // Duplicate the return into TailCallBB. | ||||
| 2403 | (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB); | ||||
| 2404 | assert(!VerifyBFIUpdates ||((void)0) | ||||
| 2405 | BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB))((void)0); | ||||
| 2406 | BFI->setBlockFreq( | ||||
| 2407 | BB, | ||||
| 2408 | (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency()); | ||||
| 2409 | ModifiedDT = Changed = true; | ||||
| 2410 | ++NumRetsDup; | ||||
| 2411 | } | ||||
| 2412 | |||||
| 2413 | // If we eliminated all predecessors of the block, delete the block now. | ||||
| 2414 | if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) | ||||
| 2415 | BB->eraseFromParent(); | ||||
| 2416 | |||||
| 2417 | return Changed; | ||||
| 2418 | } | ||||
| 2419 | |||||
| 2420 | //===----------------------------------------------------------------------===// | ||||
| 2421 | // Memory Optimization | ||||
| 2422 | //===----------------------------------------------------------------------===// | ||||
| 2423 | |||||
| 2424 | namespace { | ||||
| 2425 | |||||
| 2426 | /// This is an extended version of TargetLowering::AddrMode | ||||
| 2427 | /// which holds actual Value*'s for register values. | ||||
| 2428 | struct ExtAddrMode : public TargetLowering::AddrMode { | ||||
| 2429 | Value *BaseReg = nullptr; | ||||
| 2430 | Value *ScaledReg = nullptr; | ||||
| 2431 | Value *OriginalValue = nullptr; | ||||
| 2432 | bool InBounds = true; | ||||
| 2433 | |||||
| 2434 | enum FieldName { | ||||
| 2435 | NoField = 0x00, | ||||
| 2436 | BaseRegField = 0x01, | ||||
| 2437 | BaseGVField = 0x02, | ||||
| 2438 | BaseOffsField = 0x04, | ||||
| 2439 | ScaledRegField = 0x08, | ||||
| 2440 | ScaleField = 0x10, | ||||
| 2441 | MultipleFields = 0xff | ||||
| 2442 | }; | ||||
| 2443 | |||||
| 2444 | |||||
| 2445 | ExtAddrMode() = default; | ||||
| 2446 | |||||
| 2447 | void print(raw_ostream &OS) const; | ||||
| 2448 | void dump() const; | ||||
| 2449 | |||||
| 2450 | FieldName compare(const ExtAddrMode &other) { | ||||
| 2451 | // First check that the types are the same on each field, as differing types | ||||
| 2452 | // is something we can't cope with later on. | ||||
| 2453 | if (BaseReg && other.BaseReg && | ||||
| 2454 | BaseReg->getType() != other.BaseReg->getType()) | ||||
| 2455 | return MultipleFields; | ||||
| 2456 | if (BaseGV && other.BaseGV && | ||||
| 2457 | BaseGV->getType() != other.BaseGV->getType()) | ||||
| 2458 | return MultipleFields; | ||||
| 2459 | if (ScaledReg && other.ScaledReg && | ||||
| 2460 | ScaledReg->getType() != other.ScaledReg->getType()) | ||||
| 2461 | return MultipleFields; | ||||
| 2462 | |||||
| 2463 | // Conservatively reject 'inbounds' mismatches. | ||||
| 2464 | if (InBounds != other.InBounds) | ||||
| 2465 | return MultipleFields; | ||||
| 2466 | |||||
| 2467 | // Check each field to see if it differs. | ||||
| 2468 | unsigned Result = NoField; | ||||
| 2469 | if (BaseReg != other.BaseReg) | ||||
| 2470 | Result |= BaseRegField; | ||||
| 2471 | if (BaseGV != other.BaseGV) | ||||
| 2472 | Result |= BaseGVField; | ||||
| 2473 | if (BaseOffs != other.BaseOffs) | ||||
| 2474 | Result |= BaseOffsField; | ||||
| 2475 | if (ScaledReg != other.ScaledReg) | ||||
| 2476 | Result |= ScaledRegField; | ||||
| 2477 | // Don't count 0 as being a different scale, because that actually means | ||||
| 2478 | // unscaled (which will already be counted by having no ScaledReg). | ||||
| 2479 | if (Scale && other.Scale && Scale != other.Scale) | ||||
| 2480 | Result |= ScaleField; | ||||
| 2481 | |||||
| 2482 | if (countPopulation(Result) > 1) | ||||
| 2483 | return MultipleFields; | ||||
| 2484 | else | ||||
| 2485 | return static_cast<FieldName>(Result); | ||||
| 2486 | } | ||||
| 2487 | |||||
| 2488 | // An AddrMode is trivial if it involves no calculation i.e. it is just a base | ||||
| 2489 | // with no offset. | ||||
| 2490 | bool isTrivial() { | ||||
| 2491 | // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is | ||||
| 2492 | // trivial if at most one of these terms is nonzero, except that BaseGV and | ||||
| 2493 | // BaseReg both being zero actually means a null pointer value, which we | ||||
| 2494 | // consider to be 'non-zero' here. | ||||
| 2495 | return !BaseOffs && !Scale && !(BaseGV && BaseReg); | ||||
| 2496 | } | ||||
| 2497 | |||||
| 2498 | Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) { | ||||
| 2499 | switch (Field) { | ||||
| 2500 | default: | ||||
| 2501 | return nullptr; | ||||
| 2502 | case BaseRegField: | ||||
| 2503 | return BaseReg; | ||||
| 2504 | case BaseGVField: | ||||
| 2505 | return BaseGV; | ||||
| 2506 | case ScaledRegField: | ||||
| 2507 | return ScaledReg; | ||||
| 2508 | case BaseOffsField: | ||||
| 2509 | return ConstantInt::get(IntPtrTy, BaseOffs); | ||||
| 2510 | } | ||||
| 2511 | } | ||||
| 2512 | |||||
| 2513 | void SetCombinedField(FieldName Field, Value *V, | ||||
| 2514 | const SmallVectorImpl<ExtAddrMode> &AddrModes) { | ||||
| 2515 | switch (Field) { | ||||
| 2516 | default: | ||||
| 2517 | llvm_unreachable("Unhandled fields are expected to be rejected earlier")__builtin_unreachable(); | ||||
| 2518 | break; | ||||
| 2519 | case ExtAddrMode::BaseRegField: | ||||
| 2520 | BaseReg = V; | ||||
| 2521 | break; | ||||
| 2522 | case ExtAddrMode::BaseGVField: | ||||
| 2523 | // A combined BaseGV is an Instruction, not a GlobalValue, so it goes | ||||
| 2524 | // in the BaseReg field. | ||||
| 2525 | assert(BaseReg == nullptr)((void)0); | ||||
| 2526 | BaseReg = V; | ||||
| 2527 | BaseGV = nullptr; | ||||
| 2528 | break; | ||||
| 2529 | case ExtAddrMode::ScaledRegField: | ||||
| 2530 | ScaledReg = V; | ||||
| 2531 | // If we have a mix of scaled and unscaled addrmodes then we want scale | ||||
| 2532 | // to be the scale and not zero. | ||||
| 2533 | if (!Scale) | ||||
| 2534 | for (const ExtAddrMode &AM : AddrModes) | ||||
| 2535 | if (AM.Scale) { | ||||
| 2536 | Scale = AM.Scale; | ||||
| 2537 | break; | ||||
| 2538 | } | ||||
| 2539 | break; | ||||
| 2540 | case ExtAddrMode::BaseOffsField: | ||||
| 2541 | // The offset is no longer a constant, so it goes in ScaledReg with a | ||||
| 2542 | // scale of 1. | ||||
| 2543 | assert(ScaledReg == nullptr)((void)0); | ||||
| 2544 | ScaledReg = V; | ||||
| 2545 | Scale = 1; | ||||
| 2546 | BaseOffs = 0; | ||||
| 2547 | break; | ||||
| 2548 | } | ||||
| 2549 | } | ||||
| 2550 | }; | ||||
| 2551 | |||||
| 2552 | } // end anonymous namespace | ||||
| 2553 | |||||
| 2554 | #ifndef NDEBUG1 | ||||
| 2555 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { | ||||
| 2556 | AM.print(OS); | ||||
| 2557 | return OS; | ||||
| 2558 | } | ||||
| 2559 | #endif | ||||
| 2560 | |||||
| 2561 | #if !defined(NDEBUG1) || defined(LLVM_ENABLE_DUMP) | ||||
| 2562 | void ExtAddrMode::print(raw_ostream &OS) const { | ||||
| 2563 | bool NeedPlus = false; | ||||
| 2564 | OS << "["; | ||||
| 2565 | if (InBounds) | ||||
| 2566 | OS << "inbounds "; | ||||
| 2567 | if (BaseGV) { | ||||
| 2568 | OS << (NeedPlus ? " + " : "") | ||||
| 2569 | << "GV:"; | ||||
| 2570 | BaseGV->printAsOperand(OS, /*PrintType=*/false); | ||||
| 2571 | NeedPlus = true; | ||||
| 2572 | } | ||||
| 2573 | |||||
| 2574 | if (BaseOffs) { | ||||
| 2575 | OS << (NeedPlus ? " + " : "") | ||||
| 2576 | << BaseOffs; | ||||
| 2577 | NeedPlus = true; | ||||
| 2578 | } | ||||
| 2579 | |||||
| 2580 | if (BaseReg) { | ||||
| 2581 | OS << (NeedPlus ? " + " : "") | ||||
| 2582 | << "Base:"; | ||||
| 2583 | BaseReg->printAsOperand(OS, /*PrintType=*/false); | ||||
| 2584 | NeedPlus = true; | ||||
| 2585 | } | ||||
| 2586 | if (Scale) { | ||||
| 2587 | OS << (NeedPlus ? " + " : "") | ||||
| 2588 | << Scale << "*"; | ||||
| 2589 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); | ||||
| 2590 | } | ||||
| 2591 | |||||
| 2592 | OS << ']'; | ||||
| 2593 | } | ||||
| 2594 | |||||
| 2595 | LLVM_DUMP_METHOD__attribute__((noinline)) void ExtAddrMode::dump() const { | ||||
| 2596 | print(dbgs()); | ||||
| 2597 | dbgs() << '\n'; | ||||
| 2598 | } | ||||
| 2599 | #endif | ||||
| 2600 | |||||
| 2601 | namespace { | ||||
| 2602 | |||||
| 2603 | /// This class provides transaction based operation on the IR. | ||||
| 2604 | /// Every change made through this class is recorded in the internal state and | ||||
| 2605 | /// can be undone (rollback) until commit is called. | ||||
| 2606 | /// CGP does not check if instructions could be speculatively executed when | ||||
| 2607 | /// moved. Preserving the original location would pessimize the debugging | ||||
| 2608 | /// experience, as well as negatively impact the quality of sample PGO. | ||||
| 2609 | class TypePromotionTransaction { | ||||
| 2610 | /// This represents the common interface of the individual transaction. | ||||
| 2611 | /// Each class implements the logic for doing one specific modification on | ||||
| 2612 | /// the IR via the TypePromotionTransaction. | ||||
| 2613 | class TypePromotionAction { | ||||
| 2614 | protected: | ||||
| 2615 | /// The Instruction modified. | ||||
| 2616 | Instruction *Inst; | ||||
| 2617 | |||||
| 2618 | public: | ||||
| 2619 | /// Constructor of the action. | ||||
| 2620 | /// The constructor performs the related action on the IR. | ||||
| 2621 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} | ||||
| 2622 | |||||
| 2623 | virtual ~TypePromotionAction() = default; | ||||
| 2624 | |||||
| 2625 | /// Undo the modification done by this action. | ||||
| 2626 | /// When this method is called, the IR must be in the same state as it was | ||||
| 2627 | /// before this action was applied. | ||||
| 2628 | /// \pre Undoing the action works if and only if the IR is in the exact same | ||||
| 2629 | /// state as it was directly after this action was applied. | ||||
| 2630 | virtual void undo() = 0; | ||||
| 2631 | |||||
| 2632 | /// Advocate every change made by this action. | ||||
| 2633 | /// When the results on the IR of the action are to be kept, it is important | ||||
| 2634 | /// to call this function, otherwise hidden information may be kept forever. | ||||
| 2635 | virtual void commit() { | ||||
| 2636 | // Nothing to be done, this action is not doing anything. | ||||
| 2637 | } | ||||
| 2638 | }; | ||||
| 2639 | |||||
| 2640 | /// Utility to remember the position of an instruction. | ||||
| 2641 | class InsertionHandler { | ||||
| 2642 | /// Position of an instruction. | ||||
| 2643 | /// Either an instruction: | ||||
| 2644 | /// - Is the first in a basic block: BB is used. | ||||
| 2645 | /// - Has a previous instruction: PrevInst is used. | ||||
| 2646 | union { | ||||
| 2647 | Instruction *PrevInst; | ||||
| 2648 | BasicBlock *BB; | ||||
| 2649 | } Point; | ||||
| 2650 | |||||
| 2651 | /// Remember whether or not the instruction had a previous instruction. | ||||
| 2652 | bool HasPrevInstruction; | ||||
| 2653 | |||||
| 2654 | public: | ||||
| 2655 | /// Record the position of \p Inst. | ||||
| 2656 | InsertionHandler(Instruction *Inst) { | ||||
| 2657 | BasicBlock::iterator It = Inst->getIterator(); | ||||
| 2658 | HasPrevInstruction = (It != (Inst->getParent()->begin())); | ||||
| 2659 | if (HasPrevInstruction) | ||||
| 2660 | Point.PrevInst = &*--It; | ||||
| 2661 | else | ||||
| 2662 | Point.BB = Inst->getParent(); | ||||
| 2663 | } | ||||
| 2664 | |||||
| 2665 | /// Insert \p Inst at the recorded position. | ||||
| 2666 | void insert(Instruction *Inst) { | ||||
| 2667 | if (HasPrevInstruction) { | ||||
| 2668 | if (Inst->getParent()) | ||||
| 2669 | Inst->removeFromParent(); | ||||
| 2670 | Inst->insertAfter(Point.PrevInst); | ||||
| 2671 | } else { | ||||
| 2672 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); | ||||
| 2673 | if (Inst->getParent()) | ||||
| 2674 | Inst->moveBefore(Position); | ||||
| 2675 | else | ||||
| 2676 | Inst->insertBefore(Position); | ||||
| 2677 | } | ||||
| 2678 | } | ||||
| 2679 | }; | ||||
| 2680 | |||||
| 2681 | /// Move an instruction before another. | ||||
| 2682 | class InstructionMoveBefore : public TypePromotionAction { | ||||
| 2683 | /// Original position of the instruction. | ||||
| 2684 | InsertionHandler Position; | ||||
| 2685 | |||||
| 2686 | public: | ||||
| 2687 | /// Move \p Inst before \p Before. | ||||
| 2688 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) | ||||
| 2689 | : TypePromotionAction(Inst), Position(Inst) { | ||||
| 2690 | LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Beforedo { } while (false) | ||||
| 2691 | << "\n")do { } while (false); | ||||
| 2692 | Inst->moveBefore(Before); | ||||
| 2693 | } | ||||
| 2694 | |||||
| 2695 | /// Move the instruction back to its original position. | ||||
| 2696 | void undo() override { | ||||
| 2697 | LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n")do { } while (false); | ||||
| 2698 | Position.insert(Inst); | ||||
| 2699 | } | ||||
| 2700 | }; | ||||
| 2701 | |||||
| 2702 | /// Set the operand of an instruction with a new value. | ||||
| 2703 | class OperandSetter : public TypePromotionAction { | ||||
| 2704 | /// Original operand of the instruction. | ||||
| 2705 | Value *Origin; | ||||
| 2706 | |||||
| 2707 | /// Index of the modified instruction. | ||||
| 2708 | unsigned Idx; | ||||
| 2709 | |||||
| 2710 | public: | ||||
| 2711 | /// Set \p Idx operand of \p Inst with \p NewVal. | ||||
| 2712 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) | ||||
| 2713 | : TypePromotionAction(Inst), Idx(Idx) { | ||||
| 2714 | LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"do { } while (false) | ||||
| 2715 | << "for:" << *Inst << "\n"do { } while (false) | ||||
| 2716 | << "with:" << *NewVal << "\n")do { } while (false); | ||||
| 2717 | Origin = Inst->getOperand(Idx); | ||||
| 2718 | Inst->setOperand(Idx, NewVal); | ||||
| 2719 | } | ||||
| 2720 | |||||
| 2721 | /// Restore the original value of the instruction. | ||||
| 2722 | void undo() override { | ||||
| 2723 | LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"do { } while (false) | ||||
| 2724 | << "for: " << *Inst << "\n"do { } while (false) | ||||
| 2725 | << "with: " << *Origin << "\n")do { } while (false); | ||||
| 2726 | Inst->setOperand(Idx, Origin); | ||||
| 2727 | } | ||||
| 2728 | }; | ||||
| 2729 | |||||
| 2730 | /// Hide the operands of an instruction. | ||||
| 2731 | /// Do as if this instruction was not using any of its operands. | ||||
| 2732 | class OperandsHider : public TypePromotionAction { | ||||
| 2733 | /// The list of original operands. | ||||
| 2734 | SmallVector<Value *, 4> OriginalValues; | ||||
| 2735 | |||||
| 2736 | public: | ||||
| 2737 | /// Remove \p Inst from the uses of the operands of \p Inst. | ||||
| 2738 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { | ||||
| 2739 | LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n")do { } while (false); | ||||
| 2740 | unsigned NumOpnds = Inst->getNumOperands(); | ||||
| 2741 | OriginalValues.reserve(NumOpnds); | ||||
| 2742 | for (unsigned It = 0; It < NumOpnds; ++It) { | ||||
| 2743 | // Save the current operand. | ||||
| 2744 | Value *Val = Inst->getOperand(It); | ||||
| 2745 | OriginalValues.push_back(Val); | ||||
| 2746 | // Set a dummy one. | ||||
| 2747 | // We could use OperandSetter here, but that would imply an overhead | ||||
| 2748 | // that we are not willing to pay. | ||||
| 2749 | Inst->setOperand(It, UndefValue::get(Val->getType())); | ||||
| 2750 | } | ||||
| 2751 | } | ||||
| 2752 | |||||
| 2753 | /// Restore the original list of uses. | ||||
| 2754 | void undo() override { | ||||
| 2755 | LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n")do { } while (false); | ||||
| 2756 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) | ||||
| 2757 | Inst->setOperand(It, OriginalValues[It]); | ||||
| 2758 | } | ||||
| 2759 | }; | ||||
| 2760 | |||||
| 2761 | /// Build a truncate instruction. | ||||
| 2762 | class TruncBuilder : public TypePromotionAction { | ||||
| 2763 | Value *Val; | ||||
| 2764 | |||||
| 2765 | public: | ||||
| 2766 | /// Build a truncate instruction of \p Opnd producing a \p Ty | ||||
| 2767 | /// result. | ||||
| 2768 | /// trunc Opnd to Ty. | ||||
| 2769 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { | ||||
| 2770 | IRBuilder<> Builder(Opnd); | ||||
| 2771 | Builder.SetCurrentDebugLocation(DebugLoc()); | ||||
| 2772 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); | ||||
| 2773 | LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n")do { } while (false); | ||||
| 2774 | } | ||||
| 2775 | |||||
| 2776 | /// Get the built value. | ||||
| 2777 | Value *getBuiltValue() { return Val; } | ||||
| 2778 | |||||
| 2779 | /// Remove the built instruction. | ||||
| 2780 | void undo() override { | ||||
| 2781 | LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n")do { } while (false); | ||||
| 2782 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) | ||||
| 2783 | IVal->eraseFromParent(); | ||||
| 2784 | } | ||||
| 2785 | }; | ||||
| 2786 | |||||
| 2787 | /// Build a sign extension instruction. | ||||
| 2788 | class SExtBuilder : public TypePromotionAction { | ||||
| 2789 | Value *Val; | ||||
| 2790 | |||||
| 2791 | public: | ||||
| 2792 | /// Build a sign extension instruction of \p Opnd producing a \p Ty | ||||
| 2793 | /// result. | ||||
| 2794 | /// sext Opnd to Ty. | ||||
| 2795 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) | ||||
| 2796 | : TypePromotionAction(InsertPt) { | ||||
| 2797 | IRBuilder<> Builder(InsertPt); | ||||
| 2798 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); | ||||
| 2799 | LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n")do { } while (false); | ||||
| 2800 | } | ||||
| 2801 | |||||
| 2802 | /// Get the built value. | ||||
| 2803 | Value *getBuiltValue() { return Val; } | ||||
| 2804 | |||||
| 2805 | /// Remove the built instruction. | ||||
| 2806 | void undo() override { | ||||
| 2807 | LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n")do { } while (false); | ||||
| 2808 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) | ||||
| 2809 | IVal->eraseFromParent(); | ||||
| 2810 | } | ||||
| 2811 | }; | ||||
| 2812 | |||||
| 2813 | /// Build a zero extension instruction. | ||||
| 2814 | class ZExtBuilder : public TypePromotionAction { | ||||
| 2815 | Value *Val; | ||||
| 2816 | |||||
| 2817 | public: | ||||
| 2818 | /// Build a zero extension instruction of \p Opnd producing a \p Ty | ||||
| 2819 | /// result. | ||||
| 2820 | /// zext Opnd to Ty. | ||||
| 2821 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) | ||||
| 2822 | : TypePromotionAction(InsertPt) { | ||||
| 2823 | IRBuilder<> Builder(InsertPt); | ||||
| 2824 | Builder.SetCurrentDebugLocation(DebugLoc()); | ||||
| 2825 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); | ||||
| 2826 | LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n")do { } while (false); | ||||
| 2827 | } | ||||
| 2828 | |||||
| 2829 | /// Get the built value. | ||||
| 2830 | Value *getBuiltValue() { return Val; } | ||||
| 2831 | |||||
| 2832 | /// Remove the built instruction. | ||||
| 2833 | void undo() override { | ||||
| 2834 | LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n")do { } while (false); | ||||
| 2835 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) | ||||
| 2836 | IVal->eraseFromParent(); | ||||
| 2837 | } | ||||
| 2838 | }; | ||||
| 2839 | |||||
| 2840 | /// Mutate an instruction to another type. | ||||
| 2841 | class TypeMutator : public TypePromotionAction { | ||||
| 2842 | /// Record the original type. | ||||
| 2843 | Type *OrigTy; | ||||
| 2844 | |||||
| 2845 | public: | ||||
| 2846 | /// Mutate the type of \p Inst into \p NewTy. | ||||
| 2847 | TypeMutator(Instruction *Inst, Type *NewTy) | ||||
| 2848 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { | ||||
| 2849 | LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTydo { } while (false) | ||||
| 2850 | << "\n")do { } while (false); | ||||
| 2851 | Inst->mutateType(NewTy); | ||||
| 2852 | } | ||||
| 2853 | |||||
| 2854 | /// Mutate the instruction back to its original type. | ||||
| 2855 | void undo() override { | ||||
| 2856 | LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTydo { } while (false) | ||||
| 2857 | << "\n")do { } while (false); | ||||
| 2858 | Inst->mutateType(OrigTy); | ||||
| 2859 | } | ||||
| 2860 | }; | ||||
| 2861 | |||||
| 2862 | /// Replace the uses of an instruction by another instruction. | ||||
| 2863 | class UsesReplacer : public TypePromotionAction { | ||||
| 2864 | /// Helper structure to keep track of the replaced uses. | ||||
| 2865 | struct InstructionAndIdx { | ||||
| 2866 | /// The instruction using the instruction. | ||||
| 2867 | Instruction *Inst; | ||||
| 2868 | |||||
| 2869 | /// The index where this instruction is used for Inst. | ||||
| 2870 | unsigned Idx; | ||||
| 2871 | |||||
| 2872 | InstructionAndIdx(Instruction *Inst, unsigned Idx) | ||||
| 2873 | : Inst(Inst), Idx(Idx) {} | ||||
| 2874 | }; | ||||
| 2875 | |||||
| 2876 | /// Keep track of the original uses (pair Instruction, Index). | ||||
| 2877 | SmallVector<InstructionAndIdx, 4> OriginalUses; | ||||
| 2878 | /// Keep track of the debug users. | ||||
| 2879 | SmallVector<DbgValueInst *, 1> DbgValues; | ||||
| 2880 | |||||
| 2881 | /// Keep track of the new value so that we can undo it by replacing | ||||
| 2882 | /// instances of the new value with the original value. | ||||
| 2883 | Value *New; | ||||
| 2884 | |||||
| 2885 | using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator; | ||||
| 2886 | |||||
| 2887 | public: | ||||
| 2888 | /// Replace all the use of \p Inst by \p New. | ||||
| 2889 | UsesReplacer(Instruction *Inst, Value *New) | ||||
| 2890 | : TypePromotionAction(Inst), New(New) { | ||||
| 2891 | LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *Newdo { } while (false) | ||||
| 2892 | << "\n")do { } while (false); | ||||
| 2893 | // Record the original uses. | ||||
| 2894 | for (Use &U : Inst->uses()) { | ||||
| 2895 | Instruction *UserI = cast<Instruction>(U.getUser()); | ||||
| 2896 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); | ||||
| 2897 | } | ||||
| 2898 | // Record the debug uses separately. They are not in the instruction's | ||||
| 2899 | // use list, but they are replaced by RAUW. | ||||
| 2900 | findDbgValues(DbgValues, Inst); | ||||
| 2901 | |||||
| 2902 | // Now, we can replace the uses. | ||||
| 2903 | Inst->replaceAllUsesWith(New); | ||||
| 2904 | } | ||||
| 2905 | |||||
| 2906 | /// Reassign the original uses of Inst to Inst. | ||||
| 2907 | void undo() override { | ||||
| 2908 | LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n")do { } while (false); | ||||
| 2909 | for (InstructionAndIdx &Use : OriginalUses) | ||||
| 2910 | Use.Inst->setOperand(Use.Idx, Inst); | ||||
| 2911 | // RAUW has replaced all original uses with references to the new value, | ||||
| 2912 | // including the debug uses. Since we are undoing the replacements, | ||||
| 2913 | // the original debug uses must also be reinstated to maintain the | ||||
| 2914 | // correctness and utility of debug value instructions. | ||||
| 2915 | for (auto *DVI : DbgValues) | ||||
| 2916 | DVI->replaceVariableLocationOp(New, Inst); | ||||
| 2917 | } | ||||
| 2918 | }; | ||||
| 2919 | |||||
| 2920 | /// Remove an instruction from the IR. | ||||
| 2921 | class InstructionRemover : public TypePromotionAction { | ||||
| 2922 | /// Original position of the instruction. | ||||
| 2923 | InsertionHandler Inserter; | ||||
| 2924 | |||||
| 2925 | /// Helper structure to hide all the link to the instruction. In other | ||||
| 2926 | /// words, this helps to do as if the instruction was removed. | ||||
| 2927 | OperandsHider Hider; | ||||
| 2928 | |||||
| 2929 | /// Keep track of the uses replaced, if any. | ||||
| 2930 | UsesReplacer *Replacer = nullptr; | ||||
| 2931 | |||||
| 2932 | /// Keep track of instructions removed. | ||||
| 2933 | SetOfInstrs &RemovedInsts; | ||||
| 2934 | |||||
| 2935 | public: | ||||
| 2936 | /// Remove all reference of \p Inst and optionally replace all its | ||||
| 2937 | /// uses with New. | ||||
| 2938 | /// \p RemovedInsts Keep track of the instructions removed by this Action. | ||||
| 2939 | /// \pre If !Inst->use_empty(), then New != nullptr | ||||
| 2940 | InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, | ||||
| 2941 | Value *New = nullptr) | ||||
| 2942 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), | ||||
| 2943 | RemovedInsts(RemovedInsts) { | ||||
| 2944 | if (New) | ||||
| 2945 | Replacer = new UsesReplacer(Inst, New); | ||||
| 2946 | LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n")do { } while (false); | ||||
| 2947 | RemovedInsts.insert(Inst); | ||||
| 2948 | /// The instructions removed here will be freed after completing | ||||
| 2949 | /// optimizeBlock() for all blocks as we need to keep track of the | ||||
| 2950 | /// removed instructions during promotion. | ||||
| 2951 | Inst->removeFromParent(); | ||||
| 2952 | } | ||||
| 2953 | |||||
| 2954 | ~InstructionRemover() override { delete Replacer; } | ||||
| 2955 | |||||
| 2956 | /// Resurrect the instruction and reassign it to the proper uses if | ||||
| 2957 | /// new value was provided when build this action. | ||||
| 2958 | void undo() override { | ||||
| 2959 | LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n")do { } while (false); | ||||
| 2960 | Inserter.insert(Inst); | ||||
| 2961 | if (Replacer) | ||||
| 2962 | Replacer->undo(); | ||||
| 2963 | Hider.undo(); | ||||
| 2964 | RemovedInsts.erase(Inst); | ||||
| 2965 | } | ||||
| 2966 | }; | ||||
| 2967 | |||||
| 2968 | public: | ||||
| 2969 | /// Restoration point. | ||||
| 2970 | /// The restoration point is a pointer to an action instead of an iterator | ||||
| 2971 | /// because the iterator may be invalidated but not the pointer. | ||||
| 2972 | using ConstRestorationPt = const TypePromotionAction *; | ||||
| 2973 | |||||
| 2974 | TypePromotionTransaction(SetOfInstrs &RemovedInsts) | ||||
| 2975 | : RemovedInsts(RemovedInsts) {} | ||||
| 2976 | |||||
| 2977 | /// Advocate every changes made in that transaction. Return true if any change | ||||
| 2978 | /// happen. | ||||
| 2979 | bool commit(); | ||||
| 2980 | |||||
| 2981 | /// Undo all the changes made after the given point. | ||||
| 2982 | void rollback(ConstRestorationPt Point); | ||||
| 2983 | |||||
| 2984 | /// Get the current restoration point. | ||||
| 2985 | ConstRestorationPt getRestorationPoint() const; | ||||
| 2986 | |||||
| 2987 | /// \name API for IR modification with state keeping to support rollback. | ||||
| 2988 | /// @{ | ||||
| 2989 | /// Same as Instruction::setOperand. | ||||
| 2990 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); | ||||
| 2991 | |||||
| 2992 | /// Same as Instruction::eraseFromParent. | ||||
| 2993 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); | ||||
| 2994 | |||||
| 2995 | /// Same as Value::replaceAllUsesWith. | ||||
| 2996 | void replaceAllUsesWith(Instruction *Inst, Value *New); | ||||
| 2997 | |||||
| 2998 | /// Same as Value::mutateType. | ||||
| 2999 | void mutateType(Instruction *Inst, Type *NewTy); | ||||
| 3000 | |||||
| 3001 | /// Same as IRBuilder::createTrunc. | ||||
| 3002 | Value *createTrunc(Instruction *Opnd, Type *Ty); | ||||
| 3003 | |||||
| 3004 | /// Same as IRBuilder::createSExt. | ||||
| 3005 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); | ||||
| 3006 | |||||
| 3007 | /// Same as IRBuilder::createZExt. | ||||
| 3008 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); | ||||
| 3009 | |||||
| 3010 | /// Same as Instruction::moveBefore. | ||||
| 3011 | void moveBefore(Instruction *Inst, Instruction *Before); | ||||
| 3012 | /// @} | ||||
| 3013 | |||||
| 3014 | private: | ||||
| 3015 | /// The ordered list of actions made so far. | ||||
| 3016 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; | ||||
| 3017 | |||||
| 3018 | using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator; | ||||
| 3019 | |||||
| 3020 | SetOfInstrs &RemovedInsts; | ||||
| 3021 | }; | ||||
| 3022 | |||||
| 3023 | } // end anonymous namespace | ||||
| 3024 | |||||
| 3025 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, | ||||
| 3026 | Value *NewVal) { | ||||
| 3027 | Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>( | ||||
| 3028 | Inst, Idx, NewVal)); | ||||
| 3029 | } | ||||
| 3030 | |||||
| 3031 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, | ||||
| 3032 | Value *NewVal) { | ||||
| 3033 | Actions.push_back( | ||||
| 3034 | std::make_unique<TypePromotionTransaction::InstructionRemover>( | ||||
| 3035 | Inst, RemovedInsts, NewVal)); | ||||
| 3036 | } | ||||
| 3037 | |||||
| 3038 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, | ||||
| 3039 | Value *New) { | ||||
| 3040 | Actions.push_back( | ||||
| 3041 | std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); | ||||
| 3042 | } | ||||
| 3043 | |||||
| 3044 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { | ||||
| 3045 | Actions.push_back( | ||||
| 3046 | std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); | ||||
| 3047 | } | ||||
| 3048 | |||||
| 3049 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, | ||||
| 3050 | Type *Ty) { | ||||
| 3051 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); | ||||
| 3052 | Value *Val = Ptr->getBuiltValue(); | ||||
| 3053 | Actions.push_back(std::move(Ptr)); | ||||
| 3054 | return Val; | ||||
| 3055 | } | ||||
| 3056 | |||||
| 3057 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, | ||||
| 3058 | Value *Opnd, Type *Ty) { | ||||
| 3059 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); | ||||
| 3060 | Value *Val = Ptr->getBuiltValue(); | ||||
| 3061 | Actions.push_back(std::move(Ptr)); | ||||
| 3062 | return Val; | ||||
| 3063 | } | ||||
| 3064 | |||||
| 3065 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, | ||||
| 3066 | Value *Opnd, Type *Ty) { | ||||
| 3067 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); | ||||
| 3068 | Value *Val = Ptr->getBuiltValue(); | ||||
| 3069 | Actions.push_back(std::move(Ptr)); | ||||
| 3070 | return Val; | ||||
| 3071 | } | ||||
| 3072 | |||||
| 3073 | void TypePromotionTransaction::moveBefore(Instruction *Inst, | ||||
| 3074 | Instruction *Before) { | ||||
| 3075 | Actions.push_back( | ||||
| 3076 | std::make_unique<TypePromotionTransaction::InstructionMoveBefore>( | ||||
| 3077 | Inst, Before)); | ||||
| 3078 | } | ||||
| 3079 | |||||
| 3080 | TypePromotionTransaction::ConstRestorationPt | ||||
| 3081 | TypePromotionTransaction::getRestorationPoint() const { | ||||
| 3082 | return !Actions.empty() ? Actions.back().get() : nullptr; | ||||
| 3083 | } | ||||
| 3084 | |||||
| 3085 | bool TypePromotionTransaction::commit() { | ||||
| 3086 | for (std::unique_ptr<TypePromotionAction> &Action : Actions) | ||||
| 3087 | Action->commit(); | ||||
| 3088 | bool Modified = !Actions.empty(); | ||||
| 3089 | Actions.clear(); | ||||
| 3090 | return Modified; | ||||
| 3091 | } | ||||
| 3092 | |||||
| 3093 | void TypePromotionTransaction::rollback( | ||||
| 3094 | TypePromotionTransaction::ConstRestorationPt Point) { | ||||
| 3095 | while (!Actions.empty() && Point != Actions.back().get()) { | ||||
| 3096 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); | ||||
| 3097 | Curr->undo(); | ||||
| 3098 | } | ||||
| 3099 | } | ||||
| 3100 | |||||
| 3101 | namespace { | ||||
| 3102 | |||||
| 3103 | /// A helper class for matching addressing modes. | ||||
| 3104 | /// | ||||
| 3105 | /// This encapsulates the logic for matching the target-legal addressing modes. | ||||
| 3106 | class AddressingModeMatcher { | ||||
| 3107 | SmallVectorImpl<Instruction*> &AddrModeInsts; | ||||
| 3108 | const TargetLowering &TLI; | ||||
| 3109 | const TargetRegisterInfo &TRI; | ||||
| 3110 | const DataLayout &DL; | ||||
| 3111 | const LoopInfo &LI; | ||||
| 3112 | const std::function<const DominatorTree &()> getDTFn; | ||||
| 3113 | |||||
| 3114 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and | ||||
| 3115 | /// the memory instruction that we're computing this address for. | ||||
| 3116 | Type *AccessTy; | ||||
| 3117 | unsigned AddrSpace; | ||||
| 3118 | Instruction *MemoryInst; | ||||
| 3119 | |||||
| 3120 | /// This is the addressing mode that we're building up. This is | ||||
| 3121 | /// part of the return value of this addressing mode matching stuff. | ||||
| 3122 | ExtAddrMode &AddrMode; | ||||
| 3123 | |||||
| 3124 | /// The instructions inserted by other CodeGenPrepare optimizations. | ||||
| 3125 | const SetOfInstrs &InsertedInsts; | ||||
| 3126 | |||||
| 3127 | /// A map from the instructions to their type before promotion. | ||||
| 3128 | InstrToOrigTy &PromotedInsts; | ||||
| 3129 | |||||
| 3130 | /// The ongoing transaction where every action should be registered. | ||||
| 3131 | TypePromotionTransaction &TPT; | ||||
| 3132 | |||||
| 3133 | // A GEP which has too large offset to be folded into the addressing mode. | ||||
| 3134 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP; | ||||
| 3135 | |||||
| 3136 | /// This is set to true when we should not do profitability checks. | ||||
| 3137 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. | ||||
| 3138 | bool IgnoreProfitability; | ||||
| 3139 | |||||
| 3140 | /// True if we are optimizing for size. | ||||
| 3141 | bool OptSize; | ||||
| 3142 | |||||
| 3143 | ProfileSummaryInfo *PSI; | ||||
| 3144 | BlockFrequencyInfo *BFI; | ||||
| 3145 | |||||
| 3146 | AddressingModeMatcher( | ||||
| 3147 | SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI, | ||||
| 3148 | const TargetRegisterInfo &TRI, const LoopInfo &LI, | ||||
| 3149 | const std::function<const DominatorTree &()> getDTFn, | ||||
| 3150 | Type *AT, unsigned AS, Instruction *MI, ExtAddrMode &AM, | ||||
| 3151 | const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts, | ||||
| 3152 | TypePromotionTransaction &TPT, | ||||
| 3153 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, | ||||
| 3154 | bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) | ||||
| 3155 | : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), | ||||
| 3156 | DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn), | ||||
| 3157 | AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM), | ||||
| 3158 | InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT), | ||||
| 3159 | LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) { | ||||
| 3160 | IgnoreProfitability = false; | ||||
| 3161 | } | ||||
| 3162 | |||||
| 3163 | public: | ||||
| 3164 | /// Find the maximal addressing mode that a load/store of V can fold, | ||||
| 3165 | /// give an access type of AccessTy. This returns a list of involved | ||||
| 3166 | /// instructions in AddrModeInsts. | ||||
| 3167 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare | ||||
| 3168 | /// optimizations. | ||||
| 3169 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
| 3170 | /// \p The ongoing transaction where every action should be registered. | ||||
| 3171 | static ExtAddrMode | ||||
| 3172 | Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst, | ||||
| 3173 | SmallVectorImpl<Instruction *> &AddrModeInsts, | ||||
| 3174 | const TargetLowering &TLI, const LoopInfo &LI, | ||||
| 3175 | const std::function<const DominatorTree &()> getDTFn, | ||||
| 3176 | const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts, | ||||
| 3177 | InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT, | ||||
| 3178 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, | ||||
| 3179 | bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) { | ||||
| 3180 | ExtAddrMode Result; | ||||
| 3181 | |||||
| 3182 | bool Success = AddressingModeMatcher( | ||||
| 3183 | AddrModeInsts, TLI, TRI, LI, getDTFn, AccessTy, AS, MemoryInst, Result, | ||||
| 3184 | InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, | ||||
| 3185 | BFI).matchAddr(V, 0); | ||||
| 3186 | (void)Success; assert(Success && "Couldn't select *anything*?")((void)0); | ||||
| 3187 | return Result; | ||||
| 3188 | } | ||||
| 3189 | |||||
| 3190 | private: | ||||
| 3191 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); | ||||
| 3192 | bool matchAddr(Value *Addr, unsigned Depth); | ||||
| 3193 | bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth, | ||||
| 3194 | bool *MovedAway = nullptr); | ||||
| 3195 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, | ||||
| 3196 | ExtAddrMode &AMBefore, | ||||
| 3197 | ExtAddrMode &AMAfter); | ||||
| 3198 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); | ||||
| 3199 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, | ||||
| 3200 | Value *PromotedOperand) const; | ||||
| 3201 | }; | ||||
| 3202 | |||||
| 3203 | class PhiNodeSet; | ||||
| 3204 | |||||
| 3205 | /// An iterator for PhiNodeSet. | ||||
| 3206 | class PhiNodeSetIterator { | ||||
| 3207 | PhiNodeSet * const Set; | ||||
| 3208 | size_t CurrentIndex = 0; | ||||
| 3209 | |||||
| 3210 | public: | ||||
| 3211 | /// The constructor. Start should point to either a valid element, or be equal | ||||
| 3212 | /// to the size of the underlying SmallVector of the PhiNodeSet. | ||||
| 3213 | PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start); | ||||
| 3214 | PHINode * operator*() const; | ||||
| 3215 | PhiNodeSetIterator& operator++(); | ||||
| 3216 | bool operator==(const PhiNodeSetIterator &RHS) const; | ||||
| 3217 | bool operator!=(const PhiNodeSetIterator &RHS) const; | ||||
| 3218 | }; | ||||
| 3219 | |||||
| 3220 | /// Keeps a set of PHINodes. | ||||
| 3221 | /// | ||||
| 3222 | /// This is a minimal set implementation for a specific use case: | ||||
| 3223 | /// It is very fast when there are very few elements, but also provides good | ||||
| 3224 | /// performance when there are many. It is similar to SmallPtrSet, but also | ||||
| 3225 | /// provides iteration by insertion order, which is deterministic and stable | ||||
| 3226 | /// across runs. It is also similar to SmallSetVector, but provides removing | ||||
| 3227 | /// elements in O(1) time. This is achieved by not actually removing the element | ||||
| 3228 | /// from the underlying vector, so comes at the cost of using more memory, but | ||||
| 3229 | /// that is fine, since PhiNodeSets are used as short lived objects. | ||||
| 3230 | class PhiNodeSet { | ||||
| 3231 | friend class PhiNodeSetIterator; | ||||
| 3232 | |||||
| 3233 | using MapType = SmallDenseMap<PHINode *, size_t, 32>; | ||||
| 3234 | using iterator = PhiNodeSetIterator; | ||||
| 3235 | |||||
| 3236 | /// Keeps the elements in the order of their insertion in the underlying | ||||
| 3237 | /// vector. To achieve constant time removal, it never deletes any element. | ||||
| 3238 | SmallVector<PHINode *, 32> NodeList; | ||||
| 3239 | |||||
| 3240 | /// Keeps the elements in the underlying set implementation. This (and not the | ||||
| 3241 | /// NodeList defined above) is the source of truth on whether an element | ||||
| 3242 | /// is actually in the collection. | ||||
| 3243 | MapType NodeMap; | ||||
| 3244 | |||||
| 3245 | /// Points to the first valid (not deleted) element when the set is not empty | ||||
| 3246 | /// and the value is not zero. Equals to the size of the underlying vector | ||||
| 3247 | /// when the set is empty. When the value is 0, as in the beginning, the | ||||
| 3248 | /// first element may or may not be valid. | ||||
| 3249 | size_t FirstValidElement = 0; | ||||
| 3250 | |||||
| 3251 | public: | ||||
| 3252 | /// Inserts a new element to the collection. | ||||
| 3253 | /// \returns true if the element is actually added, i.e. was not in the | ||||
| 3254 | /// collection before the operation. | ||||
| 3255 | bool insert(PHINode *Ptr) { | ||||
| 3256 | if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) { | ||||
| 3257 | NodeList.push_back(Ptr); | ||||
| 3258 | return true; | ||||
| 3259 | } | ||||
| 3260 | return false; | ||||
| 3261 | } | ||||
| 3262 | |||||
| 3263 | /// Removes the element from the collection. | ||||
| 3264 | /// \returns whether the element is actually removed, i.e. was in the | ||||
| 3265 | /// collection before the operation. | ||||
| 3266 | bool erase(PHINode *Ptr) { | ||||
| 3267 | if (NodeMap.erase(Ptr)) { | ||||
| 3268 | SkipRemovedElements(FirstValidElement); | ||||
| 3269 | return true; | ||||
| 3270 | } | ||||
| 3271 | return false; | ||||
| 3272 | } | ||||
| 3273 | |||||
| 3274 | /// Removes all elements and clears the collection. | ||||
| 3275 | void clear() { | ||||
| 3276 | NodeMap.clear(); | ||||
| 3277 | NodeList.clear(); | ||||
| 3278 | FirstValidElement = 0; | ||||
| 3279 | } | ||||
| 3280 | |||||
| 3281 | /// \returns an iterator that will iterate the elements in the order of | ||||
| 3282 | /// insertion. | ||||
| 3283 | iterator begin() { | ||||
| 3284 | if (FirstValidElement == 0) | ||||
| 3285 | SkipRemovedElements(FirstValidElement); | ||||
| 3286 | return PhiNodeSetIterator(this, FirstValidElement); | ||||
| 3287 | } | ||||
| 3288 | |||||
| 3289 | /// \returns an iterator that points to the end of the collection. | ||||
| 3290 | iterator end() { return PhiNodeSetIterator(this, NodeList.size()); } | ||||
| 3291 | |||||
| 3292 | /// Returns the number of elements in the collection. | ||||
| 3293 | size_t size() const { | ||||
| 3294 | return NodeMap.size(); | ||||
| 3295 | } | ||||
| 3296 | |||||
| 3297 | /// \returns 1 if the given element is in the collection, and 0 if otherwise. | ||||
| 3298 | size_t count(PHINode *Ptr) const { | ||||
| 3299 | return NodeMap.count(Ptr); | ||||
| 3300 | } | ||||
| 3301 | |||||
| 3302 | private: | ||||
| 3303 | /// Updates the CurrentIndex so that it will point to a valid element. | ||||
| 3304 | /// | ||||
| 3305 | /// If the element of NodeList at CurrentIndex is valid, it does not | ||||
| 3306 | /// change it. If there are no more valid elements, it updates CurrentIndex | ||||
| 3307 | /// to point to the end of the NodeList. | ||||
| 3308 | void SkipRemovedElements(size_t &CurrentIndex) { | ||||
| 3309 | while (CurrentIndex < NodeList.size()) { | ||||
| 3310 | auto it = NodeMap.find(NodeList[CurrentIndex]); | ||||
| 3311 | // If the element has been deleted and added again later, NodeMap will | ||||
| 3312 | // point to a different index, so CurrentIndex will still be invalid. | ||||
| 3313 | if (it != NodeMap.end() && it->second == CurrentIndex) | ||||
| 3314 | break; | ||||
| 3315 | ++CurrentIndex; | ||||
| 3316 | } | ||||
| 3317 | } | ||||
| 3318 | }; | ||||
| 3319 | |||||
| 3320 | PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start) | ||||
| 3321 | : Set(Set), CurrentIndex(Start) {} | ||||
| 3322 | |||||
| 3323 | PHINode * PhiNodeSetIterator::operator*() const { | ||||
| 3324 | assert(CurrentIndex < Set->NodeList.size() &&((void)0) | ||||
| 3325 | "PhiNodeSet access out of range")((void)0); | ||||
| 3326 | return Set->NodeList[CurrentIndex]; | ||||
| 3327 | } | ||||
| 3328 | |||||
| 3329 | PhiNodeSetIterator& PhiNodeSetIterator::operator++() { | ||||
| 3330 | assert(CurrentIndex < Set->NodeList.size() &&((void)0) | ||||
| 3331 | "PhiNodeSet access out of range")((void)0); | ||||
| 3332 | ++CurrentIndex; | ||||
| 3333 | Set->SkipRemovedElements(CurrentIndex); | ||||
| 3334 | return *this; | ||||
| 3335 | } | ||||
| 3336 | |||||
| 3337 | bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const { | ||||
| 3338 | return CurrentIndex == RHS.CurrentIndex; | ||||
| 3339 | } | ||||
| 3340 | |||||
| 3341 | bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const { | ||||
| 3342 | return !((*this) == RHS); | ||||
| 3343 | } | ||||
| 3344 | |||||
| 3345 | /// Keep track of simplification of Phi nodes. | ||||
| 3346 | /// Accept the set of all phi nodes and erase phi node from this set | ||||
| 3347 | /// if it is simplified. | ||||
| 3348 | class SimplificationTracker { | ||||
| 3349 | DenseMap<Value *, Value *> Storage; | ||||
| 3350 | const SimplifyQuery &SQ; | ||||
| 3351 | // Tracks newly created Phi nodes. The elements are iterated by insertion | ||||
| 3352 | // order. | ||||
| 3353 | PhiNodeSet AllPhiNodes; | ||||
| 3354 | // Tracks newly created Select nodes. | ||||
| 3355 | SmallPtrSet<SelectInst *, 32> AllSelectNodes; | ||||
| 3356 | |||||
| 3357 | public: | ||||
| 3358 | SimplificationTracker(const SimplifyQuery &sq) | ||||
| 3359 | : SQ(sq) {} | ||||
| 3360 | |||||
| 3361 | Value *Get(Value *V) { | ||||
| 3362 | do { | ||||
| 3363 | auto SV = Storage.find(V); | ||||
| 3364 | if (SV == Storage.end()) | ||||
| 3365 | return V; | ||||
| 3366 | V = SV->second; | ||||
| 3367 | } while (true); | ||||
| 3368 | } | ||||
| 3369 | |||||
| 3370 | Value *Simplify(Value *Val) { | ||||
| 3371 | SmallVector<Value *, 32> WorkList; | ||||
| 3372 | SmallPtrSet<Value *, 32> Visited; | ||||
| 3373 | WorkList.push_back(Val); | ||||
| 3374 | while (!WorkList.empty()) { | ||||
| 3375 | auto *P = WorkList.pop_back_val(); | ||||
| 3376 | if (!Visited.insert(P).second) | ||||
| 3377 | continue; | ||||
| 3378 | if (auto *PI = dyn_cast<Instruction>(P)) | ||||
| 3379 | if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) { | ||||
| 3380 | for (auto *U : PI->users()) | ||||
| 3381 | WorkList.push_back(cast<Value>(U)); | ||||
| 3382 | Put(PI, V); | ||||
| 3383 | PI->replaceAllUsesWith(V); | ||||
| 3384 | if (auto *PHI = dyn_cast<PHINode>(PI)) | ||||
| 3385 | AllPhiNodes.erase(PHI); | ||||
| 3386 | if (auto *Select = dyn_cast<SelectInst>(PI)) | ||||
| 3387 | AllSelectNodes.erase(Select); | ||||
| 3388 | PI->eraseFromParent(); | ||||
| 3389 | } | ||||
| 3390 | } | ||||
| 3391 | return Get(Val); | ||||
| 3392 | } | ||||
| 3393 | |||||
| 3394 | void Put(Value *From, Value *To) { | ||||
| 3395 | Storage.insert({ From, To }); | ||||
| 3396 | } | ||||
| 3397 | |||||
| 3398 | void ReplacePhi(PHINode *From, PHINode *To) { | ||||
| 3399 | Value* OldReplacement = Get(From); | ||||
| 3400 | while (OldReplacement != From) { | ||||
| 3401 | From = To; | ||||
| 3402 | To = dyn_cast<PHINode>(OldReplacement); | ||||
| 3403 | OldReplacement = Get(From); | ||||
| 3404 | } | ||||
| 3405 | assert(To && Get(To) == To && "Replacement PHI node is already replaced.")((void)0); | ||||
| 3406 | Put(From, To); | ||||
| 3407 | From->replaceAllUsesWith(To); | ||||
| 3408 | AllPhiNodes.erase(From); | ||||
| 3409 | From->eraseFromParent(); | ||||
| 3410 | } | ||||
| 3411 | |||||
| 3412 | PhiNodeSet& newPhiNodes() { return AllPhiNodes; } | ||||
| 3413 | |||||
| 3414 | void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); } | ||||
| 3415 | |||||
| 3416 | void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); } | ||||
| 3417 | |||||
| 3418 | unsigned countNewPhiNodes() const { return AllPhiNodes.size(); } | ||||
| 3419 | |||||
| 3420 | unsigned countNewSelectNodes() const { return AllSelectNodes.size(); } | ||||
| 3421 | |||||
| 3422 | void destroyNewNodes(Type *CommonType) { | ||||
| 3423 | // For safe erasing, replace the uses with dummy value first. | ||||
| 3424 | auto *Dummy = UndefValue::get(CommonType); | ||||
| 3425 | for (auto *I : AllPhiNodes) { | ||||
| 3426 | I->replaceAllUsesWith(Dummy); | ||||
| 3427 | I->eraseFromParent(); | ||||
| 3428 | } | ||||
| 3429 | AllPhiNodes.clear(); | ||||
| 3430 | for (auto *I : AllSelectNodes) { | ||||
| 3431 | I->replaceAllUsesWith(Dummy); | ||||
| 3432 | I->eraseFromParent(); | ||||
| 3433 | } | ||||
| 3434 | AllSelectNodes.clear(); | ||||
| 3435 | } | ||||
| 3436 | }; | ||||
| 3437 | |||||
| 3438 | /// A helper class for combining addressing modes. | ||||
| 3439 | class AddressingModeCombiner { | ||||
| 3440 | typedef DenseMap<Value *, Value *> FoldAddrToValueMapping; | ||||
| 3441 | typedef std::pair<PHINode *, PHINode *> PHIPair; | ||||
| 3442 | |||||
| 3443 | private: | ||||
| 3444 | /// The addressing modes we've collected. | ||||
| 3445 | SmallVector<ExtAddrMode, 16> AddrModes; | ||||
| 3446 | |||||
| 3447 | /// The field in which the AddrModes differ, when we have more than one. | ||||
| 3448 | ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField; | ||||
| 3449 | |||||
| 3450 | /// Are the AddrModes that we have all just equal to their original values? | ||||
| 3451 | bool AllAddrModesTrivial = true; | ||||
| 3452 | |||||
| 3453 | /// Common Type for all different fields in addressing modes. | ||||
| 3454 | Type *CommonType; | ||||
| 3455 | |||||
| 3456 | /// SimplifyQuery for simplifyInstruction utility. | ||||
| 3457 | const SimplifyQuery &SQ; | ||||
| 3458 | |||||
| 3459 | /// Original Address. | ||||
| 3460 | Value *Original; | ||||
| 3461 | |||||
| 3462 | public: | ||||
| 3463 | AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue) | ||||
| 3464 | : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {} | ||||
| 3465 | |||||
| 3466 | /// Get the combined AddrMode | ||||
| 3467 | const ExtAddrMode &getAddrMode() const { | ||||
| 3468 | return AddrModes[0]; | ||||
| 3469 | } | ||||
| 3470 | |||||
| 3471 | /// Add a new AddrMode if it's compatible with the AddrModes we already | ||||
| 3472 | /// have. | ||||
| 3473 | /// \return True iff we succeeded in doing so. | ||||
| 3474 | bool addNewAddrMode(ExtAddrMode &NewAddrMode) { | ||||
| 3475 | // Take note of if we have any non-trivial AddrModes, as we need to detect | ||||
| 3476 | // when all AddrModes are trivial as then we would introduce a phi or select | ||||
| 3477 | // which just duplicates what's already there. | ||||
| 3478 | AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial(); | ||||
| 3479 | |||||
| 3480 | // If this is the first addrmode then everything is fine. | ||||
| 3481 | if (AddrModes.empty()) { | ||||
| 3482 | AddrModes.emplace_back(NewAddrMode); | ||||
| 3483 | return true; | ||||
| 3484 | } | ||||
| 3485 | |||||
| 3486 | // Figure out how different this is from the other address modes, which we | ||||
| 3487 | // can do just by comparing against the first one given that we only care | ||||
| 3488 | // about the cumulative difference. | ||||
| 3489 | ExtAddrMode::FieldName ThisDifferentField = | ||||
| 3490 | AddrModes[0].compare(NewAddrMode); | ||||
| 3491 | if (DifferentField == ExtAddrMode::NoField) | ||||
| 3492 | DifferentField = ThisDifferentField; | ||||
| 3493 | else if (DifferentField != ThisDifferentField) | ||||
| 3494 | DifferentField = ExtAddrMode::MultipleFields; | ||||
| 3495 | |||||
| 3496 | // If NewAddrMode differs in more than one dimension we cannot handle it. | ||||
| 3497 | bool CanHandle = DifferentField != ExtAddrMode::MultipleFields; | ||||
| 3498 | |||||
| 3499 | // If Scale Field is different then we reject. | ||||
| 3500 | CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField; | ||||
| 3501 | |||||
| 3502 | // We also must reject the case when base offset is different and | ||||
| 3503 | // scale reg is not null, we cannot handle this case due to merge of | ||||
| 3504 | // different offsets will be used as ScaleReg. | ||||
| 3505 | CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField || | ||||
| 3506 | !NewAddrMode.ScaledReg); | ||||
| 3507 | |||||
| 3508 | // We also must reject the case when GV is different and BaseReg installed | ||||
| 3509 | // due to we want to use base reg as a merge of GV values. | ||||
| 3510 | CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField || | ||||
| 3511 | !NewAddrMode.HasBaseReg); | ||||
| 3512 | |||||
| 3513 | // Even if NewAddMode is the same we still need to collect it due to | ||||
| 3514 | // original value is different. And later we will need all original values | ||||
| 3515 | // as anchors during finding the common Phi node. | ||||
| 3516 | if (CanHandle) | ||||
| 3517 | AddrModes.emplace_back(NewAddrMode); | ||||
| 3518 | else | ||||
| 3519 | AddrModes.clear(); | ||||
| 3520 | |||||
| 3521 | return CanHandle; | ||||
| 3522 | } | ||||
| 3523 | |||||
| 3524 | /// Combine the addressing modes we've collected into a single | ||||
| 3525 | /// addressing mode. | ||||
| 3526 | /// \return True iff we successfully combined them or we only had one so | ||||
| 3527 | /// didn't need to combine them anyway. | ||||
| 3528 | bool combineAddrModes() { | ||||
| 3529 | // If we have no AddrModes then they can't be combined. | ||||
| 3530 | if (AddrModes.size() == 0) | ||||
| 3531 | return false; | ||||
| 3532 | |||||
| 3533 | // A single AddrMode can trivially be combined. | ||||
| 3534 | if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField) | ||||
| 3535 | return true; | ||||
| 3536 | |||||
| 3537 | // If the AddrModes we collected are all just equal to the value they are | ||||
| 3538 | // derived from then combining them wouldn't do anything useful. | ||||
| 3539 | if (AllAddrModesTrivial) | ||||
| 3540 | return false; | ||||
| 3541 | |||||
| 3542 | if (!addrModeCombiningAllowed()) | ||||
| 3543 | return false; | ||||
| 3544 | |||||
| 3545 | // Build a map between <original value, basic block where we saw it> to | ||||
| 3546 | // value of base register. | ||||
| 3547 | // Bail out if there is no common type. | ||||
| 3548 | FoldAddrToValueMapping Map; | ||||
| 3549 | if (!initializeMap(Map)) | ||||
| 3550 | return false; | ||||
| 3551 | |||||
| 3552 | Value *CommonValue = findCommon(Map); | ||||
| 3553 | if (CommonValue) | ||||
| 3554 | AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes); | ||||
| 3555 | return CommonValue != nullptr; | ||||
| 3556 | } | ||||
| 3557 | |||||
| 3558 | private: | ||||
| 3559 | /// Initialize Map with anchor values. For address seen | ||||
| 3560 | /// we set the value of different field saw in this address. | ||||
| 3561 | /// At the same time we find a common type for different field we will | ||||
| 3562 | /// use to create new Phi/Select nodes. Keep it in CommonType field. | ||||
| 3563 | /// Return false if there is no common type found. | ||||
| 3564 | bool initializeMap(FoldAddrToValueMapping &Map) { | ||||
| 3565 | // Keep track of keys where the value is null. We will need to replace it | ||||
| 3566 | // with constant null when we know the common type. | ||||
| 3567 | SmallVector<Value *, 2> NullValue; | ||||
| 3568 | Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType()); | ||||
| 3569 | for (auto &AM : AddrModes) { | ||||
| 3570 | Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy); | ||||
| 3571 | if (DV) { | ||||
| 3572 | auto *Type = DV->getType(); | ||||
| 3573 | if (CommonType && CommonType != Type) | ||||
| 3574 | return false; | ||||
| 3575 | CommonType = Type; | ||||
| 3576 | Map[AM.OriginalValue] = DV; | ||||
| 3577 | } else { | ||||
| 3578 | NullValue.push_back(AM.OriginalValue); | ||||
| 3579 | } | ||||
| 3580 | } | ||||
| 3581 | assert(CommonType && "At least one non-null value must be!")((void)0); | ||||
| 3582 | for (auto *V : NullValue) | ||||
| 3583 | Map[V] = Constant::getNullValue(CommonType); | ||||
| 3584 | return true; | ||||
| 3585 | } | ||||
| 3586 | |||||
| 3587 | /// We have mapping between value A and other value B where B was a field in | ||||
| 3588 | /// addressing mode represented by A. Also we have an original value C | ||||
| 3589 | /// representing an address we start with. Traversing from C through phi and | ||||
| 3590 | /// selects we ended up with A's in a map. This utility function tries to find | ||||
| 3591 | /// a value V which is a field in addressing mode C and traversing through phi | ||||
| 3592 | /// nodes and selects we will end up in corresponded values B in a map. | ||||
| 3593 | /// The utility will create a new Phi/Selects if needed. | ||||
| 3594 | // The simple example looks as follows: | ||||
| 3595 | // BB1: | ||||
| 3596 | // p1 = b1 + 40 | ||||
| 3597 | // br cond BB2, BB3 | ||||
| 3598 | // BB2: | ||||
| 3599 | // p2 = b2 + 40 | ||||
| 3600 | // br BB3 | ||||
| 3601 | // BB3: | ||||
| 3602 | // p = phi [p1, BB1], [p2, BB2] | ||||
| 3603 | // v = load p | ||||
| 3604 | // Map is | ||||
| 3605 | // p1 -> b1 | ||||
| 3606 | // p2 -> b2 | ||||
| 3607 | // Request is | ||||
| 3608 | // p -> ? | ||||
| 3609 | // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3. | ||||
| 3610 | Value *findCommon(FoldAddrToValueMapping &Map) { | ||||
| 3611 | // Tracks the simplification of newly created phi nodes. The reason we use | ||||
| 3612 | // this mapping is because we will add new created Phi nodes in AddrToBase. | ||||
| 3613 | // Simplification of Phi nodes is recursive, so some Phi node may | ||||
| 3614 | // be simplified after we added it to AddrToBase. In reality this | ||||
| 3615 | // simplification is possible only if original phi/selects were not | ||||
| 3616 | // simplified yet. | ||||
| 3617 | // Using this mapping we can find the current value in AddrToBase. | ||||
| 3618 | SimplificationTracker ST(SQ); | ||||
| 3619 | |||||
| 3620 | // First step, DFS to create PHI nodes for all intermediate blocks. | ||||
| 3621 | // Also fill traverse order for the second step. | ||||
| 3622 | SmallVector<Value *, 32> TraverseOrder; | ||||
| 3623 | InsertPlaceholders(Map, TraverseOrder, ST); | ||||
| 3624 | |||||
| 3625 | // Second Step, fill new nodes by merged values and simplify if possible. | ||||
| 3626 | FillPlaceholders(Map, TraverseOrder, ST); | ||||
| 3627 | |||||
| 3628 | if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) { | ||||
| 3629 | ST.destroyNewNodes(CommonType); | ||||
| 3630 | return nullptr; | ||||
| 3631 | } | ||||
| 3632 | |||||
| 3633 | // Now we'd like to match New Phi nodes to existed ones. | ||||
| 3634 | unsigned PhiNotMatchedCount = 0; | ||||
| 3635 | if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) { | ||||
| 3636 | ST.destroyNewNodes(CommonType); | ||||
| 3637 | return nullptr; | ||||
| 3638 | } | ||||
| 3639 | |||||
| 3640 | auto *Result = ST.Get(Map.find(Original)->second); | ||||
| 3641 | if (Result) { | ||||
| 3642 | NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount; | ||||
| 3643 | NumMemoryInstsSelectCreated += ST.countNewSelectNodes(); | ||||
| 3644 | } | ||||
| 3645 | return Result; | ||||
| 3646 | } | ||||
| 3647 | |||||
| 3648 | /// Try to match PHI node to Candidate. | ||||
| 3649 | /// Matcher tracks the matched Phi nodes. | ||||
| 3650 | bool MatchPhiNode(PHINode *PHI, PHINode *Candidate, | ||||
| 3651 | SmallSetVector<PHIPair, 8> &Matcher, | ||||
| 3652 | PhiNodeSet &PhiNodesToMatch) { | ||||
| 3653 | SmallVector<PHIPair, 8> WorkList; | ||||
| 3654 | Matcher.insert({ PHI, Candidate }); | ||||
| 3655 | SmallSet<PHINode *, 8> MatchedPHIs; | ||||
| 3656 | MatchedPHIs.insert(PHI); | ||||
| 3657 | WorkList.push_back({ PHI, Candidate }); | ||||
| 3658 | SmallSet<PHIPair, 8> Visited; | ||||
| 3659 | while (!WorkList.empty()) { | ||||
| 3660 | auto Item = WorkList.pop_back_val(); | ||||
| 3661 | if (!Visited.insert(Item).second) | ||||
| 3662 | continue; | ||||
| 3663 | // We iterate over all incoming values to Phi to compare them. | ||||
| 3664 | // If values are different and both of them Phi and the first one is a | ||||
| 3665 | // Phi we added (subject to match) and both of them is in the same basic | ||||
| 3666 | // block then we can match our pair if values match. So we state that | ||||
| 3667 | // these values match and add it to work list to verify that. | ||||
| 3668 | for (auto B : Item.first->blocks()) { | ||||
| 3669 | Value *FirstValue = Item.first->getIncomingValueForBlock(B); | ||||
| 3670 | Value *SecondValue = Item.second->getIncomingValueForBlock(B); | ||||
| 3671 | if (FirstValue == SecondValue) | ||||
| 3672 | continue; | ||||
| 3673 | |||||
| 3674 | PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue); | ||||
| 3675 | PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue); | ||||
| 3676 | |||||
| 3677 | // One of them is not Phi or | ||||
| 3678 | // The first one is not Phi node from the set we'd like to match or | ||||
| 3679 | // Phi nodes from different basic blocks then | ||||
| 3680 | // we will not be able to match. | ||||
| 3681 | if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) || | ||||
| 3682 | FirstPhi->getParent() != SecondPhi->getParent()) | ||||
| 3683 | return false; | ||||
| 3684 | |||||
| 3685 | // If we already matched them then continue. | ||||
| 3686 | if (Matcher.count({ FirstPhi, SecondPhi })) | ||||
| 3687 | continue; | ||||
| 3688 | // So the values are different and does not match. So we need them to | ||||
| 3689 | // match. (But we register no more than one match per PHI node, so that | ||||
| 3690 | // we won't later try to replace them twice.) | ||||
| 3691 | if (MatchedPHIs.insert(FirstPhi).second) | ||||
| 3692 | Matcher.insert({ FirstPhi, SecondPhi }); | ||||
| 3693 | // But me must check it. | ||||
| 3694 | WorkList.push_back({ FirstPhi, SecondPhi }); | ||||
| 3695 | } | ||||
| 3696 | } | ||||
| 3697 | return true; | ||||
| 3698 | } | ||||
| 3699 | |||||
| 3700 | /// For the given set of PHI nodes (in the SimplificationTracker) try | ||||
| 3701 | /// to find their equivalents. | ||||
| 3702 | /// Returns false if this matching fails and creation of new Phi is disabled. | ||||
| 3703 | bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes, | ||||
| 3704 | unsigned &PhiNotMatchedCount) { | ||||
| 3705 | // Matched and PhiNodesToMatch iterate their elements in a deterministic | ||||
| 3706 | // order, so the replacements (ReplacePhi) are also done in a deterministic | ||||
| 3707 | // order. | ||||
| 3708 | SmallSetVector<PHIPair, 8> Matched; | ||||
| 3709 | SmallPtrSet<PHINode *, 8> WillNotMatch; | ||||
| 3710 | PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes(); | ||||
| 3711 | while (PhiNodesToMatch.size()) { | ||||
| 3712 | PHINode *PHI = *PhiNodesToMatch.begin(); | ||||
| 3713 | |||||
| 3714 | // Add us, if no Phi nodes in the basic block we do not match. | ||||
| 3715 | WillNotMatch.clear(); | ||||
| 3716 | WillNotMatch.insert(PHI); | ||||
| 3717 | |||||
| 3718 | // Traverse all Phis until we found equivalent or fail to do that. | ||||
| 3719 | bool IsMatched = false; | ||||
| 3720 | for (auto &P : PHI->getParent()->phis()) { | ||||
| 3721 | if (&P == PHI) | ||||
| 3722 | continue; | ||||
| 3723 | if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch))) | ||||
| 3724 | break; | ||||
| 3725 | // If it does not match, collect all Phi nodes from matcher. | ||||
| 3726 | // if we end up with no match, them all these Phi nodes will not match | ||||
| 3727 | // later. | ||||
| 3728 | for (auto M : Matched) | ||||
| 3729 | WillNotMatch.insert(M.first); | ||||
| 3730 | Matched.clear(); | ||||
| 3731 | } | ||||
| 3732 | if (IsMatched) { | ||||
| 3733 | // Replace all matched values and erase them. | ||||
| 3734 | for (auto MV : Matched) | ||||
| 3735 | ST.ReplacePhi(MV.first, MV.second); | ||||
| 3736 | Matched.clear(); | ||||
| 3737 | continue; | ||||
| 3738 | } | ||||
| 3739 | // If we are not allowed to create new nodes then bail out. | ||||
| 3740 | if (!AllowNewPhiNodes) | ||||
| 3741 | return false; | ||||
| 3742 | // Just remove all seen values in matcher. They will not match anything. | ||||
| 3743 | PhiNotMatchedCount += WillNotMatch.size(); | ||||
| 3744 | for (auto *P : WillNotMatch) | ||||
| 3745 | PhiNodesToMatch.erase(P); | ||||
| 3746 | } | ||||
| 3747 | return true; | ||||
| 3748 | } | ||||
| 3749 | /// Fill the placeholders with values from predecessors and simplify them. | ||||
| 3750 | void FillPlaceholders(FoldAddrToValueMapping &Map, | ||||
| 3751 | SmallVectorImpl<Value *> &TraverseOrder, | ||||
| 3752 | SimplificationTracker &ST) { | ||||
| 3753 | while (!TraverseOrder.empty()) { | ||||
| 3754 | Value *Current = TraverseOrder.pop_back_val(); | ||||
| 3755 | assert(Map.find(Current) != Map.end() && "No node to fill!!!")((void)0); | ||||
| 3756 | Value *V = Map[Current]; | ||||
| 3757 | |||||
| 3758 | if (SelectInst *Select = dyn_cast<SelectInst>(V)) { | ||||
| 3759 | // CurrentValue also must be Select. | ||||
| 3760 | auto *CurrentSelect = cast<SelectInst>(Current); | ||||
| 3761 | auto *TrueValue = CurrentSelect->getTrueValue(); | ||||
| 3762 | assert(Map.find(TrueValue) != Map.end() && "No True Value!")((void)0); | ||||
| 3763 | Select->setTrueValue(ST.Get(Map[TrueValue])); | ||||
| 3764 | auto *FalseValue = CurrentSelect->getFalseValue(); | ||||
| 3765 | assert(Map.find(FalseValue) != Map.end() && "No False Value!")((void)0); | ||||
| 3766 | Select->setFalseValue(ST.Get(Map[FalseValue])); | ||||
| 3767 | } else { | ||||
| 3768 | // Must be a Phi node then. | ||||
| 3769 | auto *PHI = cast<PHINode>(V); | ||||
| 3770 | // Fill the Phi node with values from predecessors. | ||||
| 3771 | for (auto *B : predecessors(PHI->getParent())) { | ||||
| 3772 | Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B); | ||||
| 3773 | assert(Map.find(PV) != Map.end() && "No predecessor Value!")((void)0); | ||||
| 3774 | PHI->addIncoming(ST.Get(Map[PV]), B); | ||||
| 3775 | } | ||||
| 3776 | } | ||||
| 3777 | Map[Current] = ST.Simplify(V); | ||||
| 3778 | } | ||||
| 3779 | } | ||||
| 3780 | |||||
| 3781 | /// Starting from original value recursively iterates over def-use chain up to | ||||
| 3782 | /// known ending values represented in a map. For each traversed phi/select | ||||
| 3783 | /// inserts a placeholder Phi or Select. | ||||
| 3784 | /// Reports all new created Phi/Select nodes by adding them to set. | ||||
| 3785 | /// Also reports and order in what values have been traversed. | ||||
| 3786 | void InsertPlaceholders(FoldAddrToValueMapping &Map, | ||||
| 3787 | SmallVectorImpl<Value *> &TraverseOrder, | ||||
| 3788 | SimplificationTracker &ST) { | ||||
| 3789 | SmallVector<Value *, 32> Worklist; | ||||
| 3790 | assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&((void)0) | ||||
| 3791 | "Address must be a Phi or Select node")((void)0); | ||||
| 3792 | auto *Dummy = UndefValue::get(CommonType); | ||||
| 3793 | Worklist.push_back(Original); | ||||
| 3794 | while (!Worklist.empty()) { | ||||
| 3795 | Value *Current = Worklist.pop_back_val(); | ||||
| 3796 | // if it is already visited or it is an ending value then skip it. | ||||
| 3797 | if (Map.find(Current) != Map.end()) | ||||
| 3798 | continue; | ||||
| 3799 | TraverseOrder.push_back(Current); | ||||
| 3800 | |||||
| 3801 | // CurrentValue must be a Phi node or select. All others must be covered | ||||
| 3802 | // by anchors. | ||||
| 3803 | if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) { | ||||
| 3804 | // Is it OK to get metadata from OrigSelect?! | ||||
| 3805 | // Create a Select placeholder with dummy value. | ||||
| 3806 | SelectInst *Select = SelectInst::Create( | ||||
| 3807 | CurrentSelect->getCondition(), Dummy, Dummy, | ||||
| 3808 | CurrentSelect->getName(), CurrentSelect, CurrentSelect); | ||||
| 3809 | Map[Current] = Select; | ||||
| 3810 | ST.insertNewSelect(Select); | ||||
| 3811 | // We are interested in True and False values. | ||||
| 3812 | Worklist.push_back(CurrentSelect->getTrueValue()); | ||||
| 3813 | Worklist.push_back(CurrentSelect->getFalseValue()); | ||||
| 3814 | } else { | ||||
| 3815 | // It must be a Phi node then. | ||||
| 3816 | PHINode *CurrentPhi = cast<PHINode>(Current); | ||||
| 3817 | unsigned PredCount = CurrentPhi->getNumIncomingValues(); | ||||
| 3818 | PHINode *PHI = | ||||
| 3819 | PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi); | ||||
| 3820 | Map[Current] = PHI; | ||||
| 3821 | ST.insertNewPhi(PHI); | ||||
| 3822 | append_range(Worklist, CurrentPhi->incoming_values()); | ||||
| 3823 | } | ||||
| 3824 | } | ||||
| 3825 | } | ||||
| 3826 | |||||
| 3827 | bool addrModeCombiningAllowed() { | ||||
| 3828 | if (DisableComplexAddrModes) | ||||
| 3829 | return false; | ||||
| 3830 | switch (DifferentField) { | ||||
| 3831 | default: | ||||
| 3832 | return false; | ||||
| 3833 | case ExtAddrMode::BaseRegField: | ||||
| 3834 | return AddrSinkCombineBaseReg; | ||||
| 3835 | case ExtAddrMode::BaseGVField: | ||||
| 3836 | return AddrSinkCombineBaseGV; | ||||
| 3837 | case ExtAddrMode::BaseOffsField: | ||||
| 3838 | return AddrSinkCombineBaseOffs; | ||||
| 3839 | case ExtAddrMode::ScaledRegField: | ||||
| 3840 | return AddrSinkCombineScaledReg; | ||||
| 3841 | } | ||||
| 3842 | } | ||||
| 3843 | }; | ||||
| 3844 | } // end anonymous namespace | ||||
| 3845 | |||||
| 3846 | /// Try adding ScaleReg*Scale to the current addressing mode. | ||||
| 3847 | /// Return true and update AddrMode if this addr mode is legal for the target, | ||||
| 3848 | /// false if not. | ||||
| 3849 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, | ||||
| 3850 | unsigned Depth) { | ||||
| 3851 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing | ||||
| 3852 | // mode. Just process that directly. | ||||
| 3853 | if (Scale == 1) | ||||
| 3854 | return matchAddr(ScaleReg, Depth); | ||||
| 3855 | |||||
| 3856 | // If the scale is 0, it takes nothing to add this. | ||||
| 3857 | if (Scale == 0) | ||||
| 3858 | return true; | ||||
| 3859 | |||||
| 3860 | // If we already have a scale of this value, we can add to it, otherwise, we | ||||
| 3861 | // need an available scale field. | ||||
| 3862 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) | ||||
| 3863 | return false; | ||||
| 3864 | |||||
| 3865 | ExtAddrMode TestAddrMode = AddrMode; | ||||
| 3866 | |||||
| 3867 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like | ||||
| 3868 | // [A+B + A*7] -> [B+A*8]. | ||||
| 3869 | TestAddrMode.Scale += Scale; | ||||
| 3870 | TestAddrMode.ScaledReg = ScaleReg; | ||||
| 3871 | |||||
| 3872 | // If the new address isn't legal, bail out. | ||||
| 3873 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) | ||||
| 3874 | return false; | ||||
| 3875 | |||||
| 3876 | // It was legal, so commit it. | ||||
| 3877 | AddrMode = TestAddrMode; | ||||
| 3878 | |||||
| 3879 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now | ||||
| 3880 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding | ||||
| 3881 | // X*Scale + C*Scale to addr mode. If we found available IV increment, do not | ||||
| 3882 | // go any further: we can reuse it and cannot eliminate it. | ||||
| 3883 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; | ||||
| 3884 | if (isa<Instruction>(ScaleReg) && // not a constant expr. | ||||
| 3885 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) && | ||||
| 3886 | !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) { | ||||
| 3887 | TestAddrMode.InBounds = false; | ||||
| 3888 | TestAddrMode.ScaledReg = AddLHS; | ||||
| 3889 | TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale; | ||||
| 3890 | |||||
| 3891 | // If this addressing mode is legal, commit it and remember that we folded | ||||
| 3892 | // this instruction. | ||||
| 3893 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { | ||||
| 3894 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); | ||||
| 3895 | AddrMode = TestAddrMode; | ||||
| 3896 | return true; | ||||
| 3897 | } | ||||
| 3898 | // Restore status quo. | ||||
| 3899 | TestAddrMode = AddrMode; | ||||
| 3900 | } | ||||
| 3901 | |||||
| 3902 | // If this is an add recurrence with a constant step, return the increment | ||||
| 3903 | // instruction and the canonicalized step. | ||||
| 3904 | auto GetConstantStep = [this](const Value * V) | ||||
| 3905 | ->Optional<std::pair<Instruction *, APInt> > { | ||||
| 3906 | auto *PN = dyn_cast<PHINode>(V); | ||||
| 3907 | if (!PN) | ||||
| 3908 | return None; | ||||
| 3909 | auto IVInc = getIVIncrement(PN, &LI); | ||||
| 3910 | if (!IVInc) | ||||
| 3911 | return None; | ||||
| 3912 | // TODO: The result of the intrinsics above is two-compliment. However when | ||||
| 3913 | // IV inc is expressed as add or sub, iv.next is potentially a poison value. | ||||
| 3914 | // If it has nuw or nsw flags, we need to make sure that these flags are | ||||
| 3915 | // inferrable at the point of memory instruction. Otherwise we are replacing | ||||
| 3916 | // well-defined two-compliment computation with poison. Currently, to avoid | ||||
| 3917 | // potentially complex analysis needed to prove this, we reject such cases. | ||||
| 3918 | if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first)) | ||||
| 3919 | if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap()) | ||||
| 3920 | return None; | ||||
| 3921 | if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second)) | ||||
| 3922 | return std::make_pair(IVInc->first, ConstantStep->getValue()); | ||||
| 3923 | return None; | ||||
| 3924 | }; | ||||
| 3925 | |||||
| 3926 | // Try to account for the following special case: | ||||
| 3927 | // 1. ScaleReg is an inductive variable; | ||||
| 3928 | // 2. We use it with non-zero offset; | ||||
| 3929 | // 3. IV's increment is available at the point of memory instruction. | ||||
| 3930 | // | ||||
| 3931 | // In this case, we may reuse the IV increment instead of the IV Phi to | ||||
| 3932 | // achieve the following advantages: | ||||
| 3933 | // 1. If IV step matches the offset, we will have no need in the offset; | ||||
| 3934 | // 2. Even if they don't match, we will reduce the overlap of living IV | ||||
| 3935 | // and IV increment, that will potentially lead to better register | ||||
| 3936 | // assignment. | ||||
| 3937 | if (AddrMode.BaseOffs) { | ||||
| 3938 | if (auto IVStep = GetConstantStep(ScaleReg)) { | ||||
| 3939 | Instruction *IVInc = IVStep->first; | ||||
| 3940 | // The following assert is important to ensure a lack of infinite loops. | ||||
| 3941 | // This transforms is (intentionally) the inverse of the one just above. | ||||
| 3942 | // If they don't agree on the definition of an increment, we'd alternate | ||||
| 3943 | // back and forth indefinitely. | ||||
| 3944 | assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep")((void)0); | ||||
| 3945 | APInt Step = IVStep->second; | ||||
| 3946 | APInt Offset = Step * AddrMode.Scale; | ||||
| 3947 | if (Offset.isSignedIntN(64)) { | ||||
| 3948 | TestAddrMode.InBounds = false; | ||||
| 3949 | TestAddrMode.ScaledReg = IVInc; | ||||
| 3950 | TestAddrMode.BaseOffs -= Offset.getLimitedValue(); | ||||
| 3951 | // If this addressing mode is legal, commit it.. | ||||
| 3952 | // (Note that we defer the (expensive) domtree base legality check | ||||
| 3953 | // to the very last possible point.) | ||||
| 3954 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) && | ||||
| 3955 | getDTFn().dominates(IVInc, MemoryInst)) { | ||||
| 3956 | AddrModeInsts.push_back(cast<Instruction>(IVInc)); | ||||
| 3957 | AddrMode = TestAddrMode; | ||||
| 3958 | return true; | ||||
| 3959 | } | ||||
| 3960 | // Restore status quo. | ||||
| 3961 | TestAddrMode = AddrMode; | ||||
| 3962 | } | ||||
| 3963 | } | ||||
| 3964 | } | ||||
| 3965 | |||||
| 3966 | // Otherwise, just return what we have. | ||||
| 3967 | return true; | ||||
| 3968 | } | ||||
| 3969 | |||||
| 3970 | /// This is a little filter, which returns true if an addressing computation | ||||
| 3971 | /// involving I might be folded into a load/store accessing it. | ||||
| 3972 | /// This doesn't need to be perfect, but needs to accept at least | ||||
| 3973 | /// the set of instructions that MatchOperationAddr can. | ||||
| 3974 | static bool MightBeFoldableInst(Instruction *I) { | ||||
| 3975 | switch (I->getOpcode()) { | ||||
| 3976 | case Instruction::BitCast: | ||||
| 3977 | case Instruction::AddrSpaceCast: | ||||
| 3978 | // Don't touch identity bitcasts. | ||||
| 3979 | if (I->getType() == I->getOperand(0)->getType()) | ||||
| 3980 | return false; | ||||
| 3981 | return I->getType()->isIntOrPtrTy(); | ||||
| 3982 | case Instruction::PtrToInt: | ||||
| 3983 | // PtrToInt is always a noop, as we know that the int type is pointer sized. | ||||
| 3984 | return true; | ||||
| 3985 | case Instruction::IntToPtr: | ||||
| 3986 | // We know the input is intptr_t, so this is foldable. | ||||
| 3987 | return true; | ||||
| 3988 | case Instruction::Add: | ||||
| 3989 | return true; | ||||
| 3990 | case Instruction::Mul: | ||||
| 3991 | case Instruction::Shl: | ||||
| 3992 | // Can only handle X*C and X << C. | ||||
| 3993 | return isa<ConstantInt>(I->getOperand(1)); | ||||
| 3994 | case Instruction::GetElementPtr: | ||||
| 3995 | return true; | ||||
| 3996 | default: | ||||
| 3997 | return false; | ||||
| 3998 | } | ||||
| 3999 | } | ||||
| 4000 | |||||
| 4001 | /// Check whether or not \p Val is a legal instruction for \p TLI. | ||||
| 4002 | /// \note \p Val is assumed to be the product of some type promotion. | ||||
| 4003 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed | ||||
| 4004 | /// to be legal, as the non-promoted value would have had the same state. | ||||
| 4005 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, | ||||
| 4006 | const DataLayout &DL, Value *Val) { | ||||
| 4007 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); | ||||
| 4008 | if (!PromotedInst) | ||||
| 4009 | return false; | ||||
| 4010 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); | ||||
| 4011 | // If the ISDOpcode is undefined, it was undefined before the promotion. | ||||
| 4012 | if (!ISDOpcode) | ||||
| 4013 | return true; | ||||
| 4014 | // Otherwise, check if the promoted instruction is legal or not. | ||||
| 4015 | return TLI.isOperationLegalOrCustom( | ||||
| 4016 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); | ||||
| 4017 | } | ||||
| 4018 | |||||
| 4019 | namespace { | ||||
| 4020 | |||||
| 4021 | /// Hepler class to perform type promotion. | ||||
| 4022 | class TypePromotionHelper { | ||||
| 4023 | /// Utility function to add a promoted instruction \p ExtOpnd to | ||||
| 4024 | /// \p PromotedInsts and record the type of extension we have seen. | ||||
| 4025 | static void addPromotedInst(InstrToOrigTy &PromotedInsts, | ||||
| 4026 | Instruction *ExtOpnd, | ||||
| 4027 | bool IsSExt) { | ||||
| 4028 | ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; | ||||
| 4029 | InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd); | ||||
| 4030 | if (It != PromotedInsts.end()) { | ||||
| 4031 | // If the new extension is same as original, the information in | ||||
| 4032 | // PromotedInsts[ExtOpnd] is still correct. | ||||
| 4033 | if (It->second.getInt() == ExtTy) | ||||
| 4034 | return; | ||||
| 4035 | |||||
| 4036 | // Now the new extension is different from old extension, we make | ||||
| 4037 | // the type information invalid by setting extension type to | ||||
| 4038 | // BothExtension. | ||||
| 4039 | ExtTy = BothExtension; | ||||
| 4040 | } | ||||
| 4041 | PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy); | ||||
| 4042 | } | ||||
| 4043 | |||||
| 4044 | /// Utility function to query the original type of instruction \p Opnd | ||||
| 4045 | /// with a matched extension type. If the extension doesn't match, we | ||||
| 4046 | /// cannot use the information we had on the original type. | ||||
| 4047 | /// BothExtension doesn't match any extension type. | ||||
| 4048 | static const Type *getOrigType(const InstrToOrigTy &PromotedInsts, | ||||
| 4049 | Instruction *Opnd, | ||||
| 4050 | bool IsSExt) { | ||||
| 4051 | ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; | ||||
| 4052 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); | ||||
| 4053 | if (It != PromotedInsts.end() && It->second.getInt() == ExtTy) | ||||
| 4054 | return It->second.getPointer(); | ||||
| 4055 | return nullptr; | ||||
| 4056 | } | ||||
| 4057 | |||||
| 4058 | /// Utility function to check whether or not a sign or zero extension | ||||
| 4059 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by | ||||
| 4060 | /// either using the operands of \p Inst or promoting \p Inst. | ||||
| 4061 | /// The type of the extension is defined by \p IsSExt. | ||||
| 4062 | /// In other words, check if: | ||||
| 4063 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. | ||||
| 4064 | /// #1 Promotion applies: | ||||
| 4065 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). | ||||
| 4066 | /// #2 Operand reuses: | ||||
| 4067 | /// ext opnd1 to ConsideredExtType. | ||||
| 4068 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
| 4069 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, | ||||
| 4070 | const InstrToOrigTy &PromotedInsts, bool IsSExt); | ||||
| 4071 | |||||
| 4072 | /// Utility function to determine if \p OpIdx should be promoted when | ||||
| 4073 | /// promoting \p Inst. | ||||
| 4074 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { | ||||
| 4075 | return !(isa<SelectInst>(Inst) && OpIdx == 0); | ||||
| 4076 | } | ||||
| 4077 | |||||
| 4078 | /// Utility function to promote the operand of \p Ext when this | ||||
| 4079 | /// operand is a promotable trunc or sext or zext. | ||||
| 4080 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
| 4081 | /// \p CreatedInstsCost[out] contains the cost of all instructions | ||||
| 4082 | /// created to promote the operand of Ext. | ||||
| 4083 | /// Newly added extensions are inserted in \p Exts. | ||||
| 4084 | /// Newly added truncates are inserted in \p Truncs. | ||||
| 4085 | /// Should never be called directly. | ||||
| 4086 | /// \return The promoted value which is used instead of Ext. | ||||
| 4087 | static Value *promoteOperandForTruncAndAnyExt( | ||||
| 4088 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
| 4089 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
| 4090 | SmallVectorImpl<Instruction *> *Exts, | ||||
| 4091 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); | ||||
| 4092 | |||||
| 4093 | /// Utility function to promote the operand of \p Ext when this | ||||
| 4094 | /// operand is promotable and is not a supported trunc or sext. | ||||
| 4095 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
| 4096 | /// \p CreatedInstsCost[out] contains the cost of all the instructions | ||||
| 4097 | /// created to promote the operand of Ext. | ||||
| 4098 | /// Newly added extensions are inserted in \p Exts. | ||||
| 4099 | /// Newly added truncates are inserted in \p Truncs. | ||||
| 4100 | /// Should never be called directly. | ||||
| 4101 | /// \return The promoted value which is used instead of Ext. | ||||
| 4102 | static Value *promoteOperandForOther(Instruction *Ext, | ||||
| 4103 | TypePromotionTransaction &TPT, | ||||
| 4104 | InstrToOrigTy &PromotedInsts, | ||||
| 4105 | unsigned &CreatedInstsCost, | ||||
| 4106 | SmallVectorImpl<Instruction *> *Exts, | ||||
| 4107 | SmallVectorImpl<Instruction *> *Truncs, | ||||
| 4108 | const TargetLowering &TLI, bool IsSExt); | ||||
| 4109 | |||||
| 4110 | /// \see promoteOperandForOther. | ||||
| 4111 | static Value *signExtendOperandForOther( | ||||
| 4112 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
| 4113 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
| 4114 | SmallVectorImpl<Instruction *> *Exts, | ||||
| 4115 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { | ||||
| 4116 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, | ||||
| 4117 | Exts, Truncs, TLI, true); | ||||
| 4118 | } | ||||
| 4119 | |||||
| 4120 | /// \see promoteOperandForOther. | ||||
| 4121 | static Value *zeroExtendOperandForOther( | ||||
| 4122 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
| 4123 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
| 4124 | SmallVectorImpl<Instruction *> *Exts, | ||||
| 4125 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { | ||||
| 4126 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, | ||||
| 4127 | Exts, Truncs, TLI, false); | ||||
| 4128 | } | ||||
| 4129 | |||||
| 4130 | public: | ||||
| 4131 | /// Type for the utility function that promotes the operand of Ext. | ||||
| 4132 | using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT, | ||||
| 4133 | InstrToOrigTy &PromotedInsts, | ||||
| 4134 | unsigned &CreatedInstsCost, | ||||
| 4135 | SmallVectorImpl<Instruction *> *Exts, | ||||
| 4136 | SmallVectorImpl<Instruction *> *Truncs, | ||||
| 4137 | const TargetLowering &TLI); | ||||
| 4138 | |||||
| 4139 | /// Given a sign/zero extend instruction \p Ext, return the appropriate | ||||
| 4140 | /// action to promote the operand of \p Ext instead of using Ext. | ||||
| 4141 | /// \return NULL if no promotable action is possible with the current | ||||
| 4142 | /// sign extension. | ||||
| 4143 | /// \p InsertedInsts keeps track of all the instructions inserted by the | ||||
| 4144 | /// other CodeGenPrepare optimizations. This information is important | ||||
| 4145 | /// because we do not want to promote these instructions as CodeGenPrepare | ||||
| 4146 | /// will reinsert them later. Thus creating an infinite loop: create/remove. | ||||
| 4147 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
| 4148 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, | ||||
| 4149 | const TargetLowering &TLI, | ||||
| 4150 | const InstrToOrigTy &PromotedInsts); | ||||
| 4151 | }; | ||||
| 4152 | |||||
| 4153 | } // end anonymous namespace | ||||
| 4154 | |||||
| 4155 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, | ||||
| 4156 | Type *ConsideredExtType, | ||||
| 4157 | const InstrToOrigTy &PromotedInsts, | ||||
| 4158 | bool IsSExt) { | ||||
| 4159 | // The promotion helper does not know how to deal with vector types yet. | ||||
| 4160 | // To be able to fix that, we would need to fix the places where we | ||||
| 4161 | // statically extend, e.g., constants and such. | ||||
| 4162 | if (Inst->getType()->isVectorTy()) | ||||
| 4163 | return false; | ||||
| 4164 | |||||
| 4165 | // We can always get through zext. | ||||
| 4166 | if (isa<ZExtInst>(Inst)) | ||||
| 4167 | return true; | ||||
| 4168 | |||||
| 4169 | // sext(sext) is ok too. | ||||
| 4170 | if (IsSExt && isa<SExtInst>(Inst)) | ||||
| 4171 | return true; | ||||
| 4172 | |||||
| 4173 | // We can get through binary operator, if it is legal. In other words, the | ||||
| 4174 | // binary operator must have a nuw or nsw flag. | ||||
| 4175 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); | ||||
| 4176 | if (isa_and_nonnull<OverflowingBinaryOperator>(BinOp) && | ||||
| 4177 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || | ||||
| 4178 | (IsSExt && BinOp->hasNoSignedWrap()))) | ||||
| 4179 | return true; | ||||
| 4180 | |||||
| 4181 | // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst)) | ||||
| 4182 | if ((Inst->getOpcode() == Instruction::And || | ||||
| 4183 | Inst->getOpcode() == Instruction::Or)) | ||||
| 4184 | return true; | ||||
| 4185 | |||||
| 4186 | // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst)) | ||||
| 4187 | if (Inst->getOpcode() == Instruction::Xor) { | ||||
| 4188 | const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)); | ||||
| 4189 | // Make sure it is not a NOT. | ||||
| 4190 | if (Cst && !Cst->getValue().isAllOnesValue()) | ||||
| 4191 | return true; | ||||
| 4192 | } | ||||
| 4193 | |||||
| 4194 | // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst)) | ||||
| 4195 | // It may change a poisoned value into a regular value, like | ||||
| 4196 | // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12 | ||||
| 4197 | // poisoned value regular value | ||||
| 4198 | // It should be OK since undef covers valid value. | ||||
| 4199 | if (Inst->getOpcode() == Instruction::LShr && !IsSExt) | ||||
| 4200 | return true; | ||||
| 4201 | |||||
| 4202 | // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst) | ||||
| 4203 | // It may change a poisoned value into a regular value, like | ||||
| 4204 | // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12 | ||||
| 4205 | // poisoned value regular value | ||||
| 4206 | // It should be OK since undef covers valid value. | ||||
| 4207 | if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) { | ||||
| 4208 | const auto *ExtInst = cast<const Instruction>(*Inst->user_begin()); | ||||
| 4209 | if (ExtInst->hasOneUse()) { | ||||
| 4210 | const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin()); | ||||
| 4211 | if (AndInst && AndInst->getOpcode() == Instruction::And) { | ||||
| 4212 | const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1)); | ||||
| 4213 | if (Cst && | ||||
| 4214 | Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth())) | ||||
| 4215 | return true; | ||||
| 4216 | } | ||||
| 4217 | } | ||||
| 4218 | } | ||||
| 4219 | |||||
| 4220 | // Check if we can do the following simplification. | ||||
| 4221 | // ext(trunc(opnd)) --> ext(opnd) | ||||
| 4222 | if (!isa<TruncInst>(Inst)) | ||||
| 4223 | return false; | ||||
| 4224 | |||||
| 4225 | Value *OpndVal = Inst->getOperand(0); | ||||
| 4226 | // Check if we can use this operand in the extension. | ||||
| 4227 | // If the type is larger than the result type of the extension, we cannot. | ||||
| 4228 | if (!OpndVal->getType()->isIntegerTy() || | ||||
| 4229 | OpndVal->getType()->getIntegerBitWidth() > | ||||
| 4230 | ConsideredExtType->getIntegerBitWidth()) | ||||
| 4231 | return false; | ||||
| 4232 | |||||
| 4233 | // If the operand of the truncate is not an instruction, we will not have | ||||
| 4234 | // any information on the dropped bits. | ||||
| 4235 | // (Actually we could for constant but it is not worth the extra logic). | ||||
| 4236 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); | ||||
| 4237 | if (!Opnd) | ||||
| 4238 | return false; | ||||
| 4239 | |||||
| 4240 | // Check if the source of the type is narrow enough. | ||||
| 4241 | // I.e., check that trunc just drops extended bits of the same kind of | ||||
| 4242 | // the extension. | ||||
| 4243 | // #1 get the type of the operand and check the kind of the extended bits. | ||||
| 4244 | const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt); | ||||
| 4245 | if (OpndType) | ||||
| 4246 | ; | ||||
| 4247 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) | ||||
| 4248 | OpndType = Opnd->getOperand(0)->getType(); | ||||
| 4249 | else | ||||
| 4250 | return false; | ||||
| 4251 | |||||
| 4252 | // #2 check that the truncate just drops extended bits. | ||||
| 4253 | return Inst->getType()->getIntegerBitWidth() >= | ||||
| 4254 | OpndType->getIntegerBitWidth(); | ||||
| 4255 | } | ||||
| 4256 | |||||
| 4257 | TypePromotionHelper::Action TypePromotionHelper::getAction( | ||||
| 4258 | Instruction *Ext, const SetOfInstrs &InsertedInsts, | ||||
| 4259 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { | ||||
| 4260 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&((void)0) | ||||
| 4261 | "Unexpected instruction type")((void)0); | ||||
| 4262 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); | ||||
| 4263 | Type *ExtTy = Ext->getType(); | ||||
| 4264 | bool IsSExt = isa<SExtInst>(Ext); | ||||
| 4265 | // If the operand of the extension is not an instruction, we cannot | ||||
| 4266 | // get through. | ||||
| 4267 | // If it, check we can get through. | ||||
| 4268 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) | ||||
| 4269 | return nullptr; | ||||
| 4270 | |||||
| 4271 | // Do not promote if the operand has been added by codegenprepare. | ||||
| 4272 | // Otherwise, it means we are undoing an optimization that is likely to be | ||||
| 4273 | // redone, thus causing potential infinite loop. | ||||
| 4274 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) | ||||
| 4275 | return nullptr; | ||||
| 4276 | |||||
| 4277 | // SExt or Trunc instructions. | ||||
| 4278 | // Return the related handler. | ||||
| 4279 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || | ||||
| 4280 | isa<ZExtInst>(ExtOpnd)) | ||||
| 4281 | return promoteOperandForTruncAndAnyExt; | ||||
| 4282 | |||||
| 4283 | // Regular instruction. | ||||
| 4284 | // Abort early if we will have to insert non-free instructions. | ||||
| 4285 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) | ||||
| 4286 | return nullptr; | ||||
| 4287 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; | ||||
| 4288 | } | ||||
| 4289 | |||||
| 4290 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( | ||||
| 4291 | Instruction *SExt, TypePromotionTransaction &TPT, | ||||
| 4292 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
| 4293 | SmallVectorImpl<Instruction *> *Exts, | ||||
| 4294 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { | ||||
| 4295 | // By construction, the operand of SExt is an instruction. Otherwise we cannot | ||||
| 4296 | // get through it and this method should not be called. | ||||
| 4297 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); | ||||
| 4298 | Value *ExtVal = SExt; | ||||
| 4299 | bool HasMergedNonFreeExt = false; | ||||
| 4300 | if (isa<ZExtInst>(SExtOpnd)) { | ||||
| 4301 | // Replace s|zext(zext(opnd)) | ||||
| 4302 | // => zext(opnd). | ||||
| 4303 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); | ||||
| 4304 | Value *ZExt = | ||||
| 4305 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); | ||||
| 4306 | TPT.replaceAllUsesWith(SExt, ZExt); | ||||
| 4307 | TPT.eraseInstruction(SExt); | ||||
| 4308 | ExtVal = ZExt; | ||||
| 4309 | } else { | ||||
| 4310 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) | ||||
| 4311 | // => z|sext(opnd). | ||||
| 4312 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); | ||||
| 4313 | } | ||||
| 4314 | CreatedInstsCost = 0; | ||||
| 4315 | |||||
| 4316 | // Remove dead code. | ||||
| 4317 | if (SExtOpnd->use_empty()) | ||||
| 4318 | TPT.eraseInstruction(SExtOpnd); | ||||
| 4319 | |||||
| 4320 | // Check if the extension is still needed. | ||||
| 4321 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); | ||||
| 4322 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { | ||||
| 4323 | if (ExtInst) { | ||||
| 4324 | if (Exts) | ||||
| 4325 | Exts->push_back(ExtInst); | ||||
| 4326 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; | ||||
| 4327 | } | ||||
| 4328 | return ExtVal; | ||||
| 4329 | } | ||||
| 4330 | |||||
| 4331 | // At this point we have: ext ty opnd to ty. | ||||
| 4332 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. | ||||
| 4333 | Value *NextVal = ExtInst->getOperand(0); | ||||
| 4334 | TPT.eraseInstruction(ExtInst, NextVal); | ||||
| 4335 | return NextVal; | ||||
| 4336 | } | ||||
| 4337 | |||||
| 4338 | Value *TypePromotionHelper::promoteOperandForOther( | ||||
| 4339 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
| 4340 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
| 4341 | SmallVectorImpl<Instruction *> *Exts, | ||||
| 4342 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, | ||||
| 4343 | bool IsSExt) { | ||||
| 4344 | // By construction, the operand of Ext is an instruction. Otherwise we cannot | ||||
| 4345 | // get through it and this method should not be called. | ||||
| 4346 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); | ||||
| 4347 | CreatedInstsCost = 0; | ||||
| 4348 | if (!ExtOpnd->hasOneUse()) { | ||||
| 4349 | // ExtOpnd will be promoted. | ||||
| 4350 | // All its uses, but Ext, will need to use a truncated value of the | ||||
| 4351 | // promoted version. | ||||
| 4352 | // Create the truncate now. | ||||
| 4353 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); | ||||
| 4354 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { | ||||
| 4355 | // Insert it just after the definition. | ||||
| 4356 | ITrunc->moveAfter(ExtOpnd); | ||||
| 4357 | if (Truncs) | ||||
| 4358 | Truncs->push_back(ITrunc); | ||||
| 4359 | } | ||||
| 4360 | |||||
| 4361 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); | ||||
| 4362 | // Restore the operand of Ext (which has been replaced by the previous call | ||||
| 4363 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. | ||||
| 4364 | TPT.setOperand(Ext, 0, ExtOpnd); | ||||
| 4365 | } | ||||
| 4366 | |||||
| 4367 | // Get through the Instruction: | ||||
| 4368 | // 1. Update its type. | ||||
| 4369 | // 2. Replace the uses of Ext by Inst. | ||||
| 4370 | // 3. Extend each operand that needs to be extended. | ||||
| 4371 | |||||
| 4372 | // Remember the original type of the instruction before promotion. | ||||
| 4373 | // This is useful to know that the high bits are sign extended bits. | ||||
| 4374 | addPromotedInst(PromotedInsts, ExtOpnd, IsSExt); | ||||
| 4375 | // Step #1. | ||||
| 4376 | TPT.mutateType(ExtOpnd, Ext->getType()); | ||||
| 4377 | // Step #2. | ||||
| 4378 | TPT.replaceAllUsesWith(Ext, ExtOpnd); | ||||
| 4379 | // Step #3. | ||||
| 4380 | Instruction *ExtForOpnd = Ext; | ||||
| 4381 | |||||
| 4382 | LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n")do { } while (false); | ||||
| 4383 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; | ||||
| 4384 | ++OpIdx) { | ||||
| 4385 | LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n')do { } while (false); | ||||
| 4386 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || | ||||
| 4387 | !shouldExtOperand(ExtOpnd, OpIdx)) { | ||||
| 4388 | LLVM_DEBUG(dbgs() << "No need to propagate\n")do { } while (false); | ||||
| 4389 | continue; | ||||
| 4390 | } | ||||
| 4391 | // Check if we can statically extend the operand. | ||||
| 4392 | Value *Opnd = ExtOpnd->getOperand(OpIdx); | ||||
| 4393 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { | ||||
| 4394 | LLVM_DEBUG(dbgs() << "Statically extend\n")do { } while (false); | ||||
| 4395 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); | ||||
| 4396 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) | ||||
| 4397 | : Cst->getValue().zext(BitWidth); | ||||
| 4398 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); | ||||
| 4399 | continue; | ||||
| 4400 | } | ||||
| 4401 | // UndefValue are typed, so we have to statically sign extend them. | ||||
| 4402 | if (isa<UndefValue>(Opnd)) { | ||||
| 4403 | LLVM_DEBUG(dbgs() << "Statically extend\n")do { } while (false); | ||||
| 4404 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); | ||||
| 4405 | continue; | ||||
| 4406 | } | ||||
| 4407 | |||||
| 4408 | // Otherwise we have to explicitly sign extend the operand. | ||||
| 4409 | // Check if Ext was reused to extend an operand. | ||||
| 4410 | if (!ExtForOpnd) { | ||||
| 4411 | // If yes, create a new one. | ||||
| 4412 | LLVM_DEBUG(dbgs() << "More operands to ext\n")do { } while (false); | ||||
| 4413 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) | ||||
| 4414 | : TPT.createZExt(Ext, Opnd, Ext->getType()); | ||||
| 4415 | if (!isa<Instruction>(ValForExtOpnd)) { | ||||
| 4416 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); | ||||
| 4417 | continue; | ||||
| 4418 | } | ||||
| 4419 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); | ||||
| 4420 | } | ||||
| 4421 | if (Exts) | ||||
| 4422 | Exts->push_back(ExtForOpnd); | ||||
| 4423 | TPT.setOperand(ExtForOpnd, 0, Opnd); | ||||
| 4424 | |||||
| 4425 | // Move the sign extension before the insertion point. | ||||
| 4426 | TPT.moveBefore(ExtForOpnd, ExtOpnd); | ||||
| 4427 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); | ||||
| 4428 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); | ||||
| 4429 | // If more sext are required, new instructions will have to be created. | ||||
| 4430 | ExtForOpnd = nullptr; | ||||
| 4431 | } | ||||
| 4432 | if (ExtForOpnd == Ext) { | ||||
| 4433 | LLVM_DEBUG(dbgs() << "Extension is useless now\n")do { } while (false); | ||||
| 4434 | TPT.eraseInstruction(Ext); | ||||
| 4435 | } | ||||
| 4436 | return ExtOpnd; | ||||
| 4437 | } | ||||
| 4438 | |||||
| 4439 | /// Check whether or not promoting an instruction to a wider type is profitable. | ||||
| 4440 | /// \p NewCost gives the cost of extension instructions created by the | ||||
| 4441 | /// promotion. | ||||
| 4442 | /// \p OldCost gives the cost of extension instructions before the promotion | ||||
| 4443 | /// plus the number of instructions that have been | ||||
| 4444 | /// matched in the addressing mode the promotion. | ||||
| 4445 | /// \p PromotedOperand is the value that has been promoted. | ||||
| 4446 | /// \return True if the promotion is profitable, false otherwise. | ||||
| 4447 | bool AddressingModeMatcher::isPromotionProfitable( | ||||
| 4448 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { | ||||
| 4449 | LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCostdo { } while (false) | ||||
| 4450 | << '\n')do { } while (false); | ||||
| 4451 | // The cost of the new extensions is greater than the cost of the | ||||
| 4452 | // old extension plus what we folded. | ||||
| 4453 | // This is not profitable. | ||||
| 4454 | if (NewCost > OldCost) | ||||
| 4455 | return false; | ||||
| 4456 | if (NewCost < OldCost) | ||||
| 4457 | return true; | ||||
| 4458 | // The promotion is neutral but it may help folding the sign extension in | ||||
| 4459 | // loads for instance. | ||||
| 4460 | // Check that we did not create an illegal instruction. | ||||
| 4461 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); | ||||
| 4462 | } | ||||
| 4463 | |||||
| 4464 | /// Given an instruction or constant expr, see if we can fold the operation | ||||
| 4465 | /// into the addressing mode. If so, update the addressing mode and return | ||||
| 4466 | /// true, otherwise return false without modifying AddrMode. | ||||
| 4467 | /// If \p MovedAway is not NULL, it contains the information of whether or | ||||
| 4468 | /// not AddrInst has to be folded into the addressing mode on success. | ||||
| 4469 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing | ||||
| 4470 | /// because it has been moved away. | ||||
| 4471 | /// Thus AddrInst must not be added in the matched instructions. | ||||
| 4472 | /// This state can happen when AddrInst is a sext, since it may be moved away. | ||||
| 4473 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must | ||||
| 4474 | /// not be referenced anymore. | ||||
| 4475 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, | ||||
| 4476 | unsigned Depth, | ||||
| 4477 | bool *MovedAway) { | ||||
| 4478 | // Avoid exponential behavior on extremely deep expression trees. | ||||
| 4479 | if (Depth >= 5) return false; | ||||
| 4480 | |||||
| 4481 | // By default, all matched instructions stay in place. | ||||
| 4482 | if (MovedAway) | ||||
| 4483 | *MovedAway = false; | ||||
| 4484 | |||||
| 4485 | switch (Opcode) { | ||||
| 4486 | case Instruction::PtrToInt: | ||||
| 4487 | // PtrToInt is always a noop, as we know that the int type is pointer sized. | ||||
| 4488 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
| 4489 | case Instruction::IntToPtr: { | ||||
| 4490 | auto AS = AddrInst->getType()->getPointerAddressSpace(); | ||||
| 4491 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); | ||||
| 4492 | // This inttoptr is a no-op if the integer type is pointer sized. | ||||
| 4493 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) | ||||
| 4494 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
| 4495 | return false; | ||||
| 4496 | } | ||||
| 4497 | case Instruction::BitCast: | ||||
| 4498 | // BitCast is always a noop, and we can handle it as long as it is | ||||
| 4499 | // int->int or pointer->pointer (we don't want int<->fp or something). | ||||
| 4500 | if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() && | ||||
| 4501 | // Don't touch identity bitcasts. These were probably put here by LSR, | ||||
| 4502 | // and we don't want to mess around with them. Assume it knows what it | ||||
| 4503 | // is doing. | ||||
| 4504 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) | ||||
| 4505 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
| 4506 | return false; | ||||
| 4507 | case Instruction::AddrSpaceCast: { | ||||
| 4508 | unsigned SrcAS | ||||
| 4509 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); | ||||
| 4510 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); | ||||
| 4511 | if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS)) | ||||
| 4512 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
| 4513 | return false; | ||||
| 4514 | } | ||||
| 4515 | case Instruction::Add: { | ||||
| 4516 | // Check to see if we can merge in the RHS then the LHS. If so, we win. | ||||
| 4517 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
| 4518 | unsigned OldSize = AddrModeInsts.size(); | ||||
| 4519 | // Start a transaction at this point. | ||||
| 4520 | // The LHS may match but not the RHS. | ||||
| 4521 | // Therefore, we need a higher level restoration point to undo partially | ||||
| 4522 | // matched operation. | ||||
| 4523 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
| 4524 | TPT.getRestorationPoint(); | ||||
| 4525 | |||||
| 4526 | AddrMode.InBounds = false; | ||||
| 4527 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && | ||||
| 4528 | matchAddr(AddrInst->getOperand(0), Depth+1)) | ||||
| 4529 | return true; | ||||
| 4530 | |||||
| 4531 | // Restore the old addr mode info. | ||||
| 4532 | AddrMode = BackupAddrMode; | ||||
| 4533 | AddrModeInsts.resize(OldSize); | ||||
| 4534 | TPT.rollback(LastKnownGood); | ||||
| 4535 | |||||
| 4536 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. | ||||
| 4537 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && | ||||
| 4538 | matchAddr(AddrInst->getOperand(1), Depth+1)) | ||||
| 4539 | return true; | ||||
| 4540 | |||||
| 4541 | // Otherwise we definitely can't merge the ADD in. | ||||
| 4542 | AddrMode = BackupAddrMode; | ||||
| 4543 | AddrModeInsts.resize(OldSize); | ||||
| 4544 | TPT.rollback(LastKnownGood); | ||||
| 4545 | break; | ||||
| 4546 | } | ||||
| 4547 | //case Instruction::Or: | ||||
| 4548 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. | ||||
| 4549 | //break; | ||||
| 4550 | case Instruction::Mul: | ||||
| 4551 | case Instruction::Shl: { | ||||
| 4552 | // Can only handle X*C and X << C. | ||||
| 4553 | AddrMode.InBounds = false; | ||||
| 4554 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); | ||||
| 4555 | if (!RHS || RHS->getBitWidth() > 64) | ||||
| 4556 | return false; | ||||
| 4557 | int64_t Scale = RHS->getSExtValue(); | ||||
| 4558 | if (Opcode == Instruction::Shl) | ||||
| 4559 | Scale = 1LL << Scale; | ||||
| 4560 | |||||
| 4561 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); | ||||
| 4562 | } | ||||
| 4563 | case Instruction::GetElementPtr: { | ||||
| 4564 | // Scan the GEP. We check it if it contains constant offsets and at most | ||||
| 4565 | // one variable offset. | ||||
| 4566 | int VariableOperand = -1; | ||||
| 4567 | unsigned VariableScale = 0; | ||||
| 4568 | |||||
| 4569 | int64_t ConstantOffset = 0; | ||||
| 4570 | gep_type_iterator GTI = gep_type_begin(AddrInst); | ||||
| 4571 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { | ||||
| 4572 | if (StructType *STy = GTI.getStructTypeOrNull()) { | ||||
| 4573 | const StructLayout *SL = DL.getStructLayout(STy); | ||||
| 4574 | unsigned Idx = | ||||
| 4575 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); | ||||
| 4576 | ConstantOffset += SL->getElementOffset(Idx); | ||||
| 4577 | } else { | ||||
| 4578 | TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType()); | ||||
| 4579 | if (TS.isNonZero()) { | ||||
| 4580 | // The optimisations below currently only work for fixed offsets. | ||||
| 4581 | if (TS.isScalable()) | ||||
| 4582 | return false; | ||||
| 4583 | int64_t TypeSize = TS.getFixedSize(); | ||||
| 4584 | if (ConstantInt *CI = | ||||
| 4585 | dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { | ||||
| 4586 | const APInt &CVal = CI->getValue(); | ||||
| 4587 | if (CVal.getMinSignedBits() <= 64) { | ||||
| 4588 | ConstantOffset += CVal.getSExtValue() * TypeSize; | ||||
| 4589 | continue; | ||||
| 4590 | } | ||||
| 4591 | } | ||||
| 4592 | // We only allow one variable index at the moment. | ||||
| 4593 | if (VariableOperand != -1) | ||||
| 4594 | return false; | ||||
| 4595 | |||||
| 4596 | // Remember the variable index. | ||||
| 4597 | VariableOperand = i; | ||||
| 4598 | VariableScale = TypeSize; | ||||
| 4599 | } | ||||
| 4600 | } | ||||
| 4601 | } | ||||
| 4602 | |||||
| 4603 | // A common case is for the GEP to only do a constant offset. In this case, | ||||
| 4604 | // just add it to the disp field and check validity. | ||||
| 4605 | if (VariableOperand == -1) { | ||||
| 4606 | AddrMode.BaseOffs += ConstantOffset; | ||||
| 4607 | if (ConstantOffset == 0 || | ||||
| 4608 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { | ||||
| 4609 | // Check to see if we can fold the base pointer in too. | ||||
| 4610 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) { | ||||
| 4611 | if (!cast<GEPOperator>(AddrInst)->isInBounds()) | ||||
| 4612 | AddrMode.InBounds = false; | ||||
| 4613 | return true; | ||||
| 4614 | } | ||||
| 4615 | } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) && | ||||
| 4616 | TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 && | ||||
| 4617 | ConstantOffset > 0) { | ||||
| 4618 | // Record GEPs with non-zero offsets as candidates for splitting in the | ||||
| 4619 | // event that the offset cannot fit into the r+i addressing mode. | ||||
| 4620 | // Simple and common case that only one GEP is used in calculating the | ||||
| 4621 | // address for the memory access. | ||||
| 4622 | Value *Base = AddrInst->getOperand(0); | ||||
| 4623 | auto *BaseI = dyn_cast<Instruction>(Base); | ||||
| 4624 | auto *GEP = cast<GetElementPtrInst>(AddrInst); | ||||
| 4625 | if (isa<Argument>(Base) || isa<GlobalValue>(Base) || | ||||
| 4626 | (BaseI && !isa<CastInst>(BaseI) && | ||||
| 4627 | !isa<GetElementPtrInst>(BaseI))) { | ||||
| 4628 | // Make sure the parent block allows inserting non-PHI instructions | ||||
| 4629 | // before the terminator. | ||||
| 4630 | BasicBlock *Parent = | ||||
| 4631 | BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock(); | ||||
| 4632 | if (!Parent->getTerminator()->isEHPad()) | ||||
| 4633 | LargeOffsetGEP = std::make_pair(GEP, ConstantOffset); | ||||
| 4634 | } | ||||
| 4635 | } | ||||
| 4636 | AddrMode.BaseOffs -= ConstantOffset; | ||||
| 4637 | return false; | ||||
| 4638 | } | ||||
| 4639 | |||||
| 4640 | // Save the valid addressing mode in case we can't match. | ||||
| 4641 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
| 4642 | unsigned OldSize = AddrModeInsts.size(); | ||||
| 4643 | |||||
| 4644 | // See if the scale and offset amount is valid for this target. | ||||
| 4645 | AddrMode.BaseOffs += ConstantOffset; | ||||
| 4646 | if (!cast<GEPOperator>(AddrInst)->isInBounds()) | ||||
| 4647 | AddrMode.InBounds = false; | ||||
| 4648 | |||||
| 4649 | // Match the base operand of the GEP. | ||||
| 4650 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { | ||||
| 4651 | // If it couldn't be matched, just stuff the value in a register. | ||||
| 4652 | if (AddrMode.HasBaseReg) { | ||||
| 4653 | AddrMode = BackupAddrMode; | ||||
| 4654 | AddrModeInsts.resize(OldSize); | ||||
| 4655 | return false; | ||||
| 4656 | } | ||||
| 4657 | AddrMode.HasBaseReg = true; | ||||
| 4658 | AddrMode.BaseReg = AddrInst->getOperand(0); | ||||
| 4659 | } | ||||
| 4660 | |||||
| 4661 | // Match the remaining variable portion of the GEP. | ||||
| 4662 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, | ||||
| 4663 | Depth)) { | ||||
| 4664 | // If it couldn't be matched, try stuffing the base into a register | ||||
| 4665 | // instead of matching it, and retrying the match of the scale. | ||||
| 4666 | AddrMode = BackupAddrMode; | ||||
| 4667 | AddrModeInsts.resize(OldSize); | ||||
| 4668 | if (AddrMode.HasBaseReg) | ||||
| 4669 | return false; | ||||
| 4670 | AddrMode.HasBaseReg = true; | ||||
| 4671 | AddrMode.BaseReg = AddrInst->getOperand(0); | ||||
| 4672 | AddrMode.BaseOffs += ConstantOffset; | ||||
| 4673 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), | ||||
| 4674 | VariableScale, Depth)) { | ||||
| 4675 | // If even that didn't work, bail. | ||||
| 4676 | AddrMode = BackupAddrMode; | ||||
| 4677 | AddrModeInsts.resize(OldSize); | ||||
| 4678 | return false; | ||||
| 4679 | } | ||||
| 4680 | } | ||||
| 4681 | |||||
| 4682 | return true; | ||||
| 4683 | } | ||||
| 4684 | case Instruction::SExt: | ||||
| 4685 | case Instruction::ZExt: { | ||||
| 4686 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); | ||||
| 4687 | if (!Ext) | ||||
| 4688 | return false; | ||||
| 4689 | |||||
| 4690 | // Try to move this ext out of the way of the addressing mode. | ||||
| 4691 | // Ask for a method for doing so. | ||||
| 4692 | TypePromotionHelper::Action TPH = | ||||
| 4693 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); | ||||
| 4694 | if (!TPH) | ||||
| 4695 | return false; | ||||
| 4696 | |||||
| 4697 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
| 4698 | TPT.getRestorationPoint(); | ||||
| 4699 | unsigned CreatedInstsCost = 0; | ||||
| 4700 | unsigned ExtCost = !TLI.isExtFree(Ext); | ||||
| 4701 | Value *PromotedOperand = | ||||
| 4702 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); | ||||
| 4703 | // SExt has been moved away. | ||||
| 4704 | // Thus either it will be rematched later in the recursive calls or it is | ||||
| 4705 | // gone. Anyway, we must not fold it into the addressing mode at this point. | ||||
| 4706 | // E.g., | ||||
| 4707 | // op = add opnd, 1 | ||||
| 4708 | // idx = ext op | ||||
| 4709 | // addr = gep base, idx | ||||
| 4710 | // is now: | ||||
| 4711 | // promotedOpnd = ext opnd <- no match here | ||||
| 4712 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) | ||||
| 4713 | // addr = gep base, op <- match | ||||
| 4714 | if (MovedAway) | ||||
| 4715 | *MovedAway = true; | ||||
| 4716 | |||||
| 4717 | assert(PromotedOperand &&((void)0) | ||||
| 4718 | "TypePromotionHelper should have filtered out those cases")((void)0); | ||||
| 4719 | |||||
| 4720 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
| 4721 | unsigned OldSize = AddrModeInsts.size(); | ||||
| 4722 | |||||
| 4723 | if (!matchAddr(PromotedOperand, Depth) || | ||||
| 4724 | // The total of the new cost is equal to the cost of the created | ||||
| 4725 | // instructions. | ||||
| 4726 | // The total of the old cost is equal to the cost of the extension plus | ||||
| 4727 | // what we have saved in the addressing mode. | ||||
| 4728 | !isPromotionProfitable(CreatedInstsCost, | ||||
| 4729 | ExtCost + (AddrModeInsts.size() - OldSize), | ||||
| 4730 | PromotedOperand)) { | ||||
| 4731 | AddrMode = BackupAddrMode; | ||||
| 4732 | AddrModeInsts.resize(OldSize); | ||||
| 4733 | LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n")do { } while (false); | ||||
| 4734 | TPT.rollback(LastKnownGood); | ||||
| 4735 | return false; | ||||
| 4736 | } | ||||
| 4737 | return true; | ||||
| 4738 | } | ||||
| 4739 | } | ||||
| 4740 | return false; | ||||
| 4741 | } | ||||
| 4742 | |||||
| 4743 | /// If we can, try to add the value of 'Addr' into the current addressing mode. | ||||
| 4744 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode | ||||
| 4745 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t | ||||
| 4746 | /// for the target. | ||||
| 4747 | /// | ||||
| 4748 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { | ||||
| 4749 | // Start a transaction at this point that we will rollback if the matching | ||||
| 4750 | // fails. | ||||
| 4751 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
| 4752 | TPT.getRestorationPoint(); | ||||
| 4753 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { | ||||
| 4754 | if (CI->getValue().isSignedIntN(64)) { | ||||
| 4755 | // Fold in immediates if legal for the target. | ||||
| 4756 | AddrMode.BaseOffs += CI->getSExtValue(); | ||||
| 4757 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
| 4758 | return true; | ||||
| 4759 | AddrMode.BaseOffs -= CI->getSExtValue(); | ||||
| 4760 | } | ||||
| 4761 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { | ||||
| 4762 | // If this is a global variable, try to fold it into the addressing mode. | ||||
| 4763 | if (!AddrMode.BaseGV) { | ||||
| 4764 | AddrMode.BaseGV = GV; | ||||
| 4765 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
| 4766 | return true; | ||||
| 4767 | AddrMode.BaseGV = nullptr; | ||||
| 4768 | } | ||||
| 4769 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { | ||||
| 4770 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
| 4771 | unsigned OldSize = AddrModeInsts.size(); | ||||
| 4772 | |||||
| 4773 | // Check to see if it is possible to fold this operation. | ||||
| 4774 | bool MovedAway = false; | ||||
| 4775 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { | ||||
| 4776 | // This instruction may have been moved away. If so, there is nothing | ||||
| 4777 | // to check here. | ||||
| 4778 | if (MovedAway) | ||||
| 4779 | return true; | ||||
| 4780 | // Okay, it's possible to fold this. Check to see if it is actually | ||||
| 4781 | // *profitable* to do so. We use a simple cost model to avoid increasing | ||||
| 4782 | // register pressure too much. | ||||
| 4783 | if (I->hasOneUse() || | ||||
| 4784 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { | ||||
| 4785 | AddrModeInsts.push_back(I); | ||||
| 4786 | return true; | ||||
| 4787 | } | ||||
| 4788 | |||||
| 4789 | // It isn't profitable to do this, roll back. | ||||
| 4790 | //cerr << "NOT FOLDING: " << *I; | ||||
| 4791 | AddrMode = BackupAddrMode; | ||||
| 4792 | AddrModeInsts.resize(OldSize); | ||||
| 4793 | TPT.rollback(LastKnownGood); | ||||
| 4794 | } | ||||
| 4795 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { | ||||
| 4796 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) | ||||
| 4797 | return true; | ||||
| 4798 | TPT.rollback(LastKnownGood); | ||||
| 4799 | } else if (isa<ConstantPointerNull>(Addr)) { | ||||
| 4800 | // Null pointer gets folded without affecting the addressing mode. | ||||
| 4801 | return true; | ||||
| 4802 | } | ||||
| 4803 | |||||
| 4804 | // Worse case, the target should support [reg] addressing modes. :) | ||||
| 4805 | if (!AddrMode.HasBaseReg) { | ||||
| 4806 | AddrMode.HasBaseReg = true; | ||||
| 4807 | AddrMode.BaseReg = Addr; | ||||
| 4808 | // Still check for legality in case the target supports [imm] but not [i+r]. | ||||
| 4809 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
| 4810 | return true; | ||||
| 4811 | AddrMode.HasBaseReg = false; | ||||
| 4812 | AddrMode.BaseReg = nullptr; | ||||
| 4813 | } | ||||
| 4814 | |||||
| 4815 | // If the base register is already taken, see if we can do [r+r]. | ||||
| 4816 | if (AddrMode.Scale == 0) { | ||||
| 4817 | AddrMode.Scale = 1; | ||||
| 4818 | AddrMode.ScaledReg = Addr; | ||||
| 4819 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
| 4820 | return true; | ||||
| 4821 | AddrMode.Scale = 0; | ||||
| 4822 | AddrMode.ScaledReg = nullptr; | ||||
| 4823 | } | ||||
| 4824 | // Couldn't match. | ||||
| 4825 | TPT.rollback(LastKnownGood); | ||||
| 4826 | return false; | ||||
| 4827 | } | ||||
| 4828 | |||||
| 4829 | /// Check to see if all uses of OpVal by the specified inline asm call are due | ||||
| 4830 | /// to memory operands. If so, return true, otherwise return false. | ||||
| 4831 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, | ||||
| 4832 | const TargetLowering &TLI, | ||||
| 4833 | const TargetRegisterInfo &TRI) { | ||||
| 4834 | const Function *F = CI->getFunction(); | ||||
| 4835 | TargetLowering::AsmOperandInfoVector TargetConstraints = | ||||
| 4836 | TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI); | ||||
| 4837 | |||||
| 4838 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { | ||||
| 4839 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; | ||||
| 4840 | |||||
| 4841 | // Compute the constraint code and ConstraintType to use. | ||||
| 4842 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); | ||||
| 4843 | |||||
| 4844 | // If this asm operand is our Value*, and if it isn't an indirect memory | ||||
| 4845 | // operand, we can't fold it! | ||||
| 4846 | if (OpInfo.CallOperandVal == OpVal && | ||||
| 4847 | (OpInfo.ConstraintType != TargetLowering::C_Memory || | ||||
| 4848 | !OpInfo.isIndirect)) | ||||
| 4849 | return false; | ||||
| 4850 | } | ||||
| 4851 | |||||
| 4852 | return true; | ||||
| 4853 | } | ||||
| 4854 | |||||
| 4855 | // Max number of memory uses to look at before aborting the search to conserve | ||||
| 4856 | // compile time. | ||||
| 4857 | static constexpr int MaxMemoryUsesToScan = 20; | ||||
| 4858 | |||||
| 4859 | /// Recursively walk all the uses of I until we find a memory use. | ||||
| 4860 | /// If we find an obviously non-foldable instruction, return true. | ||||
| 4861 | /// Add the ultimately found memory instructions to MemoryUses. | ||||
| 4862 | static bool FindAllMemoryUses( | ||||
| 4863 | Instruction *I, | ||||
| 4864 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, | ||||
| 4865 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI, | ||||
| 4866 | const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, | ||||
| 4867 | BlockFrequencyInfo *BFI, int SeenInsts = 0) { | ||||
| 4868 | // If we already considered this instruction, we're done. | ||||
| 4869 | if (!ConsideredInsts.insert(I).second) | ||||
| 4870 | return false; | ||||
| 4871 | |||||
| 4872 | // If this is an obviously unfoldable instruction, bail out. | ||||
| 4873 | if (!MightBeFoldableInst(I)) | ||||
| 4874 | return true; | ||||
| 4875 | |||||
| 4876 | // Loop over all the uses, recursively processing them. | ||||
| 4877 | for (Use &U : I->uses()) { | ||||
| 4878 | // Conservatively return true if we're seeing a large number or a deep chain | ||||
| 4879 | // of users. This avoids excessive compilation times in pathological cases. | ||||
| 4880 | if (SeenInsts++ >= MaxMemoryUsesToScan) | ||||
| 4881 | return true; | ||||
| 4882 | |||||
| 4883 | Instruction *UserI = cast<Instruction>(U.getUser()); | ||||
| 4884 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { | ||||
| 4885 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); | ||||
| 4886 | continue; | ||||
| 4887 | } | ||||
| 4888 | |||||
| 4889 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { | ||||
| 4890 | unsigned opNo = U.getOperandNo(); | ||||
| 4891 | if (opNo != StoreInst::getPointerOperandIndex()) | ||||
| 4892 | return true; // Storing addr, not into addr. | ||||
| 4893 | MemoryUses.push_back(std::make_pair(SI, opNo)); | ||||
| 4894 | continue; | ||||
| 4895 | } | ||||
| 4896 | |||||
| 4897 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { | ||||
| 4898 | unsigned opNo = U.getOperandNo(); | ||||
| 4899 | if (opNo != AtomicRMWInst::getPointerOperandIndex()) | ||||
| 4900 | return true; // Storing addr, not into addr. | ||||
| 4901 | MemoryUses.push_back(std::make_pair(RMW, opNo)); | ||||
| 4902 | continue; | ||||
| 4903 | } | ||||
| 4904 | |||||
| 4905 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { | ||||
| 4906 | unsigned opNo = U.getOperandNo(); | ||||
| 4907 | if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) | ||||
| 4908 | return true; // Storing addr, not into addr. | ||||
| 4909 | MemoryUses.push_back(std::make_pair(CmpX, opNo)); | ||||
| 4910 | continue; | ||||
| 4911 | } | ||||
| 4912 | |||||
| 4913 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { | ||||
| 4914 | if (CI->hasFnAttr(Attribute::Cold)) { | ||||
| 4915 | // If this is a cold call, we can sink the addressing calculation into | ||||
| 4916 | // the cold path. See optimizeCallInst | ||||
| 4917 | bool OptForSize = OptSize || | ||||
| 4918 | llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI); | ||||
| 4919 | if (!OptForSize) | ||||
| 4920 | continue; | ||||
| 4921 | } | ||||
| 4922 | |||||
| 4923 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand()); | ||||
| 4924 | if (!IA) return true; | ||||
| 4925 | |||||
| 4926 | // If this is a memory operand, we're cool, otherwise bail out. | ||||
| 4927 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) | ||||
| 4928 | return true; | ||||
| 4929 | continue; | ||||
| 4930 | } | ||||
| 4931 | |||||
| 4932 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, | ||||
| 4933 | PSI, BFI, SeenInsts)) | ||||
| 4934 | return true; | ||||
| 4935 | } | ||||
| 4936 | |||||
| 4937 | return false; | ||||
| 4938 | } | ||||
| 4939 | |||||
| 4940 | /// Return true if Val is already known to be live at the use site that we're | ||||
| 4941 | /// folding it into. If so, there is no cost to include it in the addressing | ||||
| 4942 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the | ||||
| 4943 | /// instruction already. | ||||
| 4944 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, | ||||
| 4945 | Value *KnownLive2) { | ||||
| 4946 | // If Val is either of the known-live values, we know it is live! | ||||
| 4947 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) | ||||
| 4948 | return true; | ||||
| 4949 | |||||
| 4950 | // All values other than instructions and arguments (e.g. constants) are live. | ||||
| 4951 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; | ||||
| 4952 | |||||
| 4953 | // If Val is a constant sized alloca in the entry block, it is live, this is | ||||
| 4954 | // true because it is just a reference to the stack/frame pointer, which is | ||||
| 4955 | // live for the whole function. | ||||
| 4956 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) | ||||
| 4957 | if (AI->isStaticAlloca()) | ||||
| 4958 | return true; | ||||
| 4959 | |||||
| 4960 | // Check to see if this value is already used in the memory instruction's | ||||
| 4961 | // block. If so, it's already live into the block at the very least, so we | ||||
| 4962 | // can reasonably fold it. | ||||
| 4963 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); | ||||
| 4964 | } | ||||
| 4965 | |||||
| 4966 | /// It is possible for the addressing mode of the machine to fold the specified | ||||
| 4967 | /// instruction into a load or store that ultimately uses it. | ||||
| 4968 | /// However, the specified instruction has multiple uses. | ||||
| 4969 | /// Given this, it may actually increase register pressure to fold it | ||||
| 4970 | /// into the load. For example, consider this code: | ||||
| 4971 | /// | ||||
| 4972 | /// X = ... | ||||
| 4973 | /// Y = X+1 | ||||
| 4974 | /// use(Y) -> nonload/store | ||||
| 4975 | /// Z = Y+1 | ||||
| 4976 | /// load Z | ||||
| 4977 | /// | ||||
| 4978 | /// In this case, Y has multiple uses, and can be folded into the load of Z | ||||
| 4979 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to | ||||
| 4980 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one | ||||
| 4981 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the | ||||
| 4982 | /// number of computations either. | ||||
| 4983 | /// | ||||
| 4984 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If | ||||
| 4985 | /// X was live across 'load Z' for other reasons, we actually *would* want to | ||||
| 4986 | /// fold the addressing mode in the Z case. This would make Y die earlier. | ||||
| 4987 | bool AddressingModeMatcher:: | ||||
| 4988 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, | ||||
| 4989 | ExtAddrMode &AMAfter) { | ||||
| 4990 | if (IgnoreProfitability) return true; | ||||
| 4991 | |||||
| 4992 | // AMBefore is the addressing mode before this instruction was folded into it, | ||||
| 4993 | // and AMAfter is the addressing mode after the instruction was folded. Get | ||||
| 4994 | // the set of registers referenced by AMAfter and subtract out those | ||||
| 4995 | // referenced by AMBefore: this is the set of values which folding in this | ||||
| 4996 | // address extends the lifetime of. | ||||
| 4997 | // | ||||
| 4998 | // Note that there are only two potential values being referenced here, | ||||
| 4999 | // BaseReg and ScaleReg (global addresses are always available, as are any | ||||
| 5000 | // folded immediates). | ||||
| 5001 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; | ||||
| 5002 | |||||
| 5003 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their | ||||
| 5004 | // lifetime wasn't extended by adding this instruction. | ||||
| 5005 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) | ||||
| 5006 | BaseReg = nullptr; | ||||
| 5007 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) | ||||
| 5008 | ScaledReg = nullptr; | ||||
| 5009 | |||||
| 5010 | // If folding this instruction (and it's subexprs) didn't extend any live | ||||
| 5011 | // ranges, we're ok with it. | ||||
| 5012 | if (!BaseReg && !ScaledReg) | ||||
| 5013 | return true; | ||||
| 5014 | |||||
| 5015 | // If all uses of this instruction can have the address mode sunk into them, | ||||
| 5016 | // we can remove the addressing mode and effectively trade one live register | ||||
| 5017 | // for another (at worst.) In this context, folding an addressing mode into | ||||
| 5018 | // the use is just a particularly nice way of sinking it. | ||||
| 5019 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; | ||||
| 5020 | SmallPtrSet<Instruction*, 16> ConsideredInsts; | ||||
| 5021 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, | ||||
| 5022 | PSI, BFI)) | ||||
| 5023 | return false; // Has a non-memory, non-foldable use! | ||||
| 5024 | |||||
| 5025 | // Now that we know that all uses of this instruction are part of a chain of | ||||
| 5026 | // computation involving only operations that could theoretically be folded | ||||
| 5027 | // into a memory use, loop over each of these memory operation uses and see | ||||
| 5028 | // if they could *actually* fold the instruction. The assumption is that | ||||
| 5029 | // addressing modes are cheap and that duplicating the computation involved | ||||
| 5030 | // many times is worthwhile, even on a fastpath. For sinking candidates | ||||
| 5031 | // (i.e. cold call sites), this serves as a way to prevent excessive code | ||||
| 5032 | // growth since most architectures have some reasonable small and fast way to | ||||
| 5033 | // compute an effective address. (i.e LEA on x86) | ||||
| 5034 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; | ||||
| 5035 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { | ||||
| 5036 | Instruction *User = MemoryUses[i].first; | ||||
| 5037 | unsigned OpNo = MemoryUses[i].second; | ||||
| 5038 | |||||
| 5039 | // Get the access type of this use. If the use isn't a pointer, we don't | ||||
| 5040 | // know what it accesses. | ||||
| 5041 | Value *Address = User->getOperand(OpNo); | ||||
| 5042 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); | ||||
| 5043 | if (!AddrTy) | ||||
| 5044 | return false; | ||||
| 5045 | Type *AddressAccessTy = AddrTy->getElementType(); | ||||
| 5046 | unsigned AS = AddrTy->getAddressSpace(); | ||||
| 5047 | |||||
| 5048 | // Do a match against the root of this address, ignoring profitability. This | ||||
| 5049 | // will tell us if the addressing mode for the memory operation will | ||||
| 5050 | // *actually* cover the shared instruction. | ||||
| 5051 | ExtAddrMode Result; | ||||
| 5052 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, | ||||
| 5053 | 0); | ||||
| 5054 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
| 5055 | TPT.getRestorationPoint(); | ||||
| 5056 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn, | ||||
| 5057 | AddressAccessTy, AS, MemoryInst, Result, | ||||
| 5058 | InsertedInsts, PromotedInsts, TPT, | ||||
| 5059 | LargeOffsetGEP, OptSize, PSI, BFI); | ||||
| 5060 | Matcher.IgnoreProfitability = true; | ||||
| 5061 | bool Success = Matcher.matchAddr(Address, 0); | ||||
| 5062 | (void)Success; assert(Success && "Couldn't select *anything*?")((void)0); | ||||
| 5063 | |||||
| 5064 | // The match was to check the profitability, the changes made are not | ||||
| 5065 | // part of the original matcher. Therefore, they should be dropped | ||||
| 5066 | // otherwise the original matcher will not present the right state. | ||||
| 5067 | TPT.rollback(LastKnownGood); | ||||
| 5068 | |||||
| 5069 | // If the match didn't cover I, then it won't be shared by it. | ||||
| 5070 | if (!is_contained(MatchedAddrModeInsts, I)) | ||||
| 5071 | return false; | ||||
| 5072 | |||||
| 5073 | MatchedAddrModeInsts.clear(); | ||||
| 5074 | } | ||||
| 5075 | |||||
| 5076 | return true; | ||||
| 5077 | } | ||||
| 5078 | |||||
| 5079 | /// Return true if the specified values are defined in a | ||||
| 5080 | /// different basic block than BB. | ||||
| 5081 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { | ||||
| 5082 | if (Instruction *I = dyn_cast<Instruction>(V)) | ||||
| 5083 | return I->getParent() != BB; | ||||
| 5084 | return false; | ||||
| 5085 | } | ||||
| 5086 | |||||
| 5087 | /// Sink addressing mode computation immediate before MemoryInst if doing so | ||||
| 5088 | /// can be done without increasing register pressure. The need for the | ||||
| 5089 | /// register pressure constraint means this can end up being an all or nothing | ||||
| 5090 | /// decision for all uses of the same addressing computation. | ||||
| 5091 | /// | ||||
| 5092 | /// Load and Store Instructions often have addressing modes that can do | ||||
| 5093 | /// significant amounts of computation. As such, instruction selection will try | ||||
| 5094 | /// to get the load or store to do as much computation as possible for the | ||||
| 5095 | /// program. The problem is that isel can only see within a single block. As | ||||
| 5096 | /// such, we sink as much legal addressing mode work into the block as possible. | ||||
| 5097 | /// | ||||
| 5098 | /// This method is used to optimize both load/store and inline asms with memory | ||||
| 5099 | /// operands. It's also used to sink addressing computations feeding into cold | ||||
| 5100 | /// call sites into their (cold) basic block. | ||||
| 5101 | /// | ||||
| 5102 | /// The motivation for handling sinking into cold blocks is that doing so can | ||||
| 5103 | /// both enable other address mode sinking (by satisfying the register pressure | ||||
| 5104 | /// constraint above), and reduce register pressure globally (by removing the | ||||
| 5105 | /// addressing mode computation from the fast path entirely.). | ||||
| 5106 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, | ||||
| 5107 | Type *AccessTy, unsigned AddrSpace) { | ||||
| 5108 | Value *Repl = Addr; | ||||
| 5109 | |||||
| 5110 | // Try to collapse single-value PHI nodes. This is necessary to undo | ||||
| 5111 | // unprofitable PRE transformations. | ||||
| 5112 | SmallVector<Value*, 8> worklist; | ||||
| 5113 | SmallPtrSet<Value*, 16> Visited; | ||||
| 5114 | worklist.push_back(Addr); | ||||
| 5115 | |||||
| 5116 | // Use a worklist to iteratively look through PHI and select nodes, and | ||||
| 5117 | // ensure that the addressing mode obtained from the non-PHI/select roots of | ||||
| 5118 | // the graph are compatible. | ||||
| 5119 | bool PhiOrSelectSeen = false; | ||||
| 5120 | SmallVector<Instruction*, 16> AddrModeInsts; | ||||
| 5121 | const SimplifyQuery SQ(*DL, TLInfo); | ||||
| 5122 | AddressingModeCombiner AddrModes(SQ, Addr); | ||||
| 5123 | TypePromotionTransaction TPT(RemovedInsts); | ||||
| 5124 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
| 5125 | TPT.getRestorationPoint(); | ||||
| 5126 | while (!worklist.empty()) { | ||||
| 5127 | Value *V = worklist.back(); | ||||
| 5128 | worklist.pop_back(); | ||||
| 5129 | |||||
| 5130 | // We allow traversing cyclic Phi nodes. | ||||
| 5131 | // In case of success after this loop we ensure that traversing through | ||||
| 5132 | // Phi nodes ends up with all cases to compute address of the form | ||||
| 5133 | // BaseGV + Base + Scale * Index + Offset | ||||
| 5134 | // where Scale and Offset are constans and BaseGV, Base and Index | ||||
| 5135 | // are exactly the same Values in all cases. | ||||
| 5136 | // It means that BaseGV, Scale and Offset dominate our memory instruction | ||||
| 5137 | // and have the same value as they had in address computation represented | ||||
| 5138 | // as Phi. So we can safely sink address computation to memory instruction. | ||||
| 5139 | if (!Visited.insert(V).second) | ||||
| 5140 | continue; | ||||
| 5141 | |||||
| 5142 | // For a PHI node, push all of its incoming values. | ||||
| 5143 | if (PHINode *P = dyn_cast<PHINode>(V)) { | ||||
| 5144 | append_range(worklist, P->incoming_values()); | ||||
| 5145 | PhiOrSelectSeen = true; | ||||
| 5146 | continue; | ||||
| 5147 | } | ||||
| 5148 | // Similar for select. | ||||
| 5149 | if (SelectInst *SI = dyn_cast<SelectInst>(V)) { | ||||
| 5150 | worklist.push_back(SI->getFalseValue()); | ||||
| 5151 | worklist.push_back(SI->getTrueValue()); | ||||
| 5152 | PhiOrSelectSeen = true; | ||||
| 5153 | continue; | ||||
| 5154 | } | ||||
| 5155 | |||||
| 5156 | // For non-PHIs, determine the addressing mode being computed. Note that | ||||
| 5157 | // the result may differ depending on what other uses our candidate | ||||
| 5158 | // addressing instructions might have. | ||||
| 5159 | AddrModeInsts.clear(); | ||||
| 5160 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, | ||||
| 5161 | 0); | ||||
| 5162 | // Defer the query (and possible computation of) the dom tree to point of | ||||
| 5163 | // actual use. It's expected that most address matches don't actually need | ||||
| 5164 | // the domtree. | ||||
| 5165 | auto getDTFn = [MemoryInst, this]() -> const DominatorTree & { | ||||
| 5166 | Function *F = MemoryInst->getParent()->getParent(); | ||||
| 5167 | return this->getDT(*F); | ||||
| 5168 | }; | ||||
| 5169 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( | ||||
| 5170 | V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn, | ||||
| 5171 | *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, | ||||
| 5172 | BFI.get()); | ||||
| 5173 | |||||
| 5174 | GetElementPtrInst *GEP = LargeOffsetGEP.first; | ||||
| 5175 | if (GEP && !NewGEPBases.count(GEP)) { | ||||
| 5176 | // If splitting the underlying data structure can reduce the offset of a | ||||
| 5177 | // GEP, collect the GEP. Skip the GEPs that are the new bases of | ||||
| 5178 | // previously split data structures. | ||||
| 5179 | LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP); | ||||
| 5180 | if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end()) | ||||
| 5181 | LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size(); | ||||
| 5182 | } | ||||
| 5183 | |||||
| 5184 | NewAddrMode.OriginalValue = V; | ||||
| 5185 | if (!AddrModes.addNewAddrMode(NewAddrMode)) | ||||
| 5186 | break; | ||||
| 5187 | } | ||||
| 5188 | |||||
| 5189 | // Try to combine the AddrModes we've collected. If we couldn't collect any, | ||||
| 5190 | // or we have multiple but either couldn't combine them or combining them | ||||
| 5191 | // wouldn't do anything useful, bail out now. | ||||
| 5192 | if (!AddrModes.combineAddrModes()) { | ||||
| 5193 | TPT.rollback(LastKnownGood); | ||||
| 5194 | return false; | ||||
| 5195 | } | ||||
| 5196 | bool Modified = TPT.commit(); | ||||
| 5197 | |||||
| 5198 | // Get the combined AddrMode (or the only AddrMode, if we only had one). | ||||
| 5199 | ExtAddrMode AddrMode = AddrModes.getAddrMode(); | ||||
| 5200 | |||||
| 5201 | // If all the instructions matched are already in this BB, don't do anything. | ||||
| 5202 | // If we saw a Phi node then it is not local definitely, and if we saw a select | ||||
| 5203 | // then we want to push the address calculation past it even if it's already | ||||
| 5204 | // in this BB. | ||||
| 5205 | if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) { | ||||
| 5206 | return IsNonLocalValue(V, MemoryInst->getParent()); | ||||
| 5207 | })) { | ||||
| 5208 | LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrModedo { } while (false) | ||||
| 5209 | << "\n")do { } while (false); | ||||
| 5210 | return Modified; | ||||
| 5211 | } | ||||
| 5212 | |||||
| 5213 | // Insert this computation right after this user. Since our caller is | ||||
| 5214 | // scanning from the top of the BB to the bottom, reuse of the expr are | ||||
| 5215 | // guaranteed to happen later. | ||||
| 5216 | IRBuilder<> Builder(MemoryInst); | ||||
| 5217 | |||||
| 5218 | // Now that we determined the addressing expression we want to use and know | ||||
| 5219 | // that we have to sink it into this block. Check to see if we have already | ||||
| 5220 | // done this for some other load/store instr in this block. If so, reuse | ||||
| 5221 | // the computation. Before attempting reuse, check if the address is valid | ||||
| 5222 | // as it may have been erased. | ||||
| 5223 | |||||
| 5224 | WeakTrackingVH SunkAddrVH = SunkAddrs[Addr]; | ||||
| 5225 | |||||
| 5226 | Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; | ||||
| 5227 | if (SunkAddr) { | ||||
| 5228 | LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrModedo { } while (false) | ||||
| 5229 | << " for " << *MemoryInst << "\n")do { } while (false); | ||||
| 5230 | if (SunkAddr->getType() != Addr->getType()) | ||||
| 5231 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); | ||||
| 5232 | } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() && | ||||
| 5233 | SubtargetInfo->addrSinkUsingGEPs())) { | ||||
| 5234 | // By default, we use the GEP-based method when AA is used later. This | ||||
| 5235 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. | ||||
| 5236 | LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrModedo { } while (false) | ||||
| 5237 | << " for " << *MemoryInst << "\n")do { } while (false); | ||||
| 5238 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); | ||||
| 5239 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; | ||||
| 5240 | |||||
| 5241 | // First, find the pointer. | ||||
| 5242 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { | ||||
| 5243 | ResultPtr = AddrMode.BaseReg; | ||||
| 5244 | AddrMode.BaseReg = nullptr; | ||||
| 5245 | } | ||||
| 5246 | |||||
| 5247 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { | ||||
| 5248 | // We can't add more than one pointer together, nor can we scale a | ||||
| 5249 | // pointer (both of which seem meaningless). | ||||
| 5250 | if (ResultPtr || AddrMode.Scale != 1) | ||||
| 5251 | return Modified; | ||||
| 5252 | |||||
| 5253 | ResultPtr = AddrMode.ScaledReg; | ||||
| 5254 | AddrMode.Scale = 0; | ||||
| 5255 | } | ||||
| 5256 | |||||
| 5257 | // It is only safe to sign extend the BaseReg if we know that the math | ||||
| 5258 | // required to create it did not overflow before we extend it. Since | ||||
| 5259 | // the original IR value was tossed in favor of a constant back when | ||||
| 5260 | // the AddrMode was created we need to bail out gracefully if widths | ||||
| 5261 | // do not match instead of extending it. | ||||
| 5262 | // | ||||
| 5263 | // (See below for code to add the scale.) | ||||
| 5264 | if (AddrMode.Scale) { | ||||
| 5265 | Type *ScaledRegTy = AddrMode.ScaledReg->getType(); | ||||
| 5266 | if (cast<IntegerType>(IntPtrTy)->getBitWidth() > | ||||
| 5267 | cast<IntegerType>(ScaledRegTy)->getBitWidth()) | ||||
| 5268 | return Modified; | ||||
| 5269 | } | ||||
| 5270 | |||||
| 5271 | if (AddrMode.BaseGV) { | ||||
| 5272 | if (ResultPtr) | ||||
| 5273 | return Modified; | ||||
| 5274 | |||||
| 5275 | ResultPtr = AddrMode.BaseGV; | ||||
| 5276 | } | ||||
| 5277 | |||||
| 5278 | // If the real base value actually came from an inttoptr, then the matcher | ||||
| 5279 | // will look through it and provide only the integer value. In that case, | ||||
| 5280 | // use it here. | ||||
| 5281 | if (!DL->isNonIntegralPointerType(Addr->getType())) { | ||||
| 5282 | if (!ResultPtr && AddrMode.BaseReg) { | ||||
| 5283 | ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), | ||||
| 5284 | "sunkaddr"); | ||||
| 5285 | AddrMode.BaseReg = nullptr; | ||||
| 5286 | } else if (!ResultPtr && AddrMode.Scale == 1) { | ||||
| 5287 | ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), | ||||
| 5288 | "sunkaddr"); | ||||
| 5289 | AddrMode.Scale = 0; | ||||
| 5290 | } | ||||
| 5291 | } | ||||
| 5292 | |||||
| 5293 | if (!ResultPtr && | ||||
| 5294 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { | ||||
| 5295 | SunkAddr = Constant::getNullValue(Addr->getType()); | ||||
| 5296 | } else if (!ResultPtr) { | ||||
| 5297 | return Modified; | ||||
| 5298 | } else { | ||||
| 5299 | Type *I8PtrTy = | ||||
| 5300 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); | ||||
| 5301 | Type *I8Ty = Builder.getInt8Ty(); | ||||
| 5302 | |||||
| 5303 | // Start with the base register. Do this first so that subsequent address | ||||
| 5304 | // matching finds it last, which will prevent it from trying to match it | ||||
| 5305 | // as the scaled value in case it happens to be a mul. That would be | ||||
| 5306 | // problematic if we've sunk a different mul for the scale, because then | ||||
| 5307 | // we'd end up sinking both muls. | ||||
| 5308 | if (AddrMode.BaseReg) { | ||||
| 5309 | Value *V = AddrMode.BaseReg; | ||||
| 5310 | if (V->getType() != IntPtrTy) | ||||
| 5311 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); | ||||
| 5312 | |||||
| 5313 | ResultIndex = V; | ||||
| 5314 | } | ||||
| 5315 | |||||
| 5316 | // Add the scale value. | ||||
| 5317 | if (AddrMode.Scale) { | ||||
| 5318 | Value *V = AddrMode.ScaledReg; | ||||
| 5319 | if (V->getType() == IntPtrTy) { | ||||
| 5320 | // done. | ||||
| 5321 | } else { | ||||
| 5322 | assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <((void)0) | ||||
| 5323 | cast<IntegerType>(V->getType())->getBitWidth() &&((void)0) | ||||
| 5324 | "We can't transform if ScaledReg is too narrow")((void)0); | ||||
| 5325 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); | ||||
| 5326 | } | ||||
| 5327 | |||||
| 5328 | if (AddrMode.Scale != 1) | ||||
| 5329 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), | ||||
| 5330 | "sunkaddr"); | ||||
| 5331 | if (ResultIndex) | ||||
| 5332 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); | ||||
| 5333 | else | ||||
| 5334 | ResultIndex = V; | ||||
| 5335 | } | ||||
| 5336 | |||||
| 5337 | // Add in the Base Offset if present. | ||||
| 5338 | if (AddrMode.BaseOffs) { | ||||
| 5339 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); | ||||
| 5340 | if (ResultIndex) { | ||||
| 5341 | // We need to add this separately from the scale above to help with | ||||
| 5342 | // SDAG consecutive load/store merging. | ||||
| 5343 | if (ResultPtr->getType() != I8PtrTy) | ||||
| 5344 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); | ||||
| 5345 | ResultPtr = | ||||
| 5346 | AddrMode.InBounds | ||||
| 5347 | ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, | ||||
| 5348 | "sunkaddr") | ||||
| 5349 | : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); | ||||
| 5350 | } | ||||
| 5351 | |||||
| 5352 | ResultIndex = V; | ||||
| 5353 | } | ||||
| 5354 | |||||
| 5355 | if (!ResultIndex) { | ||||
| 5356 | SunkAddr = ResultPtr; | ||||
| 5357 | } else { | ||||
| 5358 | if (ResultPtr->getType() != I8PtrTy) | ||||
| 5359 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); | ||||
| 5360 | SunkAddr = | ||||
| 5361 | AddrMode.InBounds | ||||
| 5362 | ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, | ||||
| 5363 | "sunkaddr") | ||||
| 5364 | : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); | ||||
| 5365 | } | ||||
| 5366 | |||||
| 5367 | if (SunkAddr->getType() != Addr->getType()) | ||||
| 5368 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); | ||||
| 5369 | } | ||||
| 5370 | } else { | ||||
| 5371 | // We'd require a ptrtoint/inttoptr down the line, which we can't do for | ||||
| 5372 | // non-integral pointers, so in that case bail out now. | ||||
| 5373 | Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr; | ||||
| 5374 | Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr; | ||||
| 5375 | PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy); | ||||
| 5376 | PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy); | ||||
| 5377 | if (DL->isNonIntegralPointerType(Addr->getType()) || | ||||
| 5378 | (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) || | ||||
| 5379 | (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) || | ||||
| 5380 | (AddrMode.BaseGV && | ||||
| 5381 | DL->isNonIntegralPointerType(AddrMode.BaseGV->getType()))) | ||||
| 5382 | return Modified; | ||||
| 5383 | |||||
| 5384 | LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrModedo { } while (false) | ||||
| 5385 | << " for " << *MemoryInst << "\n")do { } while (false); | ||||
| 5386 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); | ||||
| 5387 | Value *Result = nullptr; | ||||
| 5388 | |||||
| 5389 | // Start with the base register. Do this first so that subsequent address | ||||
| 5390 | // matching finds it last, which will prevent it from trying to match it | ||||
| 5391 | // as the scaled value in case it happens to be a mul. That would be | ||||
| 5392 | // problematic if we've sunk a different mul for the scale, because then | ||||
| 5393 | // we'd end up sinking both muls. | ||||
| 5394 | if (AddrMode.BaseReg) { | ||||
| 5395 | Value *V = AddrMode.BaseReg; | ||||
| 5396 | if (V->getType()->isPointerTy()) | ||||
| 5397 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); | ||||
| 5398 | if (V->getType() != IntPtrTy) | ||||
| 5399 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); | ||||
| 5400 | Result = V; | ||||
| 5401 | } | ||||
| 5402 | |||||
| 5403 | // Add the scale value. | ||||
| 5404 | if (AddrMode.Scale) { | ||||
| 5405 | Value *V = AddrMode.ScaledReg; | ||||
| 5406 | if (V->getType() == IntPtrTy) { | ||||
| 5407 | // done. | ||||
| 5408 | } else if (V->getType()->isPointerTy()) { | ||||
| 5409 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); | ||||
| 5410 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < | ||||
| 5411 | cast<IntegerType>(V->getType())->getBitWidth()) { | ||||
| 5412 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); | ||||
| 5413 | } else { | ||||
| 5414 | // It is only safe to sign extend the BaseReg if we know that the math | ||||
| 5415 | // required to create it did not overflow before we extend it. Since | ||||
| 5416 | // the original IR value was tossed in favor of a constant back when | ||||
| 5417 | // the AddrMode was created we need to bail out gracefully if widths | ||||
| 5418 | // do not match instead of extending it. | ||||
| 5419 | Instruction *I = dyn_cast_or_null<Instruction>(Result); | ||||
| 5420 | if (I && (Result != AddrMode.BaseReg)) | ||||
| 5421 | I->eraseFromParent(); | ||||
| 5422 | return Modified; | ||||
| 5423 | } | ||||
| 5424 | if (AddrMode.Scale != 1) | ||||
| 5425 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), | ||||
| 5426 | "sunkaddr"); | ||||
| 5427 | if (Result) | ||||
| 5428 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); | ||||
| 5429 | else | ||||
| 5430 | Result = V; | ||||
| 5431 | } | ||||
| 5432 | |||||
| 5433 | // Add in the BaseGV if present. | ||||
| 5434 | if (AddrMode.BaseGV) { | ||||
| 5435 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); | ||||
| 5436 | if (Result) | ||||
| 5437 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); | ||||
| 5438 | else | ||||
| 5439 | Result = V; | ||||
| 5440 | } | ||||
| 5441 | |||||
| 5442 | // Add in the Base Offset if present. | ||||
| 5443 | if (AddrMode.BaseOffs) { | ||||
| 5444 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); | ||||
| 5445 | if (Result) | ||||
| 5446 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); | ||||
| 5447 | else | ||||
| 5448 | Result = V; | ||||
| 5449 | } | ||||
| 5450 | |||||
| 5451 | if (!Result) | ||||
| 5452 | SunkAddr = Constant::getNullValue(Addr->getType()); | ||||
| 5453 | else | ||||
| 5454 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); | ||||
| 5455 | } | ||||
| 5456 | |||||
| 5457 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); | ||||
| 5458 | // Store the newly computed address into the cache. In the case we reused a | ||||
| 5459 | // value, this should be idempotent. | ||||
| 5460 | SunkAddrs[Addr] = WeakTrackingVH(SunkAddr); | ||||
| 5461 | |||||
| 5462 | // If we have no uses, recursively delete the value and all dead instructions | ||||
| 5463 | // using it. | ||||
| 5464 | if (Repl->use_empty()) { | ||||
| 5465 | resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() { | ||||
| 5466 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
| 5467 | Repl, TLInfo, nullptr, | ||||
| 5468 | [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
| 5469 | }); | ||||
| 5470 | } | ||||
| 5471 | ++NumMemoryInsts; | ||||
| 5472 | return true; | ||||
| 5473 | } | ||||
| 5474 | |||||
| 5475 | /// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find | ||||
| 5476 | /// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can | ||||
| 5477 | /// only handle a 2 operand GEP in the same basic block or a splat constant | ||||
| 5478 | /// vector. The 2 operands to the GEP must have a scalar pointer and a vector | ||||
| 5479 | /// index. | ||||
| 5480 | /// | ||||
| 5481 | /// If the existing GEP has a vector base pointer that is splat, we can look | ||||
| 5482 | /// through the splat to find the scalar pointer. If we can't find a scalar | ||||
| 5483 | /// pointer there's nothing we can do. | ||||
| 5484 | /// | ||||
| 5485 | /// If we have a GEP with more than 2 indices where the middle indices are all | ||||
| 5486 | /// zeroes, we can replace it with 2 GEPs where the second has 2 operands. | ||||
| 5487 | /// | ||||
| 5488 | /// If the final index isn't a vector or is a splat, we can emit a scalar GEP | ||||
| 5489 | /// followed by a GEP with an all zeroes vector index. This will enable | ||||
| 5490 | /// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a | ||||
| 5491 | /// zero index. | ||||
| 5492 | bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst, | ||||
| 5493 | Value *Ptr) { | ||||
| 5494 | Value *NewAddr; | ||||
| 5495 | |||||
| 5496 | if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { | ||||
| 5497 | // Don't optimize GEPs that don't have indices. | ||||
| 5498 | if (!GEP->hasIndices()) | ||||
| 5499 | return false; | ||||
| 5500 | |||||
| 5501 | // If the GEP and the gather/scatter aren't in the same BB, don't optimize. | ||||
| 5502 | // FIXME: We should support this by sinking the GEP. | ||||
| 5503 | if (MemoryInst->getParent() != GEP->getParent()) | ||||
| 5504 | return false; | ||||
| 5505 | |||||
| 5506 | SmallVector<Value *, 2> Ops(GEP->operands()); | ||||
| 5507 | |||||
| 5508 | bool RewriteGEP = false; | ||||
| 5509 | |||||
| 5510 | if (Ops[0]->getType()->isVectorTy()) { | ||||
| 5511 | Ops[0] = getSplatValue(Ops[0]); | ||||
| 5512 | if (!Ops[0]) | ||||
| 5513 | return false; | ||||
| 5514 | RewriteGEP = true; | ||||
| 5515 | } | ||||
| 5516 | |||||
| 5517 | unsigned FinalIndex = Ops.size() - 1; | ||||
| 5518 | |||||
| 5519 | // Ensure all but the last index is 0. | ||||
| 5520 | // FIXME: This isn't strictly required. All that's required is that they are | ||||
| 5521 | // all scalars or splats. | ||||
| 5522 | for (unsigned i = 1; i < FinalIndex; ++i) { | ||||
| 5523 | auto *C = dyn_cast<Constant>(Ops[i]); | ||||
| 5524 | if (!C) | ||||
| 5525 | return false; | ||||
| 5526 | if (isa<VectorType>(C->getType())) | ||||
| 5527 | C = C->getSplatValue(); | ||||
| 5528 | auto *CI = dyn_cast_or_null<ConstantInt>(C); | ||||
| 5529 | if (!CI || !CI->isZero()) | ||||
| 5530 | return false; | ||||
| 5531 | // Scalarize the index if needed. | ||||
| 5532 | Ops[i] = CI; | ||||
| 5533 | } | ||||
| 5534 | |||||
| 5535 | // Try to scalarize the final index. | ||||
| 5536 | if (Ops[FinalIndex]->getType()->isVectorTy()) { | ||||
| 5537 | if (Value *V = getSplatValue(Ops[FinalIndex])) { | ||||
| 5538 | auto *C = dyn_cast<ConstantInt>(V); | ||||
| 5539 | // Don't scalarize all zeros vector. | ||||
| 5540 | if (!C || !C->isZero()) { | ||||
| 5541 | Ops[FinalIndex] = V; | ||||
| 5542 | RewriteGEP = true; | ||||
| 5543 | } | ||||
| 5544 | } | ||||
| 5545 | } | ||||
| 5546 | |||||
| 5547 | // If we made any changes or the we have extra operands, we need to generate | ||||
| 5548 | // new instructions. | ||||
| 5549 | if (!RewriteGEP && Ops.size() == 2) | ||||
| 5550 | return false; | ||||
| 5551 | |||||
| 5552 | auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); | ||||
| 5553 | |||||
| 5554 | IRBuilder<> Builder(MemoryInst); | ||||
| 5555 | |||||
| 5556 | Type *SourceTy = GEP->getSourceElementType(); | ||||
| 5557 | Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType()); | ||||
| 5558 | |||||
| 5559 | // If the final index isn't a vector, emit a scalar GEP containing all ops | ||||
| 5560 | // and a vector GEP with all zeroes final index. | ||||
| 5561 | if (!Ops[FinalIndex]->getType()->isVectorTy()) { | ||||
| 5562 | NewAddr = Builder.CreateGEP(SourceTy, Ops[0], | ||||
| 5563 | makeArrayRef(Ops).drop_front()); | ||||
| 5564 | auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts); | ||||
| 5565 | auto *SecondTy = GetElementPtrInst::getIndexedType( | ||||
| 5566 | SourceTy, makeArrayRef(Ops).drop_front()); | ||||
| 5567 | NewAddr = | ||||
| 5568 | Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy)); | ||||
| 5569 | } else { | ||||
| 5570 | Value *Base = Ops[0]; | ||||
| 5571 | Value *Index = Ops[FinalIndex]; | ||||
| 5572 | |||||
| 5573 | // Create a scalar GEP if there are more than 2 operands. | ||||
| 5574 | if (Ops.size() != 2) { | ||||
| 5575 | // Replace the last index with 0. | ||||
| 5576 | Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy); | ||||
| 5577 | Base = Builder.CreateGEP(SourceTy, Base, | ||||
| 5578 | makeArrayRef(Ops).drop_front()); | ||||
| 5579 | SourceTy = GetElementPtrInst::getIndexedType( | ||||
| 5580 | SourceTy, makeArrayRef(Ops).drop_front()); | ||||
| 5581 | } | ||||
| 5582 | |||||
| 5583 | // Now create the GEP with scalar pointer and vector index. | ||||
| 5584 | NewAddr = Builder.CreateGEP(SourceTy, Base, Index); | ||||
| 5585 | } | ||||
| 5586 | } else if (!isa<Constant>(Ptr)) { | ||||
| 5587 | // Not a GEP, maybe its a splat and we can create a GEP to enable | ||||
| 5588 | // SelectionDAGBuilder to use it as a uniform base. | ||||
| 5589 | Value *V = getSplatValue(Ptr); | ||||
| 5590 | if (!V) | ||||
| 5591 | return false; | ||||
| 5592 | |||||
| 5593 | auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); | ||||
| 5594 | |||||
| 5595 | IRBuilder<> Builder(MemoryInst); | ||||
| 5596 | |||||
| 5597 | // Emit a vector GEP with a scalar pointer and all 0s vector index. | ||||
| 5598 | Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType()); | ||||
| 5599 | auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts); | ||||
| 5600 | Type *ScalarTy; | ||||
| 5601 | if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() == | ||||
| 5602 | Intrinsic::masked_gather) { | ||||
| 5603 | ScalarTy = MemoryInst->getType()->getScalarType(); | ||||
| 5604 | } else { | ||||
| 5605 | assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==((void)0) | ||||
| 5606 | Intrinsic::masked_scatter)((void)0); | ||||
| 5607 | ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType(); | ||||
| 5608 | } | ||||
| 5609 | NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy)); | ||||
| 5610 | } else { | ||||
| 5611 | // Constant, SelectionDAGBuilder knows to check if its a splat. | ||||
| 5612 | return false; | ||||
| 5613 | } | ||||
| 5614 | |||||
| 5615 | MemoryInst->replaceUsesOfWith(Ptr, NewAddr); | ||||
| 5616 | |||||
| 5617 | // If we have no uses, recursively delete the value and all dead instructions | ||||
| 5618 | // using it. | ||||
| 5619 | if (Ptr->use_empty()) | ||||
| 5620 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
| 5621 | Ptr, TLInfo, nullptr, | ||||
| 5622 | [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
| 5623 | |||||
| 5624 | return true; | ||||
| 5625 | } | ||||
| 5626 | |||||
| 5627 | /// If there are any memory operands, use OptimizeMemoryInst to sink their | ||||
| 5628 | /// address computing into the block when possible / profitable. | ||||
| 5629 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { | ||||
| 5630 | bool MadeChange = false; | ||||
| 5631 | |||||
| 5632 | const TargetRegisterInfo *TRI = | ||||
| 5633 | TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo(); | ||||
| 5634 | TargetLowering::AsmOperandInfoVector TargetConstraints = | ||||
| 5635 | TLI->ParseConstraints(*DL, TRI, *CS); | ||||
| 5636 | unsigned ArgNo = 0; | ||||
| 5637 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { | ||||
| 5638 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; | ||||
| 5639 | |||||
| 5640 | // Compute the constraint code and ConstraintType to use. | ||||
| 5641 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); | ||||
| 5642 | |||||
| 5643 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && | ||||
| 5644 | OpInfo.isIndirect) { | ||||
| 5645 | Value *OpVal = CS->getArgOperand(ArgNo++); | ||||
| 5646 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); | ||||
| 5647 | } else if (OpInfo.Type == InlineAsm::isInput) | ||||
| 5648 | ArgNo++; | ||||
| 5649 | } | ||||
| 5650 | |||||
| 5651 | return MadeChange; | ||||
| 5652 | } | ||||
| 5653 | |||||
| 5654 | /// Check if all the uses of \p Val are equivalent (or free) zero or | ||||
| 5655 | /// sign extensions. | ||||
| 5656 | static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { | ||||
| 5657 | assert(!Val->use_empty() && "Input must have at least one use")((void)0); | ||||
| 5658 | const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); | ||||
| 5659 | bool IsSExt = isa<SExtInst>(FirstUser); | ||||
| 5660 | Type *ExtTy = FirstUser->getType(); | ||||
| 5661 | for (const User *U : Val->users()) { | ||||
| 5662 | const Instruction *UI = cast<Instruction>(U); | ||||
| 5663 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) | ||||
| 5664 | return false; | ||||
| 5665 | Type *CurTy = UI->getType(); | ||||
| 5666 | // Same input and output types: Same instruction after CSE. | ||||
| 5667 | if (CurTy == ExtTy) | ||||
| 5668 | continue; | ||||
| 5669 | |||||
| 5670 | // If IsSExt is true, we are in this situation: | ||||
| 5671 | // a = Val | ||||
| 5672 | // b = sext ty1 a to ty2 | ||||
| 5673 | // c = sext ty1 a to ty3 | ||||
| 5674 | // Assuming ty2 is shorter than ty3, this could be turned into: | ||||
| 5675 | // a = Val | ||||
| 5676 | // b = sext ty1 a to ty2 | ||||
| 5677 | // c = sext ty2 b to ty3 | ||||
| 5678 | // However, the last sext is not free. | ||||
| 5679 | if (IsSExt) | ||||
| 5680 | return false; | ||||
| 5681 | |||||
| 5682 | // This is a ZExt, maybe this is free to extend from one type to another. | ||||
| 5683 | // In that case, we would not account for a different use. | ||||
| 5684 | Type *NarrowTy; | ||||
| 5685 | Type *LargeTy; | ||||
| 5686 | if (ExtTy->getScalarType()->getIntegerBitWidth() > | ||||
| 5687 | CurTy->getScalarType()->getIntegerBitWidth()) { | ||||
| 5688 | NarrowTy = CurTy; | ||||
| 5689 | LargeTy = ExtTy; | ||||
| 5690 | } else { | ||||
| 5691 | NarrowTy = ExtTy; | ||||
| 5692 | LargeTy = CurTy; | ||||
| 5693 | } | ||||
| 5694 | |||||
| 5695 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) | ||||
| 5696 | return false; | ||||
| 5697 | } | ||||
| 5698 | // All uses are the same or can be derived from one another for free. | ||||
| 5699 | return true; | ||||
| 5700 | } | ||||
| 5701 | |||||
| 5702 | /// Try to speculatively promote extensions in \p Exts and continue | ||||
| 5703 | /// promoting through newly promoted operands recursively as far as doing so is | ||||
| 5704 | /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. | ||||
| 5705 | /// When some promotion happened, \p TPT contains the proper state to revert | ||||
| 5706 | /// them. | ||||
| 5707 | /// | ||||
| 5708 | /// \return true if some promotion happened, false otherwise. | ||||
| 5709 | bool CodeGenPrepare::tryToPromoteExts( | ||||
| 5710 | TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, | ||||
| 5711 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, | ||||
| 5712 | unsigned CreatedInstsCost) { | ||||
| 5713 | bool Promoted = false; | ||||
| 5714 | |||||
| 5715 | // Iterate over all the extensions to try to promote them. | ||||
| 5716 | for (auto *I : Exts) { | ||||
| 5717 | // Early check if we directly have ext(load). | ||||
| 5718 | if (isa<LoadInst>(I->getOperand(0))) { | ||||
| 5719 | ProfitablyMovedExts.push_back(I); | ||||
| 5720 | continue; | ||||
| 5721 | } | ||||
| 5722 | |||||
| 5723 | // Check whether or not we want to do any promotion. The reason we have | ||||
| 5724 | // this check inside the for loop is to catch the case where an extension | ||||
| 5725 | // is directly fed by a load because in such case the extension can be moved | ||||
| 5726 | // up without any promotion on its operands. | ||||
| 5727 | if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion) | ||||
| 5728 | return false; | ||||
| 5729 | |||||
| 5730 | // Get the action to perform the promotion. | ||||
| 5731 | TypePromotionHelper::Action TPH = | ||||
| 5732 | TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); | ||||
| 5733 | // Check if we can promote. | ||||
| 5734 | if (!TPH) { | ||||
| 5735 | // Save the current extension as we cannot move up through its operand. | ||||
| 5736 | ProfitablyMovedExts.push_back(I); | ||||
| 5737 | continue; | ||||
| 5738 | } | ||||
| 5739 | |||||
| 5740 | // Save the current state. | ||||
| 5741 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
| 5742 | TPT.getRestorationPoint(); | ||||
| 5743 | SmallVector<Instruction *, 4> NewExts; | ||||
| 5744 | unsigned NewCreatedInstsCost = 0; | ||||
| 5745 | unsigned ExtCost = !TLI->isExtFree(I); | ||||
| 5746 | // Promote. | ||||
| 5747 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, | ||||
| 5748 | &NewExts, nullptr, *TLI); | ||||
| 5749 | assert(PromotedVal &&((void)0) | ||||
| 5750 | "TypePromotionHelper should have filtered out those cases")((void)0); | ||||
| 5751 | |||||
| 5752 | // We would be able to merge only one extension in a load. | ||||
| 5753 | // Therefore, if we have more than 1 new extension we heuristically | ||||
| 5754 | // cut this search path, because it means we degrade the code quality. | ||||
| 5755 | // With exactly 2, the transformation is neutral, because we will merge | ||||
| 5756 | // one extension but leave one. However, we optimistically keep going, | ||||
| 5757 | // because the new extension may be removed too. | ||||
| 5758 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; | ||||
| 5759 | // FIXME: It would be possible to propagate a negative value instead of | ||||
| 5760 | // conservatively ceiling it to 0. | ||||
| 5761 | TotalCreatedInstsCost = | ||||
| 5762 | std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); | ||||
| 5763 | if (!StressExtLdPromotion && | ||||
| 5764 | (TotalCreatedInstsCost > 1 || | ||||
| 5765 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { | ||||
| 5766 | // This promotion is not profitable, rollback to the previous state, and | ||||
| 5767 | // save the current extension in ProfitablyMovedExts as the latest | ||||
| 5768 | // speculative promotion turned out to be unprofitable. | ||||
| 5769 | TPT.rollback(LastKnownGood); | ||||
| 5770 | ProfitablyMovedExts.push_back(I); | ||||
| 5771 | continue; | ||||
| 5772 | } | ||||
| 5773 | // Continue promoting NewExts as far as doing so is profitable. | ||||
| 5774 | SmallVector<Instruction *, 2> NewlyMovedExts; | ||||
| 5775 | (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); | ||||
| 5776 | bool NewPromoted = false; | ||||
| 5777 | for (auto *ExtInst : NewlyMovedExts) { | ||||
| 5778 | Instruction *MovedExt = cast<Instruction>(ExtInst); | ||||
| 5779 | Value *ExtOperand = MovedExt->getOperand(0); | ||||
| 5780 | // If we have reached to a load, we need this extra profitability check | ||||
| 5781 | // as it could potentially be merged into an ext(load). | ||||
| 5782 | if (isa<LoadInst>(ExtOperand) && | ||||
| 5783 | !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || | ||||
| 5784 | (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) | ||||
| 5785 | continue; | ||||
| 5786 | |||||
| 5787 | ProfitablyMovedExts.push_back(MovedExt); | ||||
| 5788 | NewPromoted = true; | ||||
| 5789 | } | ||||
| 5790 | |||||
| 5791 | // If none of speculative promotions for NewExts is profitable, rollback | ||||
| 5792 | // and save the current extension (I) as the last profitable extension. | ||||
| 5793 | if (!NewPromoted) { | ||||
| 5794 | TPT.rollback(LastKnownGood); | ||||
| 5795 | ProfitablyMovedExts.push_back(I); | ||||
| 5796 | continue; | ||||
| 5797 | } | ||||
| 5798 | // The promotion is profitable. | ||||
| 5799 | Promoted = true; | ||||
| 5800 | } | ||||
| 5801 | return Promoted; | ||||
| 5802 | } | ||||
| 5803 | |||||
| 5804 | /// Merging redundant sexts when one is dominating the other. | ||||
| 5805 | bool CodeGenPrepare::mergeSExts(Function &F) { | ||||
| 5806 | bool Changed = false; | ||||
| 5807 | for (auto &Entry : ValToSExtendedUses) { | ||||
| 5808 | SExts &Insts = Entry.second; | ||||
| 5809 | SExts CurPts; | ||||
| 5810 | for (Instruction *Inst : Insts) { | ||||
| 5811 | if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || | ||||
| 5812 | Inst->getOperand(0) != Entry.first) | ||||
| 5813 | continue; | ||||
| 5814 | bool inserted = false; | ||||
| 5815 | for (auto &Pt : CurPts) { | ||||
| 5816 | if (getDT(F).dominates(Inst, Pt)) { | ||||
| 5817 | Pt->replaceAllUsesWith(Inst); | ||||
| 5818 | RemovedInsts.insert(Pt); | ||||
| 5819 | Pt->removeFromParent(); | ||||
| 5820 | Pt = Inst; | ||||
| 5821 | inserted = true; | ||||
| 5822 | Changed = true; | ||||
| 5823 | break; | ||||
| 5824 | } | ||||
| 5825 | if (!getDT(F).dominates(Pt, Inst)) | ||||
| 5826 | // Give up if we need to merge in a common dominator as the | ||||
| 5827 | // experiments show it is not profitable. | ||||
| 5828 | continue; | ||||
| 5829 | Inst->replaceAllUsesWith(Pt); | ||||
| 5830 | RemovedInsts.insert(Inst); | ||||
| 5831 | Inst->removeFromParent(); | ||||
| 5832 | inserted = true; | ||||
| 5833 | Changed = true; | ||||
| 5834 | break; | ||||
| 5835 | } | ||||
| 5836 | if (!inserted) | ||||
| 5837 | CurPts.push_back(Inst); | ||||
| 5838 | } | ||||
| 5839 | } | ||||
| 5840 | return Changed; | ||||
| 5841 | } | ||||
| 5842 | |||||
| 5843 | // Splitting large data structures so that the GEPs accessing them can have | ||||
| 5844 | // smaller offsets so that they can be sunk to the same blocks as their users. | ||||
| 5845 | // For example, a large struct starting from %base is split into two parts | ||||
| 5846 | // where the second part starts from %new_base. | ||||
| 5847 | // | ||||
| 5848 | // Before: | ||||
| 5849 | // BB0: | ||||
| 5850 | // %base = | ||||
| 5851 | // | ||||
| 5852 | // BB1: | ||||
| 5853 | // %gep0 = gep %base, off0 | ||||
| 5854 | // %gep1 = gep %base, off1 | ||||
| 5855 | // %gep2 = gep %base, off2 | ||||
| 5856 | // | ||||
| 5857 | // BB2: | ||||
| 5858 | // %load1 = load %gep0 | ||||
| 5859 | // %load2 = load %gep1 | ||||
| 5860 | // %load3 = load %gep2 | ||||
| 5861 | // | ||||
| 5862 | // After: | ||||
| 5863 | // BB0: | ||||
| 5864 | // %base = | ||||
| 5865 | // %new_base = gep %base, off0 | ||||
| 5866 | // | ||||
| 5867 | // BB1: | ||||
| 5868 | // %new_gep0 = %new_base | ||||
| 5869 | // %new_gep1 = gep %new_base, off1 - off0 | ||||
| 5870 | // %new_gep2 = gep %new_base, off2 - off0 | ||||
| 5871 | // | ||||
| 5872 | // BB2: | ||||
| 5873 | // %load1 = load i32, i32* %new_gep0 | ||||
| 5874 | // %load2 = load i32, i32* %new_gep1 | ||||
| 5875 | // %load3 = load i32, i32* %new_gep2 | ||||
| 5876 | // | ||||
| 5877 | // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because | ||||
| 5878 | // their offsets are smaller enough to fit into the addressing mode. | ||||
| 5879 | bool CodeGenPrepare::splitLargeGEPOffsets() { | ||||
| 5880 | bool Changed = false; | ||||
| 5881 | for (auto &Entry : LargeOffsetGEPMap) { | ||||
| 5882 | Value *OldBase = Entry.first; | ||||
| 5883 | SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>> | ||||
| 5884 | &LargeOffsetGEPs = Entry.second; | ||||
| 5885 | auto compareGEPOffset = | ||||
| 5886 | [&](const std::pair<GetElementPtrInst *, int64_t> &LHS, | ||||
| 5887 | const std::pair<GetElementPtrInst *, int64_t> &RHS) { | ||||
| 5888 | if (LHS.first == RHS.first) | ||||
| 5889 | return false; | ||||
| 5890 | if (LHS.second != RHS.second) | ||||
| 5891 | return LHS.second < RHS.second; | ||||
| 5892 | return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first]; | ||||
| 5893 | }; | ||||
| 5894 | // Sorting all the GEPs of the same data structures based on the offsets. | ||||
| 5895 | llvm::sort(LargeOffsetGEPs, compareGEPOffset); | ||||
| 5896 | LargeOffsetGEPs.erase( | ||||
| 5897 | std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()), | ||||
| 5898 | LargeOffsetGEPs.end()); | ||||
| 5899 | // Skip if all the GEPs have the same offsets. | ||||
| 5900 | if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second) | ||||
| 5901 | continue; | ||||
| 5902 | GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first; | ||||
| 5903 | int64_t BaseOffset = LargeOffsetGEPs.begin()->second; | ||||
| 5904 | Value *NewBaseGEP = nullptr; | ||||
| 5905 | |||||
| 5906 | auto *LargeOffsetGEP = LargeOffsetGEPs.begin(); | ||||
| 5907 | while (LargeOffsetGEP != LargeOffsetGEPs.end()) { | ||||
| 5908 | GetElementPtrInst *GEP = LargeOffsetGEP->first; | ||||
| 5909 | int64_t Offset = LargeOffsetGEP->second; | ||||
| 5910 | if (Offset != BaseOffset) { | ||||
| 5911 | TargetLowering::AddrMode AddrMode; | ||||
| 5912 | AddrMode.BaseOffs = Offset - BaseOffset; | ||||
| 5913 | // The result type of the GEP might not be the type of the memory | ||||
| 5914 | // access. | ||||
| 5915 | if (!TLI->isLegalAddressingMode(*DL, AddrMode, | ||||
| 5916 | GEP->getResultElementType(), | ||||
| 5917 | GEP->getAddressSpace())) { | ||||
| 5918 | // We need to create a new base if the offset to the current base is | ||||
| 5919 | // too large to fit into the addressing mode. So, a very large struct | ||||
| 5920 | // may be split into several parts. | ||||
| 5921 | BaseGEP = GEP; | ||||
| 5922 | BaseOffset = Offset; | ||||
| 5923 | NewBaseGEP = nullptr; | ||||
| 5924 | } | ||||
| 5925 | } | ||||
| 5926 | |||||
| 5927 | // Generate a new GEP to replace the current one. | ||||
| 5928 | LLVMContext &Ctx = GEP->getContext(); | ||||
| 5929 | Type *IntPtrTy = DL->getIntPtrType(GEP->getType()); | ||||
| 5930 | Type *I8PtrTy = | ||||
| 5931 | Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace()); | ||||
| 5932 | Type *I8Ty = Type::getInt8Ty(Ctx); | ||||
| 5933 | |||||
| 5934 | if (!NewBaseGEP) { | ||||
| 5935 | // Create a new base if we don't have one yet. Find the insertion | ||||
| 5936 | // pointer for the new base first. | ||||
| 5937 | BasicBlock::iterator NewBaseInsertPt; | ||||
| 5938 | BasicBlock *NewBaseInsertBB; | ||||
| 5939 | if (auto *BaseI = dyn_cast<Instruction>(OldBase)) { | ||||
| 5940 | // If the base of the struct is an instruction, the new base will be | ||||
| 5941 | // inserted close to it. | ||||
| 5942 | NewBaseInsertBB = BaseI->getParent(); | ||||
| 5943 | if (isa<PHINode>(BaseI)) | ||||
| 5944 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); | ||||
| 5945 | else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) { | ||||
| 5946 | NewBaseInsertBB = | ||||
| 5947 | SplitEdge(NewBaseInsertBB, Invoke->getNormalDest()); | ||||
| 5948 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); | ||||
| 5949 | } else | ||||
| 5950 | NewBaseInsertPt = std::next(BaseI->getIterator()); | ||||
| 5951 | } else { | ||||
| 5952 | // If the current base is an argument or global value, the new base | ||||
| 5953 | // will be inserted to the entry block. | ||||
| 5954 | NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock(); | ||||
| 5955 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); | ||||
| 5956 | } | ||||
| 5957 | IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt); | ||||
| 5958 | // Create a new base. | ||||
| 5959 | Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset); | ||||
| 5960 | NewBaseGEP = OldBase; | ||||
| 5961 | if (NewBaseGEP->getType() != I8PtrTy) | ||||
| 5962 | NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy); | ||||
| 5963 | NewBaseGEP = | ||||
| 5964 | NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep"); | ||||
| 5965 | NewGEPBases.insert(NewBaseGEP); | ||||
| 5966 | } | ||||
| 5967 | |||||
| 5968 | IRBuilder<> Builder(GEP); | ||||
| 5969 | Value *NewGEP = NewBaseGEP; | ||||
| 5970 | if (Offset == BaseOffset) { | ||||
| 5971 | if (GEP->getType() != I8PtrTy) | ||||
| 5972 | NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); | ||||
| 5973 | } else { | ||||
| 5974 | // Calculate the new offset for the new GEP. | ||||
| 5975 | Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset); | ||||
| 5976 | NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index); | ||||
| 5977 | |||||
| 5978 | if (GEP->getType() != I8PtrTy) | ||||
| 5979 | NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); | ||||
| 5980 | } | ||||
| 5981 | GEP->replaceAllUsesWith(NewGEP); | ||||
| 5982 | LargeOffsetGEPID.erase(GEP); | ||||
| 5983 | LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP); | ||||
| 5984 | GEP->eraseFromParent(); | ||||
| 5985 | Changed = true; | ||||
| 5986 | } | ||||
| 5987 | } | ||||
| 5988 | return Changed; | ||||
| 5989 | } | ||||
| 5990 | |||||
| 5991 | bool CodeGenPrepare::optimizePhiType( | ||||
| 5992 | PHINode *I, SmallPtrSetImpl<PHINode *> &Visited, | ||||
| 5993 | SmallPtrSetImpl<Instruction *> &DeletedInstrs) { | ||||
| 5994 | // We are looking for a collection on interconnected phi nodes that together | ||||
| 5995 | // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts | ||||
| 5996 | // are of the same type. Convert the whole set of nodes to the type of the | ||||
| 5997 | // bitcast. | ||||
| 5998 | Type *PhiTy = I->getType(); | ||||
| 5999 | Type *ConvertTy = nullptr; | ||||
| 6000 | if (Visited.count(I) || | ||||
| 6001 | (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy())) | ||||
| 6002 | return false; | ||||
| 6003 | |||||
| 6004 | SmallVector<Instruction *, 4> Worklist; | ||||
| 6005 | Worklist.push_back(cast<Instruction>(I)); | ||||
| 6006 | SmallPtrSet<PHINode *, 4> PhiNodes; | ||||
| 6007 | PhiNodes.insert(I); | ||||
| 6008 | Visited.insert(I); | ||||
| 6009 | SmallPtrSet<Instruction *, 4> Defs; | ||||
| 6010 | SmallPtrSet<Instruction *, 4> Uses; | ||||
| 6011 | // This works by adding extra bitcasts between load/stores and removing | ||||
| 6012 | // existing bicasts. If we have a phi(bitcast(load)) or a store(bitcast(phi)) | ||||
| 6013 | // we can get in the situation where we remove a bitcast in one iteration | ||||
| 6014 | // just to add it again in the next. We need to ensure that at least one | ||||
| 6015 | // bitcast we remove are anchored to something that will not change back. | ||||
| 6016 | bool AnyAnchored = false; | ||||
| 6017 | |||||
| 6018 | while (!Worklist.empty()) { | ||||
| 6019 | Instruction *II = Worklist.pop_back_val(); | ||||
| 6020 | |||||
| 6021 | if (auto *Phi = dyn_cast<PHINode>(II)) { | ||||
| 6022 | // Handle Defs, which might also be PHI's | ||||
| 6023 | for (Value *V : Phi->incoming_values()) { | ||||
| 6024 | if (auto *OpPhi = dyn_cast<PHINode>(V)) { | ||||
| 6025 | if (!PhiNodes.count(OpPhi)) { | ||||
| 6026 | if (Visited.count(OpPhi)) | ||||
| 6027 | return false; | ||||
| 6028 | PhiNodes.insert(OpPhi); | ||||
| 6029 | Visited.insert(OpPhi); | ||||
| 6030 | Worklist.push_back(OpPhi); | ||||
| 6031 | } | ||||
| 6032 | } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) { | ||||
| 6033 | if (!OpLoad->isSimple()) | ||||
| 6034 | return false; | ||||
| 6035 | if (!Defs.count(OpLoad)) { | ||||
| 6036 | Defs.insert(OpLoad); | ||||
| 6037 | Worklist.push_back(OpLoad); | ||||
| 6038 | } | ||||
| 6039 | } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) { | ||||
| 6040 | if (!Defs.count(OpEx)) { | ||||
| 6041 | Defs.insert(OpEx); | ||||
| 6042 | Worklist.push_back(OpEx); | ||||
| 6043 | } | ||||
| 6044 | } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) { | ||||
| 6045 | if (!ConvertTy) | ||||
| 6046 | ConvertTy = OpBC->getOperand(0)->getType(); | ||||
| 6047 | if (OpBC->getOperand(0)->getType() != ConvertTy) | ||||
| 6048 | return false; | ||||
| 6049 | if (!Defs.count(OpBC)) { | ||||
| 6050 | Defs.insert(OpBC); | ||||
| 6051 | Worklist.push_back(OpBC); | ||||
| 6052 | AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) && | ||||
| 6053 | !isa<ExtractElementInst>(OpBC->getOperand(0)); | ||||
| 6054 | } | ||||
| 6055 | } else if (!isa<UndefValue>(V)) { | ||||
| 6056 | return false; | ||||
| 6057 | } | ||||
| 6058 | } | ||||
| 6059 | } | ||||
| 6060 | |||||
| 6061 | // Handle uses which might also be phi's | ||||
| 6062 | for (User *V : II->users()) { | ||||
| 6063 | if (auto *OpPhi = dyn_cast<PHINode>(V)) { | ||||
| 6064 | if (!PhiNodes.count(OpPhi)) { | ||||
| 6065 | if (Visited.count(OpPhi)) | ||||
| 6066 | return false; | ||||
| 6067 | PhiNodes.insert(OpPhi); | ||||
| 6068 | Visited.insert(OpPhi); | ||||
| 6069 | Worklist.push_back(OpPhi); | ||||
| 6070 | } | ||||
| 6071 | } else if (auto *OpStore = dyn_cast<StoreInst>(V)) { | ||||
| 6072 | if (!OpStore->isSimple() || OpStore->getOperand(0) != II) | ||||
| 6073 | return false; | ||||
| 6074 | Uses.insert(OpStore); | ||||
| 6075 | } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) { | ||||
| 6076 | if (!ConvertTy) | ||||
| 6077 | ConvertTy = OpBC->getType(); | ||||
| 6078 | if (OpBC->getType() != ConvertTy) | ||||
| 6079 | return false; | ||||
| 6080 | Uses.insert(OpBC); | ||||
| 6081 | AnyAnchored |= | ||||
| 6082 | any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); }); | ||||
| 6083 | } else { | ||||
| 6084 | return false; | ||||
| 6085 | } | ||||
| 6086 | } | ||||
| 6087 | } | ||||
| 6088 | |||||
| 6089 | if (!ConvertTy || !AnyAnchored || !TLI->shouldConvertPhiType(PhiTy, ConvertTy)) | ||||
| 6090 | return false; | ||||
| 6091 | |||||
| 6092 | LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "do { } while (false) | ||||
| 6093 | << *ConvertTy << "\n")do { } while (false); | ||||
| 6094 | |||||
| 6095 | // Create all the new phi nodes of the new type, and bitcast any loads to the | ||||
| 6096 | // correct type. | ||||
| 6097 | ValueToValueMap ValMap; | ||||
| 6098 | ValMap[UndefValue::get(PhiTy)] = UndefValue::get(ConvertTy); | ||||
| 6099 | for (Instruction *D : Defs) { | ||||
| 6100 | if (isa<BitCastInst>(D)) { | ||||
| 6101 | ValMap[D] = D->getOperand(0); | ||||
| 6102 | DeletedInstrs.insert(D); | ||||
| 6103 | } else { | ||||
| 6104 | ValMap[D] = | ||||
| 6105 | new BitCastInst(D, ConvertTy, D->getName() + ".bc", D->getNextNode()); | ||||
| 6106 | } | ||||
| 6107 | } | ||||
| 6108 | for (PHINode *Phi : PhiNodes) | ||||
| 6109 | ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(), | ||||
| 6110 | Phi->getName() + ".tc", Phi); | ||||
| 6111 | // Pipe together all the PhiNodes. | ||||
| 6112 | for (PHINode *Phi : PhiNodes) { | ||||
| 6113 | PHINode *NewPhi = cast<PHINode>(ValMap[Phi]); | ||||
| 6114 | for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++) | ||||
| 6115 | NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)], | ||||
| 6116 | Phi->getIncomingBlock(i)); | ||||
| 6117 | Visited.insert(NewPhi); | ||||
| 6118 | } | ||||
| 6119 | // And finally pipe up the stores and bitcasts | ||||
| 6120 | for (Instruction *U : Uses) { | ||||
| 6121 | if (isa<BitCastInst>(U)) { | ||||
| 6122 | DeletedInstrs.insert(U); | ||||
| 6123 | U->replaceAllUsesWith(ValMap[U->getOperand(0)]); | ||||
| 6124 | } else { | ||||
| 6125 | U->setOperand(0, | ||||
| 6126 | new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc", U)); | ||||
| 6127 | } | ||||
| 6128 | } | ||||
| 6129 | |||||
| 6130 | // Save the removed phis to be deleted later. | ||||
| 6131 | for (PHINode *Phi : PhiNodes) | ||||
| 6132 | DeletedInstrs.insert(Phi); | ||||
| 6133 | return true; | ||||
| 6134 | } | ||||
| 6135 | |||||
| 6136 | bool CodeGenPrepare::optimizePhiTypes(Function &F) { | ||||
| 6137 | if (!OptimizePhiTypes) | ||||
| 6138 | return false; | ||||
| 6139 | |||||
| 6140 | bool Changed = false; | ||||
| 6141 | SmallPtrSet<PHINode *, 4> Visited; | ||||
| 6142 | SmallPtrSet<Instruction *, 4> DeletedInstrs; | ||||
| 6143 | |||||
| 6144 | // Attempt to optimize all the phis in the functions to the correct type. | ||||
| 6145 | for (auto &BB : F) | ||||
| 6146 | for (auto &Phi : BB.phis()) | ||||
| 6147 | Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs); | ||||
| 6148 | |||||
| 6149 | // Remove any old phi's that have been converted. | ||||
| 6150 | for (auto *I : DeletedInstrs) { | ||||
| 6151 | I->replaceAllUsesWith(UndefValue::get(I->getType())); | ||||
| 6152 | I->eraseFromParent(); | ||||
| 6153 | } | ||||
| 6154 | |||||
| 6155 | return Changed; | ||||
| 6156 | } | ||||
| 6157 | |||||
| 6158 | /// Return true, if an ext(load) can be formed from an extension in | ||||
| 6159 | /// \p MovedExts. | ||||
| 6160 | bool CodeGenPrepare::canFormExtLd( | ||||
| 6161 | const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, | ||||
| 6162 | Instruction *&Inst, bool HasPromoted) { | ||||
| 6163 | for (auto *MovedExtInst : MovedExts) { | ||||
| 6164 | if (isa<LoadInst>(MovedExtInst->getOperand(0))) { | ||||
| 6165 | LI = cast<LoadInst>(MovedExtInst->getOperand(0)); | ||||
| 6166 | Inst = MovedExtInst; | ||||
| 6167 | break; | ||||
| 6168 | } | ||||
| 6169 | } | ||||
| 6170 | if (!LI) | ||||
| 6171 | return false; | ||||
| 6172 | |||||
| 6173 | // If they're already in the same block, there's nothing to do. | ||||
| 6174 | // Make the cheap checks first if we did not promote. | ||||
| 6175 | // If we promoted, we need to check if it is indeed profitable. | ||||
| 6176 | if (!HasPromoted && LI->getParent() == Inst->getParent()) | ||||
| 6177 | return false; | ||||
| 6178 | |||||
| 6179 | return TLI->isExtLoad(LI, Inst, *DL); | ||||
| 6180 | } | ||||
| 6181 | |||||
| 6182 | /// Move a zext or sext fed by a load into the same basic block as the load, | ||||
| 6183 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the | ||||
| 6184 | /// extend into the load. | ||||
| 6185 | /// | ||||
| 6186 | /// E.g., | ||||
| 6187 | /// \code | ||||
| 6188 | /// %ld = load i32* %addr | ||||
| 6189 | /// %add = add nuw i32 %ld, 4 | ||||
| 6190 | /// %zext = zext i32 %add to i64 | ||||
| 6191 | // \endcode | ||||
| 6192 | /// => | ||||
| 6193 | /// \code | ||||
| 6194 | /// %ld = load i32* %addr | ||||
| 6195 | /// %zext = zext i32 %ld to i64 | ||||
| 6196 | /// %add = add nuw i64 %zext, 4 | ||||
| 6197 | /// \encode | ||||
| 6198 | /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which | ||||
| 6199 | /// allow us to match zext(load i32*) to i64. | ||||
| 6200 | /// | ||||
| 6201 | /// Also, try to promote the computations used to obtain a sign extended | ||||
| 6202 | /// value used into memory accesses. | ||||
| 6203 | /// E.g., | ||||
| 6204 | /// \code | ||||
| 6205 | /// a = add nsw i32 b, 3 | ||||
| 6206 | /// d = sext i32 a to i64 | ||||
| 6207 | /// e = getelementptr ..., i64 d | ||||
| 6208 | /// \endcode | ||||
| 6209 | /// => | ||||
| 6210 | /// \code | ||||
| 6211 | /// f = sext i32 b to i64 | ||||
| 6212 | /// a = add nsw i64 f, 3 | ||||
| 6213 | /// e = getelementptr ..., i64 a | ||||
| 6214 | /// \endcode | ||||
| 6215 | /// | ||||
| 6216 | /// \p Inst[in/out] the extension may be modified during the process if some | ||||
| 6217 | /// promotions apply. | ||||
| 6218 | bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { | ||||
| 6219 | bool AllowPromotionWithoutCommonHeader = false; | ||||
| 6220 | /// See if it is an interesting sext operations for the address type | ||||
| 6221 | /// promotion before trying to promote it, e.g., the ones with the right | ||||
| 6222 | /// type and used in memory accesses. | ||||
| 6223 | bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( | ||||
| 6224 | *Inst, AllowPromotionWithoutCommonHeader); | ||||
| 6225 | TypePromotionTransaction TPT(RemovedInsts); | ||||
| 6226 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
| 6227 | TPT.getRestorationPoint(); | ||||
| 6228 | SmallVector<Instruction *, 1> Exts; | ||||
| 6229 | SmallVector<Instruction *, 2> SpeculativelyMovedExts; | ||||
| 6230 | Exts.push_back(Inst); | ||||
| 6231 | |||||
| 6232 | bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); | ||||
| 6233 | |||||
| 6234 | // Look for a load being extended. | ||||
| 6235 | LoadInst *LI = nullptr; | ||||
| 6236 | Instruction *ExtFedByLoad; | ||||
| 6237 | |||||
| 6238 | // Try to promote a chain of computation if it allows to form an extended | ||||
| 6239 | // load. | ||||
| 6240 | if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { | ||||
| 6241 | assert(LI && ExtFedByLoad && "Expect a valid load and extension")((void)0); | ||||
| 6242 | TPT.commit(); | ||||
| 6243 | // Move the extend into the same block as the load. | ||||
| 6244 | ExtFedByLoad->moveAfter(LI); | ||||
| 6245 | ++NumExtsMoved; | ||||
| 6246 | Inst = ExtFedByLoad; | ||||
| 6247 | return true; | ||||
| 6248 | } | ||||
| 6249 | |||||
| 6250 | // Continue promoting SExts if known as considerable depending on targets. | ||||
| 6251 | if (ATPConsiderable && | ||||
| 6252 | performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, | ||||
| 6253 | HasPromoted, TPT, SpeculativelyMovedExts)) | ||||
| 6254 | return true; | ||||
| 6255 | |||||
| 6256 | TPT.rollback(LastKnownGood); | ||||
| 6257 | return false; | ||||
| 6258 | } | ||||
| 6259 | |||||
| 6260 | // Perform address type promotion if doing so is profitable. | ||||
| 6261 | // If AllowPromotionWithoutCommonHeader == false, we should find other sext | ||||
| 6262 | // instructions that sign extended the same initial value. However, if | ||||
| 6263 | // AllowPromotionWithoutCommonHeader == true, we expect promoting the | ||||
| 6264 | // extension is just profitable. | ||||
| 6265 | bool CodeGenPrepare::performAddressTypePromotion( | ||||
| 6266 | Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, | ||||
| 6267 | bool HasPromoted, TypePromotionTransaction &TPT, | ||||
| 6268 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { | ||||
| 6269 | bool Promoted = false; | ||||
| 6270 | SmallPtrSet<Instruction *, 1> UnhandledExts; | ||||
| 6271 | bool AllSeenFirst = true; | ||||
| 6272 | for (auto *I : SpeculativelyMovedExts) { | ||||
| 6273 | Value *HeadOfChain = I->getOperand(0); | ||||
| 6274 | DenseMap<Value *, Instruction *>::iterator AlreadySeen = | ||||
| 6275 | SeenChainsForSExt.find(HeadOfChain); | ||||
| 6276 | // If there is an unhandled SExt which has the same header, try to promote | ||||
| 6277 | // it as well. | ||||
| 6278 | if (AlreadySeen != SeenChainsForSExt.end()) { | ||||
| 6279 | if (AlreadySeen->second != nullptr) | ||||
| 6280 | UnhandledExts.insert(AlreadySeen->second); | ||||
| 6281 | AllSeenFirst = false; | ||||
| 6282 | } | ||||
| 6283 | } | ||||
| 6284 | |||||
| 6285 | if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && | ||||
| 6286 | SpeculativelyMovedExts.size() == 1)) { | ||||
| 6287 | TPT.commit(); | ||||
| 6288 | if (HasPromoted) | ||||
| 6289 | Promoted = true; | ||||
| 6290 | for (auto *I : SpeculativelyMovedExts) { | ||||
| 6291 | Value *HeadOfChain = I->getOperand(0); | ||||
| 6292 | SeenChainsForSExt[HeadOfChain] = nullptr; | ||||
| 6293 | ValToSExtendedUses[HeadOfChain].push_back(I); | ||||
| 6294 | } | ||||
| 6295 | // Update Inst as promotion happen. | ||||
| 6296 | Inst = SpeculativelyMovedExts.pop_back_val(); | ||||
| 6297 | } else { | ||||
| 6298 | // This is the first chain visited from the header, keep the current chain | ||||
| 6299 | // as unhandled. Defer to promote this until we encounter another SExt | ||||
| 6300 | // chain derived from the same header. | ||||
| 6301 | for (auto *I : SpeculativelyMovedExts) { | ||||
| 6302 | Value *HeadOfChain = I->getOperand(0); | ||||
| 6303 | SeenChainsForSExt[HeadOfChain] = Inst; | ||||
| 6304 | } | ||||
| 6305 | return false; | ||||
| 6306 | } | ||||
| 6307 | |||||
| 6308 | if (!AllSeenFirst && !UnhandledExts.empty()) | ||||
| 6309 | for (auto *VisitedSExt : UnhandledExts) { | ||||
| 6310 | if (RemovedInsts.count(VisitedSExt)) | ||||
| 6311 | continue; | ||||
| 6312 | TypePromotionTransaction TPT(RemovedInsts); | ||||
| 6313 | SmallVector<Instruction *, 1> Exts; | ||||
| 6314 | SmallVector<Instruction *, 2> Chains; | ||||
| 6315 | Exts.push_back(VisitedSExt); | ||||
| 6316 | bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); | ||||
| 6317 | TPT.commit(); | ||||
| 6318 | if (HasPromoted) | ||||
| 6319 | Promoted = true; | ||||
| 6320 | for (auto *I : Chains) { | ||||
| 6321 | Value *HeadOfChain = I->getOperand(0); | ||||
| 6322 | // Mark this as handled. | ||||
| 6323 | SeenChainsForSExt[HeadOfChain] = nullptr; | ||||
| 6324 | ValToSExtendedUses[HeadOfChain].push_back(I); | ||||
| 6325 | } | ||||
| 6326 | } | ||||
| 6327 | return Promoted; | ||||
| 6328 | } | ||||
| 6329 | |||||
| 6330 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { | ||||
| 6331 | BasicBlock *DefBB = I->getParent(); | ||||
| 6332 | |||||
| 6333 | // If the result of a {s|z}ext and its source are both live out, rewrite all | ||||
| 6334 | // other uses of the source with result of extension. | ||||
| 6335 | Value *Src = I->getOperand(0); | ||||
| 6336 | if (Src->hasOneUse()) | ||||
| 6337 | return false; | ||||
| 6338 | |||||
| 6339 | // Only do this xform if truncating is free. | ||||
| 6340 | if (!TLI->isTruncateFree(I->getType(), Src->getType())) | ||||
| 6341 | return false; | ||||
| 6342 | |||||
| 6343 | // Only safe to perform the optimization if the source is also defined in | ||||
| 6344 | // this block. | ||||
| 6345 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) | ||||
| 6346 | return false; | ||||
| 6347 | |||||
| 6348 | bool DefIsLiveOut = false; | ||||
| 6349 | for (User *U : I->users()) { | ||||
| 6350 | Instruction *UI = cast<Instruction>(U); | ||||
| 6351 | |||||
| 6352 | // Figure out which BB this ext is used in. | ||||
| 6353 | BasicBlock *UserBB = UI->getParent(); | ||||
| 6354 | if (UserBB == DefBB) continue; | ||||
| 6355 | DefIsLiveOut = true; | ||||
| 6356 | break; | ||||
| 6357 | } | ||||
| 6358 | if (!DefIsLiveOut) | ||||
| 6359 | return false; | ||||
| 6360 | |||||
| 6361 | // Make sure none of the uses are PHI nodes. | ||||
| 6362 | for (User *U : Src->users()) { | ||||
| 6363 | Instruction *UI = cast<Instruction>(U); | ||||
| 6364 | BasicBlock *UserBB = UI->getParent(); | ||||
| 6365 | if (UserBB == DefBB) continue; | ||||
| 6366 | // Be conservative. We don't want this xform to end up introducing | ||||
| 6367 | // reloads just before load / store instructions. | ||||
| 6368 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) | ||||
| 6369 | return false; | ||||
| 6370 | } | ||||
| 6371 | |||||
| 6372 | // InsertedTruncs - Only insert one trunc in each block once. | ||||
| 6373 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; | ||||
| 6374 | |||||
| 6375 | bool MadeChange = false; | ||||
| 6376 | for (Use &U : Src->uses()) { | ||||
| 6377 | Instruction *User = cast<Instruction>(U.getUser()); | ||||
| 6378 | |||||
| 6379 | // Figure out which BB this ext is used in. | ||||
| 6380 | BasicBlock *UserBB = User->getParent(); | ||||
| 6381 | if (UserBB == DefBB) continue; | ||||
| 6382 | |||||
| 6383 | // Both src and def are live in this block. Rewrite the use. | ||||
| 6384 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; | ||||
| 6385 | |||||
| 6386 | if (!InsertedTrunc) { | ||||
| 6387 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
| 6388 | assert(InsertPt != UserBB->end())((void)0); | ||||
| 6389 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); | ||||
| 6390 | InsertedInsts.insert(InsertedTrunc); | ||||
| 6391 | } | ||||
| 6392 | |||||
| 6393 | // Replace a use of the {s|z}ext source with a use of the result. | ||||
| 6394 | U = InsertedTrunc; | ||||
| 6395 | ++NumExtUses; | ||||
| 6396 | MadeChange = true; | ||||
| 6397 | } | ||||
| 6398 | |||||
| 6399 | return MadeChange; | ||||
| 6400 | } | ||||
| 6401 | |||||
| 6402 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" | ||||
| 6403 | // just after the load if the target can fold this into one extload instruction, | ||||
| 6404 | // with the hope of eliminating some of the other later "and" instructions using | ||||
| 6405 | // the loaded value. "and"s that are made trivially redundant by the insertion | ||||
| 6406 | // of the new "and" are removed by this function, while others (e.g. those whose | ||||
| 6407 | // path from the load goes through a phi) are left for isel to potentially | ||||
| 6408 | // remove. | ||||
| 6409 | // | ||||
| 6410 | // For example: | ||||
| 6411 | // | ||||
| 6412 | // b0: | ||||
| 6413 | // x = load i32 | ||||
| 6414 | // ... | ||||
| 6415 | // b1: | ||||
| 6416 | // y = and x, 0xff | ||||
| 6417 | // z = use y | ||||
| 6418 | // | ||||
| 6419 | // becomes: | ||||
| 6420 | // | ||||
| 6421 | // b0: | ||||
| 6422 | // x = load i32 | ||||
| 6423 | // x' = and x, 0xff | ||||
| 6424 | // ... | ||||
| 6425 | // b1: | ||||
| 6426 | // z = use x' | ||||
| 6427 | // | ||||
| 6428 | // whereas: | ||||
| 6429 | // | ||||
| 6430 | // b0: | ||||
| 6431 | // x1 = load i32 | ||||
| 6432 | // ... | ||||
| 6433 | // b1: | ||||
| 6434 | // x2 = load i32 | ||||
| 6435 | // ... | ||||
| 6436 | // b2: | ||||
| 6437 | // x = phi x1, x2 | ||||
| 6438 | // y = and x, 0xff | ||||
| 6439 | // | ||||
| 6440 | // becomes (after a call to optimizeLoadExt for each load): | ||||
| 6441 | // | ||||
| 6442 | // b0: | ||||
| 6443 | // x1 = load i32 | ||||
| 6444 | // x1' = and x1, 0xff | ||||
| 6445 | // ... | ||||
| 6446 | // b1: | ||||
| 6447 | // x2 = load i32 | ||||
| 6448 | // x2' = and x2, 0xff | ||||
| 6449 | // ... | ||||
| 6450 | // b2: | ||||
| 6451 | // x = phi x1', x2' | ||||
| 6452 | // y = and x, 0xff | ||||
| 6453 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { | ||||
| 6454 | if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy()) | ||||
| 6455 | return false; | ||||
| 6456 | |||||
| 6457 | // Skip loads we've already transformed. | ||||
| 6458 | if (Load->hasOneUse() && | ||||
| 6459 | InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) | ||||
| 6460 | return false; | ||||
| 6461 | |||||
| 6462 | // Look at all uses of Load, looking through phis, to determine how many bits | ||||
| 6463 | // of the loaded value are needed. | ||||
| 6464 | SmallVector<Instruction *, 8> WorkList; | ||||
| 6465 | SmallPtrSet<Instruction *, 16> Visited; | ||||
| 6466 | SmallVector<Instruction *, 8> AndsToMaybeRemove; | ||||
| 6467 | for (auto *U : Load->users()) | ||||
| 6468 | WorkList.push_back(cast<Instruction>(U)); | ||||
| 6469 | |||||
| 6470 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); | ||||
| 6471 | unsigned BitWidth = LoadResultVT.getSizeInBits(); | ||||
| 6472 | // If the BitWidth is 0, do not try to optimize the type | ||||
| 6473 | if (BitWidth == 0) | ||||
| 6474 | return false; | ||||
| 6475 | |||||
| 6476 | APInt DemandBits(BitWidth, 0); | ||||
| 6477 | APInt WidestAndBits(BitWidth, 0); | ||||
| 6478 | |||||
| 6479 | while (!WorkList.empty()) { | ||||
| 6480 | Instruction *I = WorkList.back(); | ||||
| 6481 | WorkList.pop_back(); | ||||
| 6482 | |||||
| 6483 | // Break use-def graph loops. | ||||
| 6484 | if (!Visited.insert(I).second) | ||||
| 6485 | continue; | ||||
| 6486 | |||||
| 6487 | // For a PHI node, push all of its users. | ||||
| 6488 | if (auto *Phi = dyn_cast<PHINode>(I)) { | ||||
| 6489 | for (auto *U : Phi->users()) | ||||
| 6490 | WorkList.push_back(cast<Instruction>(U)); | ||||
| 6491 | continue; | ||||
| 6492 | } | ||||
| 6493 | |||||
| 6494 | switch (I->getOpcode()) { | ||||
| 6495 | case Instruction::And: { | ||||
| 6496 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); | ||||
| 6497 | if (!AndC) | ||||
| 6498 | return false; | ||||
| 6499 | APInt AndBits = AndC->getValue(); | ||||
| 6500 | DemandBits |= AndBits; | ||||
| 6501 | // Keep track of the widest and mask we see. | ||||
| 6502 | if (AndBits.ugt(WidestAndBits)) | ||||
| 6503 | WidestAndBits = AndBits; | ||||
| 6504 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) | ||||
| 6505 | AndsToMaybeRemove.push_back(I); | ||||
| 6506 | break; | ||||
| 6507 | } | ||||
| 6508 | |||||
| 6509 | case Instruction::Shl: { | ||||
| 6510 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); | ||||
| 6511 | if (!ShlC) | ||||
| 6512 | return false; | ||||
| 6513 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); | ||||
| 6514 | DemandBits.setLowBits(BitWidth - ShiftAmt); | ||||
| 6515 | break; | ||||
| 6516 | } | ||||
| 6517 | |||||
| 6518 | case Instruction::Trunc: { | ||||
| 6519 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); | ||||
| 6520 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); | ||||
| 6521 | DemandBits.setLowBits(TruncBitWidth); | ||||
| 6522 | break; | ||||
| 6523 | } | ||||
| 6524 | |||||
| 6525 | default: | ||||
| 6526 | return false; | ||||
| 6527 | } | ||||
| 6528 | } | ||||
| 6529 | |||||
| 6530 | uint32_t ActiveBits = DemandBits.getActiveBits(); | ||||
| 6531 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the | ||||
| 6532 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, | ||||
| 6533 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but | ||||
| 6534 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR | ||||
| 6535 | // followed by an AND. | ||||
| 6536 | // TODO: Look into removing this restriction by fixing backends to either | ||||
| 6537 | // return false for isLoadExtLegal for i1 or have them select this pattern to | ||||
| 6538 | // a single instruction. | ||||
| 6539 | // | ||||
| 6540 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits | ||||
| 6541 | // mask, since these are the only ands that will be removed by isel. | ||||
| 6542 | if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || | ||||
| 6543 | WidestAndBits != DemandBits) | ||||
| 6544 | return false; | ||||
| 6545 | |||||
| 6546 | LLVMContext &Ctx = Load->getType()->getContext(); | ||||
| 6547 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); | ||||
| 6548 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); | ||||
| 6549 | |||||
| 6550 | // Reject cases that won't be matched as extloads. | ||||
| 6551 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || | ||||
| 6552 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) | ||||
| 6553 | return false; | ||||
| 6554 | |||||
| 6555 | IRBuilder<> Builder(Load->getNextNode()); | ||||
| 6556 | auto *NewAnd = cast<Instruction>( | ||||
| 6557 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); | ||||
| 6558 | // Mark this instruction as "inserted by CGP", so that other | ||||
| 6559 | // optimizations don't touch it. | ||||
| 6560 | InsertedInsts.insert(NewAnd); | ||||
| 6561 | |||||
| 6562 | // Replace all uses of load with new and (except for the use of load in the | ||||
| 6563 | // new and itself). | ||||
| 6564 | Load->replaceAllUsesWith(NewAnd); | ||||
| 6565 | NewAnd->setOperand(0, Load); | ||||
| 6566 | |||||
| 6567 | // Remove any and instructions that are now redundant. | ||||
| 6568 | for (auto *And : AndsToMaybeRemove) | ||||
| 6569 | // Check that the and mask is the same as the one we decided to put on the | ||||
| 6570 | // new and. | ||||
| 6571 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { | ||||
| 6572 | And->replaceAllUsesWith(NewAnd); | ||||
| 6573 | if (&*CurInstIterator == And) | ||||
| 6574 | CurInstIterator = std::next(And->getIterator()); | ||||
| 6575 | And->eraseFromParent(); | ||||
| 6576 | ++NumAndUses; | ||||
| 6577 | } | ||||
| 6578 | |||||
| 6579 | ++NumAndsAdded; | ||||
| 6580 | return true; | ||||
| 6581 | } | ||||
| 6582 | |||||
| 6583 | /// Check if V (an operand of a select instruction) is an expensive instruction | ||||
| 6584 | /// that is only used once. | ||||
| 6585 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { | ||||
| 6586 | auto *I = dyn_cast<Instruction>(V); | ||||
| 6587 | // If it's safe to speculatively execute, then it should not have side | ||||
| 6588 | // effects; therefore, it's safe to sink and possibly *not* execute. | ||||
| 6589 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && | ||||
| 6590 | TTI->getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency) >= | ||||
| 6591 | TargetTransformInfo::TCC_Expensive; | ||||
| 6592 | } | ||||
| 6593 | |||||
| 6594 | /// Returns true if a SelectInst should be turned into an explicit branch. | ||||
| 6595 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, | ||||
| 6596 | const TargetLowering *TLI, | ||||
| 6597 | SelectInst *SI) { | ||||
| 6598 | // If even a predictable select is cheap, then a branch can't be cheaper. | ||||
| 6599 | if (!TLI->isPredictableSelectExpensive()) | ||||
| 6600 | return false; | ||||
| 6601 | |||||
| 6602 | // FIXME: This should use the same heuristics as IfConversion to determine | ||||
| 6603 | // whether a select is better represented as a branch. | ||||
| 6604 | |||||
| 6605 | // If metadata tells us that the select condition is obviously predictable, | ||||
| 6606 | // then we want to replace the select with a branch. | ||||
| 6607 | uint64_t TrueWeight, FalseWeight; | ||||
| 6608 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { | ||||
| 6609 | uint64_t Max = std::max(TrueWeight, FalseWeight); | ||||
| 6610 | uint64_t Sum = TrueWeight + FalseWeight; | ||||
| 6611 | if (Sum != 0) { | ||||
| 6612 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); | ||||
| 6613 | if (Probability > TTI->getPredictableBranchThreshold()) | ||||
| 6614 | return true; | ||||
| 6615 | } | ||||
| 6616 | } | ||||
| 6617 | |||||
| 6618 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); | ||||
| 6619 | |||||
| 6620 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its | ||||
| 6621 | // comparison condition. If the compare has more than one use, there's | ||||
| 6622 | // probably another cmov or setcc around, so it's not worth emitting a branch. | ||||
| 6623 | if (!Cmp || !Cmp->hasOneUse()) | ||||
| 6624 | return false; | ||||
| 6625 | |||||
| 6626 | // If either operand of the select is expensive and only needed on one side | ||||
| 6627 | // of the select, we should form a branch. | ||||
| 6628 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || | ||||
| 6629 | sinkSelectOperand(TTI, SI->getFalseValue())) | ||||
| 6630 | return true; | ||||
| 6631 | |||||
| 6632 | return false; | ||||
| 6633 | } | ||||
| 6634 | |||||
| 6635 | /// If \p isTrue is true, return the true value of \p SI, otherwise return | ||||
| 6636 | /// false value of \p SI. If the true/false value of \p SI is defined by any | ||||
| 6637 | /// select instructions in \p Selects, look through the defining select | ||||
| 6638 | /// instruction until the true/false value is not defined in \p Selects. | ||||
| 6639 | static Value *getTrueOrFalseValue( | ||||
| 6640 | SelectInst *SI, bool isTrue, | ||||
| 6641 | const SmallPtrSet<const Instruction *, 2> &Selects) { | ||||
| 6642 | Value *V = nullptr; | ||||
| 6643 | |||||
| 6644 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); | ||||
| 6645 | DefSI = dyn_cast<SelectInst>(V)) { | ||||
| 6646 | assert(DefSI->getCondition() == SI->getCondition() &&((void)0) | ||||
| 6647 | "The condition of DefSI does not match with SI")((void)0); | ||||
| 6648 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); | ||||
| 6649 | } | ||||
| 6650 | |||||
| 6651 | assert(V && "Failed to get select true/false value")((void)0); | ||||
| 6652 | return V; | ||||
| 6653 | } | ||||
| 6654 | |||||
| 6655 | bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) { | ||||
| 6656 | assert(Shift->isShift() && "Expected a shift")((void)0); | ||||
| 6657 | |||||
| 6658 | // If this is (1) a vector shift, (2) shifts by scalars are cheaper than | ||||
| 6659 | // general vector shifts, and (3) the shift amount is a select-of-splatted | ||||
| 6660 | // values, hoist the shifts before the select: | ||||
| 6661 | // shift Op0, (select Cond, TVal, FVal) --> | ||||
| 6662 | // select Cond, (shift Op0, TVal), (shift Op0, FVal) | ||||
| 6663 | // | ||||
| 6664 | // This is inverting a generic IR transform when we know that the cost of a | ||||
| 6665 | // general vector shift is more than the cost of 2 shift-by-scalars. | ||||
| 6666 | // We can't do this effectively in SDAG because we may not be able to | ||||
| 6667 | // determine if the select operands are splats from within a basic block. | ||||
| 6668 | Type *Ty = Shift->getType(); | ||||
| 6669 | if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) | ||||
| 6670 | return false; | ||||
| 6671 | Value *Cond, *TVal, *FVal; | ||||
| 6672 | if (!match(Shift->getOperand(1), | ||||
| 6673 | m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) | ||||
| 6674 | return false; | ||||
| 6675 | if (!isSplatValue(TVal) || !isSplatValue(FVal)) | ||||
| 6676 | return false; | ||||
| 6677 | |||||
| 6678 | IRBuilder<> Builder(Shift); | ||||
| 6679 | BinaryOperator::BinaryOps Opcode = Shift->getOpcode(); | ||||
| 6680 | Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal); | ||||
| 6681 | Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal); | ||||
| 6682 | Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); | ||||
| 6683 | Shift->replaceAllUsesWith(NewSel); | ||||
| 6684 | Shift->eraseFromParent(); | ||||
| 6685 | return true; | ||||
| 6686 | } | ||||
| 6687 | |||||
| 6688 | bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) { | ||||
| 6689 | Intrinsic::ID Opcode = Fsh->getIntrinsicID(); | ||||
| 6690 | assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&((void)0) | ||||
| 6691 | "Expected a funnel shift")((void)0); | ||||
| 6692 | |||||
| 6693 | // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper | ||||
| 6694 | // than general vector shifts, and (3) the shift amount is select-of-splatted | ||||
| 6695 | // values, hoist the funnel shifts before the select: | ||||
| 6696 | // fsh Op0, Op1, (select Cond, TVal, FVal) --> | ||||
| 6697 | // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal) | ||||
| 6698 | // | ||||
| 6699 | // This is inverting a generic IR transform when we know that the cost of a | ||||
| 6700 | // general vector shift is more than the cost of 2 shift-by-scalars. | ||||
| 6701 | // We can't do this effectively in SDAG because we may not be able to | ||||
| 6702 | // determine if the select operands are splats from within a basic block. | ||||
| 6703 | Type *Ty = Fsh->getType(); | ||||
| 6704 | if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) | ||||
| 6705 | return false; | ||||
| 6706 | Value *Cond, *TVal, *FVal; | ||||
| 6707 | if (!match(Fsh->getOperand(2), | ||||
| 6708 | m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) | ||||
| 6709 | return false; | ||||
| 6710 | if (!isSplatValue(TVal) || !isSplatValue(FVal)) | ||||
| 6711 | return false; | ||||
| 6712 | |||||
| 6713 | IRBuilder<> Builder(Fsh); | ||||
| 6714 | Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1); | ||||
| 6715 | Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, TVal }); | ||||
| 6716 | Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, FVal }); | ||||
| 6717 | Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); | ||||
| 6718 | Fsh->replaceAllUsesWith(NewSel); | ||||
| 6719 | Fsh->eraseFromParent(); | ||||
| 6720 | return true; | ||||
| 6721 | } | ||||
| 6722 | |||||
| 6723 | /// If we have a SelectInst that will likely profit from branch prediction, | ||||
| 6724 | /// turn it into a branch. | ||||
| 6725 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { | ||||
| 6726 | if (DisableSelectToBranch) | ||||
| 6727 | return false; | ||||
| 6728 | |||||
| 6729 | // Find all consecutive select instructions that share the same condition. | ||||
| 6730 | SmallVector<SelectInst *, 2> ASI; | ||||
| 6731 | ASI.push_back(SI); | ||||
| 6732 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); | ||||
| 6733 | It != SI->getParent()->end(); ++It) { | ||||
| 6734 | SelectInst *I = dyn_cast<SelectInst>(&*It); | ||||
| 6735 | if (I && SI->getCondition() == I->getCondition()) { | ||||
| 6736 | ASI.push_back(I); | ||||
| 6737 | } else { | ||||
| 6738 | break; | ||||
| 6739 | } | ||||
| 6740 | } | ||||
| 6741 | |||||
| 6742 | SelectInst *LastSI = ASI.back(); | ||||
| 6743 | // Increment the current iterator to skip all the rest of select instructions | ||||
| 6744 | // because they will be either "not lowered" or "all lowered" to branch. | ||||
| 6745 | CurInstIterator = std::next(LastSI->getIterator()); | ||||
| 6746 | |||||
| 6747 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); | ||||
| 6748 | |||||
| 6749 | // Can we convert the 'select' to CF ? | ||||
| 6750 | if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable)) | ||||
| 6751 | return false; | ||||
| 6752 | |||||
| 6753 | TargetLowering::SelectSupportKind SelectKind; | ||||
| 6754 | if (VectorCond) | ||||
| 6755 | SelectKind = TargetLowering::VectorMaskSelect; | ||||
| 6756 | else if (SI->getType()->isVectorTy()) | ||||
| 6757 | SelectKind = TargetLowering::ScalarCondVectorVal; | ||||
| 6758 | else | ||||
| 6759 | SelectKind = TargetLowering::ScalarValSelect; | ||||
| 6760 | |||||
| 6761 | if (TLI->isSelectSupported(SelectKind) && | ||||
| 6762 | (!isFormingBranchFromSelectProfitable(TTI, TLI, SI) || OptSize || | ||||
| 6763 | llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI.get()))) | ||||
| 6764 | return false; | ||||
| 6765 | |||||
| 6766 | // The DominatorTree needs to be rebuilt by any consumers after this | ||||
| 6767 | // transformation. We simply reset here rather than setting the ModifiedDT | ||||
| 6768 | // flag to avoid restarting the function walk in runOnFunction for each | ||||
| 6769 | // select optimized. | ||||
| 6770 | DT.reset(); | ||||
| 6771 | |||||
| 6772 | // Transform a sequence like this: | ||||
| 6773 | // start: | ||||
| 6774 | // %cmp = cmp uge i32 %a, %b | ||||
| 6775 | // %sel = select i1 %cmp, i32 %c, i32 %d | ||||
| 6776 | // | ||||
| 6777 | // Into: | ||||
| 6778 | // start: | ||||
| 6779 | // %cmp = cmp uge i32 %a, %b | ||||
| 6780 | // %cmp.frozen = freeze %cmp | ||||
| 6781 | // br i1 %cmp.frozen, label %select.true, label %select.false | ||||
| 6782 | // select.true: | ||||
| 6783 | // br label %select.end | ||||
| 6784 | // select.false: | ||||
| 6785 | // br label %select.end | ||||
| 6786 | // select.end: | ||||
| 6787 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] | ||||
| 6788 | // | ||||
| 6789 | // %cmp should be frozen, otherwise it may introduce undefined behavior. | ||||
| 6790 | // In addition, we may sink instructions that produce %c or %d from | ||||
| 6791 | // the entry block into the destination(s) of the new branch. | ||||
| 6792 | // If the true or false blocks do not contain a sunken instruction, that | ||||
| 6793 | // block and its branch may be optimized away. In that case, one side of the | ||||
| 6794 | // first branch will point directly to select.end, and the corresponding PHI | ||||
| 6795 | // predecessor block will be the start block. | ||||
| 6796 | |||||
| 6797 | // First, we split the block containing the select into 2 blocks. | ||||
| 6798 | BasicBlock *StartBlock = SI->getParent(); | ||||
| 6799 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); | ||||
| 6800 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); | ||||
| 6801 | BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock).getFrequency()); | ||||
| 6802 | |||||
| 6803 | // Delete the unconditional branch that was just created by the split. | ||||
| 6804 | StartBlock->getTerminator()->eraseFromParent(); | ||||
| 6805 | |||||
| 6806 | // These are the new basic blocks for the conditional branch. | ||||
| 6807 | // At least one will become an actual new basic block. | ||||
| 6808 | BasicBlock *TrueBlock = nullptr; | ||||
| 6809 | BasicBlock *FalseBlock = nullptr; | ||||
| 6810 | BranchInst *TrueBranch = nullptr; | ||||
| 6811 | BranchInst *FalseBranch = nullptr; | ||||
| 6812 | |||||
| 6813 | // Sink expensive instructions into the conditional blocks to avoid executing | ||||
| 6814 | // them speculatively. | ||||
| 6815 | for (SelectInst *SI : ASI) { | ||||
| 6816 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { | ||||
| 6817 | if (TrueBlock == nullptr) { | ||||
| 6818 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", | ||||
| 6819 | EndBlock->getParent(), EndBlock); | ||||
| 6820 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); | ||||
| 6821 | TrueBranch->setDebugLoc(SI->getDebugLoc()); | ||||
| 6822 | } | ||||
| 6823 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); | ||||
| 6824 | TrueInst->moveBefore(TrueBranch); | ||||
| 6825 | } | ||||
| 6826 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { | ||||
| 6827 | if (FalseBlock == nullptr) { | ||||
| 6828 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", | ||||
| 6829 | EndBlock->getParent(), EndBlock); | ||||
| 6830 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); | ||||
| 6831 | FalseBranch->setDebugLoc(SI->getDebugLoc()); | ||||
| 6832 | } | ||||
| 6833 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); | ||||
| 6834 | FalseInst->moveBefore(FalseBranch); | ||||
| 6835 | } | ||||
| 6836 | } | ||||
| 6837 | |||||
| 6838 | // If there was nothing to sink, then arbitrarily choose the 'false' side | ||||
| 6839 | // for a new input value to the PHI. | ||||
| 6840 | if (TrueBlock == FalseBlock) { | ||||
| 6841 | assert(TrueBlock == nullptr &&((void)0) | ||||
| 6842 | "Unexpected basic block transform while optimizing select")((void)0); | ||||
| 6843 | |||||
| 6844 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", | ||||
| 6845 | EndBlock->getParent(), EndBlock); | ||||
| 6846 | auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); | ||||
| 6847 | FalseBranch->setDebugLoc(SI->getDebugLoc()); | ||||
| 6848 | } | ||||
| 6849 | |||||
| 6850 | // Insert the real conditional branch based on the original condition. | ||||
| 6851 | // If we did not create a new block for one of the 'true' or 'false' paths | ||||
| 6852 | // of the condition, it means that side of the branch goes to the end block | ||||
| 6853 | // directly and the path originates from the start block from the point of | ||||
| 6854 | // view of the new PHI. | ||||
| 6855 | BasicBlock *TT, *FT; | ||||
| 6856 | if (TrueBlock == nullptr) { | ||||
| 6857 | TT = EndBlock; | ||||
| 6858 | FT = FalseBlock; | ||||
| 6859 | TrueBlock = StartBlock; | ||||
| 6860 | } else if (FalseBlock == nullptr) { | ||||
| 6861 | TT = TrueBlock; | ||||
| 6862 | FT = EndBlock; | ||||
| 6863 | FalseBlock = StartBlock; | ||||
| 6864 | } else { | ||||
| 6865 | TT = TrueBlock; | ||||
| 6866 | FT = FalseBlock; | ||||
| 6867 | } | ||||
| 6868 | IRBuilder<> IB(SI); | ||||
| 6869 | auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen"); | ||||
| 6870 | IB.CreateCondBr(CondFr, TT, FT, SI); | ||||
| 6871 | |||||
| 6872 | SmallPtrSet<const Instruction *, 2> INS; | ||||
| 6873 | INS.insert(ASI.begin(), ASI.end()); | ||||
| 6874 | // Use reverse iterator because later select may use the value of the | ||||
| 6875 | // earlier select, and we need to propagate value through earlier select | ||||
| 6876 | // to get the PHI operand. | ||||
| 6877 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { | ||||
| 6878 | SelectInst *SI = *It; | ||||
| 6879 | // The select itself is replaced with a PHI Node. | ||||
| 6880 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); | ||||
| 6881 | PN->takeName(SI); | ||||
| 6882 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); | ||||
| 6883 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); | ||||
| 6884 | PN->setDebugLoc(SI->getDebugLoc()); | ||||
| 6885 | |||||
| 6886 | SI->replaceAllUsesWith(PN); | ||||
| 6887 | SI->eraseFromParent(); | ||||
| 6888 | INS.erase(SI); | ||||
| 6889 | ++NumSelectsExpanded; | ||||
| 6890 | } | ||||
| 6891 | |||||
| 6892 | // Instruct OptimizeBlock to skip to the next block. | ||||
| 6893 | CurInstIterator = StartBlock->end(); | ||||
| 6894 | return true; | ||||
| 6895 | } | ||||
| 6896 | |||||
| 6897 | /// Some targets only accept certain types for splat inputs. For example a VDUP | ||||
| 6898 | /// in MVE takes a GPR (integer) register, and the instruction that incorporate | ||||
| 6899 | /// a VDUP (such as a VADD qd, qm, rm) also require a gpr register. | ||||
| 6900 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { | ||||
| 6901 | // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only | ||||
| 6902 | if (!match(SVI, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), | ||||
| 6903 | m_Undef(), m_ZeroMask()))) | ||||
| 6904 | return false; | ||||
| 6905 | Type *NewType = TLI->shouldConvertSplatType(SVI); | ||||
| 6906 | if (!NewType) | ||||
| 6907 | return false; | ||||
| 6908 | |||||
| 6909 | auto *SVIVecType = cast<FixedVectorType>(SVI->getType()); | ||||
| 6910 | assert(!NewType->isVectorTy() && "Expected a scalar type!")((void)0); | ||||
| 6911 | assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&((void)0) | ||||
| 6912 | "Expected a type of the same size!")((void)0); | ||||
| 6913 | auto *NewVecType = | ||||
| 6914 | FixedVectorType::get(NewType, SVIVecType->getNumElements()); | ||||
| 6915 | |||||
| 6916 | // Create a bitcast (shuffle (insert (bitcast(..)))) | ||||
| 6917 | IRBuilder<> Builder(SVI->getContext()); | ||||
| 6918 | Builder.SetInsertPoint(SVI); | ||||
| 6919 | Value *BC1 = Builder.CreateBitCast( | ||||
| 6920 | cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType); | ||||
| 6921 | Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1); | ||||
| 6922 | Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType); | ||||
| 6923 | |||||
| 6924 | SVI->replaceAllUsesWith(BC2); | ||||
| 6925 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
| 6926 | SVI, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
| 6927 | |||||
| 6928 | // Also hoist the bitcast up to its operand if it they are not in the same | ||||
| 6929 | // block. | ||||
| 6930 | if (auto *BCI = dyn_cast<Instruction>(BC1)) | ||||
| 6931 | if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0))) | ||||
| 6932 | if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) && | ||||
| 6933 | !Op->isTerminator() && !Op->isEHPad()) | ||||
| 6934 | BCI->moveAfter(Op); | ||||
| 6935 | |||||
| 6936 | return true; | ||||
| 6937 | } | ||||
| 6938 | |||||
| 6939 | bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) { | ||||
| 6940 | // If the operands of I can be folded into a target instruction together with | ||||
| 6941 | // I, duplicate and sink them. | ||||
| 6942 | SmallVector<Use *, 4> OpsToSink; | ||||
| 6943 | if (!TLI->shouldSinkOperands(I, OpsToSink)) | ||||
| 6944 | return false; | ||||
| 6945 | |||||
| 6946 | // OpsToSink can contain multiple uses in a use chain (e.g. | ||||
| 6947 | // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating | ||||
| 6948 | // uses must come first, so we process the ops in reverse order so as to not | ||||
| 6949 | // create invalid IR. | ||||
| 6950 | BasicBlock *TargetBB = I->getParent(); | ||||
| 6951 | bool Changed = false; | ||||
| 6952 | SmallVector<Use *, 4> ToReplace; | ||||
| 6953 | for (Use *U : reverse(OpsToSink)) { | ||||
| 6954 | auto *UI = cast<Instruction>(U->get()); | ||||
| 6955 | if (UI->getParent() == TargetBB || isa<PHINode>(UI)) | ||||
| 6956 | continue; | ||||
| 6957 | ToReplace.push_back(U); | ||||
| 6958 | } | ||||
| 6959 | |||||
| 6960 | SetVector<Instruction *> MaybeDead; | ||||
| 6961 | DenseMap<Instruction *, Instruction *> NewInstructions; | ||||
| 6962 | Instruction *InsertPoint = I; | ||||
| 6963 | for (Use *U : ToReplace) { | ||||
| 6964 | auto *UI = cast<Instruction>(U->get()); | ||||
| 6965 | Instruction *NI = UI->clone(); | ||||
| 6966 | NewInstructions[UI] = NI; | ||||
| 6967 | MaybeDead.insert(UI); | ||||
| 6968 | LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n")do { } while (false); | ||||
| 6969 | NI->insertBefore(InsertPoint); | ||||
| 6970 | InsertPoint = NI; | ||||
| 6971 | InsertedInsts.insert(NI); | ||||
| 6972 | |||||
| 6973 | // Update the use for the new instruction, making sure that we update the | ||||
| 6974 | // sunk instruction uses, if it is part of a chain that has already been | ||||
| 6975 | // sunk. | ||||
| 6976 | Instruction *OldI = cast<Instruction>(U->getUser()); | ||||
| 6977 | if (NewInstructions.count(OldI)) | ||||
| 6978 | NewInstructions[OldI]->setOperand(U->getOperandNo(), NI); | ||||
| 6979 | else | ||||
| 6980 | U->set(NI); | ||||
| 6981 | Changed = true; | ||||
| 6982 | } | ||||
| 6983 | |||||
| 6984 | // Remove instructions that are dead after sinking. | ||||
| 6985 | for (auto *I : MaybeDead) { | ||||
| 6986 | if (!I->hasNUsesOrMore(1)) { | ||||
| 6987 | LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n")do { } while (false); | ||||
| 6988 | I->eraseFromParent(); | ||||
| 6989 | } | ||||
| 6990 | } | ||||
| 6991 | |||||
| 6992 | return Changed; | ||||
| 6993 | } | ||||
| 6994 | |||||
| 6995 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { | ||||
| 6996 | Value *Cond = SI->getCondition(); | ||||
| 6997 | Type *OldType = Cond->getType(); | ||||
| 6998 | LLVMContext &Context = Cond->getContext(); | ||||
| 6999 | EVT OldVT = TLI->getValueType(*DL, OldType); | ||||
| 7000 | MVT RegType = TLI->getRegisterType(Context, OldVT); | ||||
| 7001 | unsigned RegWidth = RegType.getSizeInBits(); | ||||
| 7002 | |||||
| 7003 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) | ||||
| 7004 | return false; | ||||
| 7005 | |||||
| 7006 | // If the register width is greater than the type width, expand the condition | ||||
| 7007 | // of the switch instruction and each case constant to the width of the | ||||
| 7008 | // register. By widening the type of the switch condition, subsequent | ||||
| 7009 | // comparisons (for case comparisons) will not need to be extended to the | ||||
| 7010 | // preferred register width, so we will potentially eliminate N-1 extends, | ||||
| 7011 | // where N is the number of cases in the switch. | ||||
| 7012 | auto *NewType = Type::getIntNTy(Context, RegWidth); | ||||
| 7013 | |||||
| 7014 | // Extend the switch condition and case constants using the target preferred | ||||
| 7015 | // extend unless the switch condition is a function argument with an extend | ||||
| 7016 | // attribute. In that case, we can avoid an unnecessary mask/extension by | ||||
| 7017 | // matching the argument extension instead. | ||||
| 7018 | Instruction::CastOps ExtType = Instruction::ZExt; | ||||
| 7019 | // Some targets prefer SExt over ZExt. | ||||
| 7020 | if (TLI->isSExtCheaperThanZExt(OldVT, RegType)) | ||||
| 7021 | ExtType = Instruction::SExt; | ||||
| 7022 | |||||
| 7023 | if (auto *Arg = dyn_cast<Argument>(Cond)) { | ||||
| 7024 | if (Arg->hasSExtAttr()) | ||||
| 7025 | ExtType = Instruction::SExt; | ||||
| 7026 | if (Arg->hasZExtAttr()) | ||||
| 7027 | ExtType = Instruction::ZExt; | ||||
| 7028 | } | ||||
| 7029 | |||||
| 7030 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); | ||||
| 7031 | ExtInst->insertBefore(SI); | ||||
| 7032 | ExtInst->setDebugLoc(SI->getDebugLoc()); | ||||
| 7033 | SI->setCondition(ExtInst); | ||||
| 7034 | for (auto Case : SI->cases()) { | ||||
| 7035 | APInt NarrowConst = Case.getCaseValue()->getValue(); | ||||
| 7036 | APInt WideConst = (ExtType == Instruction::ZExt) ? | ||||
| 7037 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); | ||||
| 7038 | Case.setValue(ConstantInt::get(Context, WideConst)); | ||||
| 7039 | } | ||||
| 7040 | |||||
| 7041 | return true; | ||||
| 7042 | } | ||||
| 7043 | |||||
| 7044 | |||||
| 7045 | namespace { | ||||
| 7046 | |||||
| 7047 | /// Helper class to promote a scalar operation to a vector one. | ||||
| 7048 | /// This class is used to move downward extractelement transition. | ||||
| 7049 | /// E.g., | ||||
| 7050 | /// a = vector_op <2 x i32> | ||||
| 7051 | /// b = extractelement <2 x i32> a, i32 0 | ||||
| 7052 | /// c = scalar_op b | ||||
| 7053 | /// store c | ||||
| 7054 | /// | ||||
| 7055 | /// => | ||||
| 7056 | /// a = vector_op <2 x i32> | ||||
| 7057 | /// c = vector_op a (equivalent to scalar_op on the related lane) | ||||
| 7058 | /// * d = extractelement <2 x i32> c, i32 0 | ||||
| 7059 | /// * store d | ||||
| 7060 | /// Assuming both extractelement and store can be combine, we get rid of the | ||||
| 7061 | /// transition. | ||||
| 7062 | class VectorPromoteHelper { | ||||
| 7063 | /// DataLayout associated with the current module. | ||||
| 7064 | const DataLayout &DL; | ||||
| 7065 | |||||
| 7066 | /// Used to perform some checks on the legality of vector operations. | ||||
| 7067 | const TargetLowering &TLI; | ||||
| 7068 | |||||
| 7069 | /// Used to estimated the cost of the promoted chain. | ||||
| 7070 | const TargetTransformInfo &TTI; | ||||
| 7071 | |||||
| 7072 | /// The transition being moved downwards. | ||||
| 7073 | Instruction *Transition; | ||||
| 7074 | |||||
| 7075 | /// The sequence of instructions to be promoted. | ||||
| 7076 | SmallVector<Instruction *, 4> InstsToBePromoted; | ||||
| 7077 | |||||
| 7078 | /// Cost of combining a store and an extract. | ||||
| 7079 | unsigned StoreExtractCombineCost; | ||||
| 7080 | |||||
| 7081 | /// Instruction that will be combined with the transition. | ||||
| 7082 | Instruction *CombineInst = nullptr; | ||||
| 7083 | |||||
| 7084 | /// The instruction that represents the current end of the transition. | ||||
| 7085 | /// Since we are faking the promotion until we reach the end of the chain | ||||
| 7086 | /// of computation, we need a way to get the current end of the transition. | ||||
| 7087 | Instruction *getEndOfTransition() const { | ||||
| 7088 | if (InstsToBePromoted.empty()) | ||||
| 7089 | return Transition; | ||||
| 7090 | return InstsToBePromoted.back(); | ||||
| 7091 | } | ||||
| 7092 | |||||
| 7093 | /// Return the index of the original value in the transition. | ||||
| 7094 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, | ||||
| 7095 | /// c, is at index 0. | ||||
| 7096 | unsigned getTransitionOriginalValueIdx() const { | ||||
| 7097 | assert(isa<ExtractElementInst>(Transition) &&((void)0) | ||||
| 7098 | "Other kind of transitions are not supported yet")((void)0); | ||||
| 7099 | return 0; | ||||
| 7100 | } | ||||
| 7101 | |||||
| 7102 | /// Return the index of the index in the transition. | ||||
| 7103 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index | ||||
| 7104 | /// is at index 1. | ||||
| 7105 | unsigned getTransitionIdx() const { | ||||
| 7106 | assert(isa<ExtractElementInst>(Transition) &&((void)0) | ||||
| 7107 | "Other kind of transitions are not supported yet")((void)0); | ||||
| 7108 | return 1; | ||||
| 7109 | } | ||||
| 7110 | |||||
| 7111 | /// Get the type of the transition. | ||||
| 7112 | /// This is the type of the original value. | ||||
| 7113 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the | ||||
| 7114 | /// transition is <2 x i32>. | ||||
| 7115 | Type *getTransitionType() const { | ||||
| 7116 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); | ||||
| 7117 | } | ||||
| 7118 | |||||
| 7119 | /// Promote \p ToBePromoted by moving \p Def downward through. | ||||
| 7120 | /// I.e., we have the following sequence: | ||||
| 7121 | /// Def = Transition <ty1> a to <ty2> | ||||
| 7122 | /// b = ToBePromoted <ty2> Def, ... | ||||
| 7123 | /// => | ||||
| 7124 | /// b = ToBePromoted <ty1> a, ... | ||||
| 7125 | /// Def = Transition <ty1> ToBePromoted to <ty2> | ||||
| 7126 | void promoteImpl(Instruction *ToBePromoted); | ||||
| 7127 | |||||
| 7128 | /// Check whether or not it is profitable to promote all the | ||||
| 7129 | /// instructions enqueued to be promoted. | ||||
| 7130 | bool isProfitableToPromote() { | ||||
| 7131 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); | ||||
| 7132 | unsigned Index = isa<ConstantInt>(ValIdx) | ||||
| 7133 | ? cast<ConstantInt>(ValIdx)->getZExtValue() | ||||
| 7134 | : -1; | ||||
| 7135 | Type *PromotedType = getTransitionType(); | ||||
| 7136 | |||||
| 7137 | StoreInst *ST = cast<StoreInst>(CombineInst); | ||||
| 7138 | unsigned AS = ST->getPointerAddressSpace(); | ||||
| 7139 | // Check if this store is supported. | ||||
| 7140 | if (!TLI.allowsMisalignedMemoryAccesses( | ||||
| 7141 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, | ||||
| 7142 | ST->getAlign())) { | ||||
| 7143 | // If this is not supported, there is no way we can combine | ||||
| 7144 | // the extract with the store. | ||||
| 7145 | return false; | ||||
| 7146 | } | ||||
| 7147 | |||||
| 7148 | // The scalar chain of computation has to pay for the transition | ||||
| 7149 | // scalar to vector. | ||||
| 7150 | // The vector chain has to account for the combining cost. | ||||
| 7151 | InstructionCost ScalarCost = | ||||
| 7152 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); | ||||
| 7153 | InstructionCost VectorCost = StoreExtractCombineCost; | ||||
| 7154 | enum TargetTransformInfo::TargetCostKind CostKind = | ||||
| 7155 | TargetTransformInfo::TCK_RecipThroughput; | ||||
| 7156 | for (const auto &Inst : InstsToBePromoted) { | ||||
| 7157 | // Compute the cost. | ||||
| 7158 | // By construction, all instructions being promoted are arithmetic ones. | ||||
| 7159 | // Moreover, one argument is a constant that can be viewed as a splat | ||||
| 7160 | // constant. | ||||
| 7161 | Value *Arg0 = Inst->getOperand(0); | ||||
| 7162 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || | ||||
| 7163 | isa<ConstantFP>(Arg0); | ||||
| 7164 | TargetTransformInfo::OperandValueKind Arg0OVK = | ||||
| 7165 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue | ||||
| 7166 | : TargetTransformInfo::OK_AnyValue; | ||||
| 7167 | TargetTransformInfo::OperandValueKind Arg1OVK = | ||||
| 7168 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue | ||||
| 7169 | : TargetTransformInfo::OK_AnyValue; | ||||
| 7170 | ScalarCost += TTI.getArithmeticInstrCost( | ||||
| 7171 | Inst->getOpcode(), Inst->getType(), CostKind, Arg0OVK, Arg1OVK); | ||||
| 7172 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, | ||||
| 7173 | CostKind, | ||||
| 7174 | Arg0OVK, Arg1OVK); | ||||
| 7175 | } | ||||
| 7176 | LLVM_DEBUG(do { } while (false) | ||||
| 7177 | dbgs() << "Estimated cost of computation to be promoted:\nScalar: "do { } while (false) | ||||
| 7178 | << ScalarCost << "\nVector: " << VectorCost << '\n')do { } while (false); | ||||
| 7179 | return ScalarCost > VectorCost; | ||||
| 7180 | } | ||||
| 7181 | |||||
| 7182 | /// Generate a constant vector with \p Val with the same | ||||
| 7183 | /// number of elements as the transition. | ||||
| 7184 | /// \p UseSplat defines whether or not \p Val should be replicated | ||||
| 7185 | /// across the whole vector. | ||||
| 7186 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, | ||||
| 7187 | /// otherwise we generate a vector with as many undef as possible: | ||||
| 7188 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only | ||||
| 7189 | /// used at the index of the extract. | ||||
| 7190 | Value *getConstantVector(Constant *Val, bool UseSplat) const { | ||||
| 7191 | unsigned ExtractIdx = std::numeric_limits<unsigned>::max(); | ||||
| 7192 | if (!UseSplat) { | ||||
| 7193 | // If we cannot determine where the constant must be, we have to | ||||
| 7194 | // use a splat constant. | ||||
| 7195 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); | ||||
| 7196 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) | ||||
| 7197 | ExtractIdx = CstVal->getSExtValue(); | ||||
| 7198 | else | ||||
| 7199 | UseSplat = true; | ||||
| 7200 | } | ||||
| 7201 | |||||
| 7202 | ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount(); | ||||
| 7203 | if (UseSplat) | ||||
| 7204 | return ConstantVector::getSplat(EC, Val); | ||||
| 7205 | |||||
| 7206 | if (!EC.isScalable()) { | ||||
| 7207 | SmallVector<Constant *, 4> ConstVec; | ||||
| 7208 | UndefValue *UndefVal = UndefValue::get(Val->getType()); | ||||
| 7209 | for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) { | ||||
| 7210 | if (Idx == ExtractIdx) | ||||
| 7211 | ConstVec.push_back(Val); | ||||
| 7212 | else | ||||
| 7213 | ConstVec.push_back(UndefVal); | ||||
| 7214 | } | ||||
| 7215 | return ConstantVector::get(ConstVec); | ||||
| 7216 | } else | ||||
| 7217 | llvm_unreachable(__builtin_unreachable() | ||||
| 7218 | "Generate scalable vector for non-splat is unimplemented")__builtin_unreachable(); | ||||
| 7219 | } | ||||
| 7220 | |||||
| 7221 | /// Check if promoting to a vector type an operand at \p OperandIdx | ||||
| 7222 | /// in \p Use can trigger undefined behavior. | ||||
| 7223 | static bool canCauseUndefinedBehavior(const Instruction *Use, | ||||
| 7224 | unsigned OperandIdx) { | ||||
| 7225 | // This is not safe to introduce undef when the operand is on | ||||
| 7226 | // the right hand side of a division-like instruction. | ||||
| 7227 | if (OperandIdx != 1) | ||||
| 7228 | return false; | ||||
| 7229 | switch (Use->getOpcode()) { | ||||
| 7230 | default: | ||||
| 7231 | return false; | ||||
| 7232 | case Instruction::SDiv: | ||||
| 7233 | case Instruction::UDiv: | ||||
| 7234 | case Instruction::SRem: | ||||
| 7235 | case Instruction::URem: | ||||
| 7236 | return true; | ||||
| 7237 | case Instruction::FDiv: | ||||
| 7238 | case Instruction::FRem: | ||||
| 7239 | return !Use->hasNoNaNs(); | ||||
| 7240 | } | ||||
| 7241 | llvm_unreachable(nullptr)__builtin_unreachable(); | ||||
| 7242 | } | ||||
| 7243 | |||||
| 7244 | public: | ||||
| 7245 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, | ||||
| 7246 | const TargetTransformInfo &TTI, Instruction *Transition, | ||||
| 7247 | unsigned CombineCost) | ||||
| 7248 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), | ||||
| 7249 | StoreExtractCombineCost(CombineCost) { | ||||
| 7250 | assert(Transition && "Do not know how to promote null")((void)0); | ||||
| 7251 | } | ||||
| 7252 | |||||
| 7253 | /// Check if we can promote \p ToBePromoted to \p Type. | ||||
| 7254 | bool canPromote(const Instruction *ToBePromoted) const { | ||||
| 7255 | // We could support CastInst too. | ||||
| 7256 | return isa<BinaryOperator>(ToBePromoted); | ||||
| 7257 | } | ||||
| 7258 | |||||
| 7259 | /// Check if it is profitable to promote \p ToBePromoted | ||||
| 7260 | /// by moving downward the transition through. | ||||
| 7261 | bool shouldPromote(const Instruction *ToBePromoted) const { | ||||
| 7262 | // Promote only if all the operands can be statically expanded. | ||||
| 7263 | // Indeed, we do not want to introduce any new kind of transitions. | ||||
| 7264 | for (const Use &U : ToBePromoted->operands()) { | ||||
| 7265 | const Value *Val = U.get(); | ||||
| 7266 | if (Val == getEndOfTransition()) { | ||||
| 7267 | // If the use is a division and the transition is on the rhs, | ||||
| 7268 | // we cannot promote the operation, otherwise we may create a | ||||
| 7269 | // division by zero. | ||||
| 7270 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) | ||||
| 7271 | return false; | ||||
| 7272 | continue; | ||||
| 7273 | } | ||||
| 7274 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && | ||||
| 7275 | !isa<ConstantFP>(Val)) | ||||
| 7276 | return false; | ||||
| 7277 | } | ||||
| 7278 | // Check that the resulting operation is legal. | ||||
| 7279 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); | ||||
| 7280 | if (!ISDOpcode) | ||||
| 7281 | return false; | ||||
| 7282 | return StressStoreExtract || | ||||
| 7283 | TLI.isOperationLegalOrCustom( | ||||
| 7284 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); | ||||
| 7285 | } | ||||
| 7286 | |||||
| 7287 | /// Check whether or not \p Use can be combined | ||||
| 7288 | /// with the transition. | ||||
| 7289 | /// I.e., is it possible to do Use(Transition) => AnotherUse? | ||||
| 7290 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } | ||||
| 7291 | |||||
| 7292 | /// Record \p ToBePromoted as part of the chain to be promoted. | ||||
| 7293 | void enqueueForPromotion(Instruction *ToBePromoted) { | ||||
| 7294 | InstsToBePromoted.push_back(ToBePromoted); | ||||
| 7295 | } | ||||
| 7296 | |||||
| 7297 | /// Set the instruction that will be combined with the transition. | ||||
| 7298 | void recordCombineInstruction(Instruction *ToBeCombined) { | ||||
| 7299 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine")((void)0); | ||||
| 7300 | CombineInst = ToBeCombined; | ||||
| 7301 | } | ||||
| 7302 | |||||
| 7303 | /// Promote all the instructions enqueued for promotion if it is | ||||
| 7304 | /// is profitable. | ||||
| 7305 | /// \return True if the promotion happened, false otherwise. | ||||
| 7306 | bool promote() { | ||||
| 7307 | // Check if there is something to promote. | ||||
| 7308 | // Right now, if we do not have anything to combine with, | ||||
| 7309 | // we assume the promotion is not profitable. | ||||
| 7310 | if (InstsToBePromoted.empty() || !CombineInst) | ||||
| 7311 | return false; | ||||
| 7312 | |||||
| 7313 | // Check cost. | ||||
| 7314 | if (!StressStoreExtract && !isProfitableToPromote()) | ||||
| 7315 | return false; | ||||
| 7316 | |||||
| 7317 | // Promote. | ||||
| 7318 | for (auto &ToBePromoted : InstsToBePromoted) | ||||
| 7319 | promoteImpl(ToBePromoted); | ||||
| 7320 | InstsToBePromoted.clear(); | ||||
| 7321 | return true; | ||||
| 7322 | } | ||||
| 7323 | }; | ||||
| 7324 | |||||
| 7325 | } // end anonymous namespace | ||||
| 7326 | |||||
| 7327 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { | ||||
| 7328 | // At this point, we know that all the operands of ToBePromoted but Def | ||||
| 7329 | // can be statically promoted. | ||||
| 7330 | // For Def, we need to use its parameter in ToBePromoted: | ||||
| 7331 | // b = ToBePromoted ty1 a | ||||
| 7332 | // Def = Transition ty1 b to ty2 | ||||
| 7333 | // Move the transition down. | ||||
| 7334 | // 1. Replace all uses of the promoted operation by the transition. | ||||
| 7335 | // = ... b => = ... Def. | ||||
| 7336 | assert(ToBePromoted->getType() == Transition->getType() &&((void)0) | ||||
| 7337 | "The type of the result of the transition does not match "((void)0) | ||||
| 7338 | "the final type")((void)0); | ||||
| 7339 | ToBePromoted->replaceAllUsesWith(Transition); | ||||
| 7340 | // 2. Update the type of the uses. | ||||
| 7341 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. | ||||
| 7342 | Type *TransitionTy = getTransitionType(); | ||||
| 7343 | ToBePromoted->mutateType(TransitionTy); | ||||
| 7344 | // 3. Update all the operands of the promoted operation with promoted | ||||
| 7345 | // operands. | ||||
| 7346 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. | ||||
| 7347 | for (Use &U : ToBePromoted->operands()) { | ||||
| 7348 | Value *Val = U.get(); | ||||
| 7349 | Value *NewVal = nullptr; | ||||
| 7350 | if (Val == Transition) | ||||
| 7351 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); | ||||
| 7352 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || | ||||
| 7353 | isa<ConstantFP>(Val)) { | ||||
| 7354 | // Use a splat constant if it is not safe to use undef. | ||||
| 7355 | NewVal = getConstantVector( | ||||
| 7356 | cast<Constant>(Val), | ||||
| 7357 | isa<UndefValue>(Val) || | ||||
| 7358 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); | ||||
| 7359 | } else | ||||
| 7360 | llvm_unreachable("Did you modified shouldPromote and forgot to update "__builtin_unreachable() | ||||
| 7361 | "this?")__builtin_unreachable(); | ||||
| 7362 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); | ||||
| 7363 | } | ||||
| 7364 | Transition->moveAfter(ToBePromoted); | ||||
| 7365 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); | ||||
| 7366 | } | ||||
| 7367 | |||||
| 7368 | /// Some targets can do store(extractelement) with one instruction. | ||||
| 7369 | /// Try to push the extractelement towards the stores when the target | ||||
| 7370 | /// has this feature and this is profitable. | ||||
| 7371 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { | ||||
| 7372 | unsigned CombineCost = std::numeric_limits<unsigned>::max(); | ||||
| 7373 | if (DisableStoreExtract || | ||||
| 7374 | (!StressStoreExtract && | ||||
| 7375 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), | ||||
| 7376 | Inst->getOperand(1), CombineCost))) | ||||
| 7377 | return false; | ||||
| 7378 | |||||
| 7379 | // At this point we know that Inst is a vector to scalar transition. | ||||
| 7380 | // Try to move it down the def-use chain, until: | ||||
| 7381 | // - We can combine the transition with its single use | ||||
| 7382 | // => we got rid of the transition. | ||||
| 7383 | // - We escape the current basic block | ||||
| 7384 | // => we would need to check that we are moving it at a cheaper place and | ||||
| 7385 | // we do not do that for now. | ||||
| 7386 | BasicBlock *Parent = Inst->getParent(); | ||||
| 7387 | LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n')do { } while (false); | ||||
| 7388 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); | ||||
| 7389 | // If the transition has more than one use, assume this is not going to be | ||||
| 7390 | // beneficial. | ||||
| 7391 | while (Inst->hasOneUse()) { | ||||
| 7392 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); | ||||
| 7393 | LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n')do { } while (false); | ||||
| 7394 | |||||
| 7395 | if (ToBePromoted->getParent() != Parent) { | ||||
| 7396 | LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("do { } while (false) | ||||
| 7397 | << ToBePromoted->getParent()->getName()do { } while (false) | ||||
| 7398 | << ") than the transition (" << Parent->getName()do { } while (false) | ||||
| 7399 | << ").\n")do { } while (false); | ||||
| 7400 | return false; | ||||
| 7401 | } | ||||
| 7402 | |||||
| 7403 | if (VPH.canCombine(ToBePromoted)) { | ||||
| 7404 | LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'do { } while (false) | ||||
| 7405 | << "will be combined with: " << *ToBePromoted << '\n')do { } while (false); | ||||
| 7406 | VPH.recordCombineInstruction(ToBePromoted); | ||||
| 7407 | bool Changed = VPH.promote(); | ||||
| 7408 | NumStoreExtractExposed += Changed; | ||||
| 7409 | return Changed; | ||||
| 7410 | } | ||||
| 7411 | |||||
| 7412 | LLVM_DEBUG(dbgs() << "Try promoting.\n")do { } while (false); | ||||
| 7413 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) | ||||
| 7414 | return false; | ||||
| 7415 | |||||
| 7416 | LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n")do { } while (false); | ||||
| 7417 | |||||
| 7418 | VPH.enqueueForPromotion(ToBePromoted); | ||||
| 7419 | Inst = ToBePromoted; | ||||
| 7420 | } | ||||
| 7421 | return false; | ||||
| 7422 | } | ||||
| 7423 | |||||
| 7424 | /// For the instruction sequence of store below, F and I values | ||||
| 7425 | /// are bundled together as an i64 value before being stored into memory. | ||||
| 7426 | /// Sometimes it is more efficient to generate separate stores for F and I, | ||||
| 7427 | /// which can remove the bitwise instructions or sink them to colder places. | ||||
| 7428 | /// | ||||
| 7429 | /// (store (or (zext (bitcast F to i32) to i64), | ||||
| 7430 | /// (shl (zext I to i64), 32)), addr) --> | ||||
| 7431 | /// (store F, addr) and (store I, addr+4) | ||||
| 7432 | /// | ||||
| 7433 | /// Similarly, splitting for other merged store can also be beneficial, like: | ||||
| 7434 | /// For pair of {i32, i32}, i64 store --> two i32 stores. | ||||
| 7435 | /// For pair of {i32, i16}, i64 store --> two i32 stores. | ||||
| 7436 | /// For pair of {i16, i16}, i32 store --> two i16 stores. | ||||
| 7437 | /// For pair of {i16, i8}, i32 store --> two i16 stores. | ||||
| 7438 | /// For pair of {i8, i8}, i16 store --> two i8 stores. | ||||
| 7439 | /// | ||||
| 7440 | /// We allow each target to determine specifically which kind of splitting is | ||||
| 7441 | /// supported. | ||||
| 7442 | /// | ||||
| 7443 | /// The store patterns are commonly seen from the simple code snippet below | ||||
| 7444 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. | ||||
| 7445 | /// void goo(const std::pair<int, float> &); | ||||
| 7446 | /// hoo() { | ||||
| 7447 | /// ... | ||||
| 7448 | /// goo(std::make_pair(tmp, ftmp)); | ||||
| 7449 | /// ... | ||||
| 7450 | /// } | ||||
| 7451 | /// | ||||
| 7452 | /// Although we already have similar splitting in DAG Combine, we duplicate | ||||
| 7453 | /// it in CodeGenPrepare to catch the case in which pattern is across | ||||
| 7454 | /// multiple BBs. The logic in DAG Combine is kept to catch case generated | ||||
| 7455 | /// during code expansion. | ||||
| 7456 | static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, | ||||
| 7457 | const TargetLowering &TLI) { | ||||
| 7458 | // Handle simple but common cases only. | ||||
| 7459 | Type *StoreType = SI.getValueOperand()->getType(); | ||||
| 7460 | |||||
| 7461 | // The code below assumes shifting a value by <number of bits>, | ||||
| 7462 | // whereas scalable vectors would have to be shifted by | ||||
| 7463 | // <2log(vscale) + number of bits> in order to store the | ||||
| 7464 | // low/high parts. Bailing out for now. | ||||
| 7465 | if (isa<ScalableVectorType>(StoreType)) | ||||
| 7466 | return false; | ||||
| 7467 | |||||
| 7468 | if (!DL.typeSizeEqualsStoreSize(StoreType) || | ||||
| 7469 | DL.getTypeSizeInBits(StoreType) == 0) | ||||
| 7470 | return false; | ||||
| 7471 | |||||
| 7472 | unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; | ||||
| 7473 | Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); | ||||
| 7474 | if (!DL.typeSizeEqualsStoreSize(SplitStoreType)) | ||||
| 7475 | return false; | ||||
| 7476 | |||||
| 7477 | // Don't split the store if it is volatile. | ||||
| 7478 | if (SI.isVolatile()) | ||||
| 7479 | return false; | ||||
| 7480 | |||||
| 7481 | // Match the following patterns: | ||||
| 7482 | // (store (or (zext LValue to i64), | ||||
| 7483 | // (shl (zext HValue to i64), 32)), HalfValBitSize) | ||||
| 7484 | // or | ||||
| 7485 | // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) | ||||
| 7486 | // (zext LValue to i64), | ||||
| 7487 | // Expect both operands of OR and the first operand of SHL have only | ||||
| 7488 | // one use. | ||||
| 7489 | Value *LValue, *HValue; | ||||
| 7490 | if (!match(SI.getValueOperand(), | ||||
| 7491 | m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), | ||||
| 7492 | m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), | ||||
| 7493 | m_SpecificInt(HalfValBitSize)))))) | ||||
| 7494 | return false; | ||||
| 7495 | |||||
| 7496 | // Check LValue and HValue are int with size less or equal than 32. | ||||
| 7497 | if (!LValue->getType()->isIntegerTy() || | ||||
| 7498 | DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || | ||||
| 7499 | !HValue->getType()->isIntegerTy() || | ||||
| 7500 | DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) | ||||
| 7501 | return false; | ||||
| 7502 | |||||
| 7503 | // If LValue/HValue is a bitcast instruction, use the EVT before bitcast | ||||
| 7504 | // as the input of target query. | ||||
| 7505 | auto *LBC = dyn_cast<BitCastInst>(LValue); | ||||
| 7506 | auto *HBC = dyn_cast<BitCastInst>(HValue); | ||||
| 7507 | EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) | ||||
| 7508 | : EVT::getEVT(LValue->getType()); | ||||
| 7509 | EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) | ||||
| 7510 | : EVT::getEVT(HValue->getType()); | ||||
| 7511 | if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) | ||||
| 7512 | return false; | ||||
| 7513 | |||||
| 7514 | // Start to split store. | ||||
| 7515 | IRBuilder<> Builder(SI.getContext()); | ||||
| 7516 | Builder.SetInsertPoint(&SI); | ||||
| 7517 | |||||
| 7518 | // If LValue/HValue is a bitcast in another BB, create a new one in current | ||||
| 7519 | // BB so it may be merged with the splitted stores by dag combiner. | ||||
| 7520 | if (LBC && LBC->getParent() != SI.getParent()) | ||||
| 7521 | LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); | ||||
| 7522 | if (HBC && HBC->getParent() != SI.getParent()) | ||||
| 7523 | HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); | ||||
| 7524 | |||||
| 7525 | bool IsLE = SI.getModule()->getDataLayout().isLittleEndian(); | ||||
| 7526 | auto CreateSplitStore = [&](Value *V, bool Upper) { | ||||
| 7527 | V = Builder.CreateZExtOrBitCast(V, SplitStoreType); | ||||
| 7528 | Value *Addr = Builder.CreateBitCast( | ||||
| 7529 | SI.getOperand(1), | ||||
| 7530 | SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); | ||||
| 7531 | Align Alignment = SI.getAlign(); | ||||
| 7532 | const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper); | ||||
| 7533 | if (IsOffsetStore) { | ||||
| 7534 | Addr = Builder.CreateGEP( | ||||
| 7535 | SplitStoreType, Addr, | ||||
| 7536 | ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); | ||||
| 7537 | |||||
| 7538 | // When splitting the store in half, naturally one half will retain the | ||||
| 7539 | // alignment of the original wider store, regardless of whether it was | ||||
| 7540 | // over-aligned or not, while the other will require adjustment. | ||||
| 7541 | Alignment = commonAlignment(Alignment, HalfValBitSize / 8); | ||||
| 7542 | } | ||||
| 7543 | Builder.CreateAlignedStore(V, Addr, Alignment); | ||||
| 7544 | }; | ||||
| 7545 | |||||
| 7546 | CreateSplitStore(LValue, false); | ||||
| 7547 | CreateSplitStore(HValue, true); | ||||
| 7548 | |||||
| 7549 | // Delete the old store. | ||||
| 7550 | SI.eraseFromParent(); | ||||
| 7551 | return true; | ||||
| 7552 | } | ||||
| 7553 | |||||
| 7554 | // Return true if the GEP has two operands, the first operand is of a sequential | ||||
| 7555 | // type, and the second operand is a constant. | ||||
| 7556 | static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) { | ||||
| 7557 | gep_type_iterator I = gep_type_begin(*GEP); | ||||
| 7558 | return GEP->getNumOperands() == 2 && | ||||
| 7559 | I.isSequential() && | ||||
| 7560 | isa<ConstantInt>(GEP->getOperand(1)); | ||||
| 7561 | } | ||||
| 7562 | |||||
| 7563 | // Try unmerging GEPs to reduce liveness interference (register pressure) across | ||||
| 7564 | // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks, | ||||
| 7565 | // reducing liveness interference across those edges benefits global register | ||||
| 7566 | // allocation. Currently handles only certain cases. | ||||
| 7567 | // | ||||
| 7568 | // For example, unmerge %GEPI and %UGEPI as below. | ||||
| 7569 | // | ||||
| 7570 | // ---------- BEFORE ---------- | ||||
| 7571 | // SrcBlock: | ||||
| 7572 | // ... | ||||
| 7573 | // %GEPIOp = ... | ||||
| 7574 | // ... | ||||
| 7575 | // %GEPI = gep %GEPIOp, Idx | ||||
| 7576 | // ... | ||||
| 7577 | // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ] | ||||
| 7578 | // (* %GEPI is alive on the indirectbr edges due to other uses ahead) | ||||
| 7579 | // (* %GEPIOp is alive on the indirectbr edges only because of it's used by | ||||
| 7580 | // %UGEPI) | ||||
| 7581 | // | ||||
| 7582 | // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged) | ||||
| 7583 | // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged) | ||||
| 7584 | // ... | ||||
| 7585 | // | ||||
| 7586 | // DstBi: | ||||
| 7587 | // ... | ||||
| 7588 | // %UGEPI = gep %GEPIOp, UIdx | ||||
| 7589 | // ... | ||||
| 7590 | // --------------------------- | ||||
| 7591 | // | ||||
| 7592 | // ---------- AFTER ---------- | ||||
| 7593 | // SrcBlock: | ||||
| 7594 | // ... (same as above) | ||||
| 7595 | // (* %GEPI is still alive on the indirectbr edges) | ||||
| 7596 | // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the | ||||
| 7597 | // unmerging) | ||||
| 7598 | // ... | ||||
| 7599 | // | ||||
| 7600 | // DstBi: | ||||
| 7601 | // ... | ||||
| 7602 | // %UGEPI = gep %GEPI, (UIdx-Idx) | ||||
| 7603 | // ... | ||||
| 7604 | // --------------------------- | ||||
| 7605 | // | ||||
| 7606 | // The register pressure on the IndirectBr edges is reduced because %GEPIOp is | ||||
| 7607 | // no longer alive on them. | ||||
| 7608 | // | ||||
| 7609 | // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging | ||||
| 7610 | // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as | ||||
| 7611 | // not to disable further simplications and optimizations as a result of GEP | ||||
| 7612 | // merging. | ||||
| 7613 | // | ||||
| 7614 | // Note this unmerging may increase the length of the data flow critical path | ||||
| 7615 | // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff | ||||
| 7616 | // between the register pressure and the length of data-flow critical | ||||
| 7617 | // path. Restricting this to the uncommon IndirectBr case would minimize the | ||||
| 7618 | // impact of potentially longer critical path, if any, and the impact on compile | ||||
| 7619 | // time. | ||||
| 7620 | static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, | ||||
| 7621 | const TargetTransformInfo *TTI) { | ||||
| 7622 | BasicBlock *SrcBlock = GEPI->getParent(); | ||||
| 7623 | // Check that SrcBlock ends with an IndirectBr. If not, give up. The common | ||||
| 7624 | // (non-IndirectBr) cases exit early here. | ||||
| 7625 | if (!isa<IndirectBrInst>(SrcBlock->getTerminator())) | ||||
| 7626 | return false; | ||||
| 7627 | // Check that GEPI is a simple gep with a single constant index. | ||||
| 7628 | if (!GEPSequentialConstIndexed(GEPI)) | ||||
| 7629 | return false; | ||||
| 7630 | ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1)); | ||||
| 7631 | // Check that GEPI is a cheap one. | ||||
| 7632 | if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(), | ||||
| 7633 | TargetTransformInfo::TCK_SizeAndLatency) | ||||
| 7634 | > TargetTransformInfo::TCC_Basic) | ||||
| 7635 | return false; | ||||
| 7636 | Value *GEPIOp = GEPI->getOperand(0); | ||||
| 7637 | // Check that GEPIOp is an instruction that's also defined in SrcBlock. | ||||
| 7638 | if (!isa<Instruction>(GEPIOp)) | ||||
| 7639 | return false; | ||||
| 7640 | auto *GEPIOpI = cast<Instruction>(GEPIOp); | ||||
| 7641 | if (GEPIOpI->getParent() != SrcBlock) | ||||
| 7642 | return false; | ||||
| 7643 | // Check that GEP is used outside the block, meaning it's alive on the | ||||
| 7644 | // IndirectBr edge(s). | ||||
| 7645 | if (find_if(GEPI->users(), [&](User *Usr) { | ||||
| 7646 | if (auto *I = dyn_cast<Instruction>(Usr)) { | ||||
| 7647 | if (I->getParent() != SrcBlock) { | ||||
| 7648 | return true; | ||||
| 7649 | } | ||||
| 7650 | } | ||||
| 7651 | return false; | ||||
| 7652 | }) == GEPI->users().end()) | ||||
| 7653 | return false; | ||||
| 7654 | // The second elements of the GEP chains to be unmerged. | ||||
| 7655 | std::vector<GetElementPtrInst *> UGEPIs; | ||||
| 7656 | // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive | ||||
| 7657 | // on IndirectBr edges. | ||||
| 7658 | for (User *Usr : GEPIOp->users()) { | ||||
| 7659 | if (Usr == GEPI) continue; | ||||
| 7660 | // Check if Usr is an Instruction. If not, give up. | ||||
| 7661 | if (!isa<Instruction>(Usr)) | ||||
| 7662 | return false; | ||||
| 7663 | auto *UI = cast<Instruction>(Usr); | ||||
| 7664 | // Check if Usr in the same block as GEPIOp, which is fine, skip. | ||||
| 7665 | if (UI->getParent() == SrcBlock) | ||||
| 7666 | continue; | ||||
| 7667 | // Check if Usr is a GEP. If not, give up. | ||||
| 7668 | if (!isa<GetElementPtrInst>(Usr)) | ||||
| 7669 | return false; | ||||
| 7670 | auto *UGEPI = cast<GetElementPtrInst>(Usr); | ||||
| 7671 | // Check if UGEPI is a simple gep with a single constant index and GEPIOp is | ||||
| 7672 | // the pointer operand to it. If so, record it in the vector. If not, give | ||||
| 7673 | // up. | ||||
| 7674 | if (!GEPSequentialConstIndexed(UGEPI)) | ||||
| 7675 | return false; | ||||
| 7676 | if (UGEPI->getOperand(0) != GEPIOp) | ||||
| 7677 | return false; | ||||
| 7678 | if (GEPIIdx->getType() != | ||||
| 7679 | cast<ConstantInt>(UGEPI->getOperand(1))->getType()) | ||||
| 7680 | return false; | ||||
| 7681 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); | ||||
| 7682 | if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(), | ||||
| 7683 | TargetTransformInfo::TCK_SizeAndLatency) | ||||
| 7684 | > TargetTransformInfo::TCC_Basic) | ||||
| 7685 | return false; | ||||
| 7686 | UGEPIs.push_back(UGEPI); | ||||
| 7687 | } | ||||
| 7688 | if (UGEPIs.size() == 0) | ||||
| 7689 | return false; | ||||
| 7690 | // Check the materializing cost of (Uidx-Idx). | ||||
| 7691 | for (GetElementPtrInst *UGEPI : UGEPIs) { | ||||
| 7692 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); | ||||
| 7693 | APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue(); | ||||
| 7694 | InstructionCost ImmCost = TTI->getIntImmCost( | ||||
| 7695 | NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency); | ||||
| 7696 | if (ImmCost > TargetTransformInfo::TCC_Basic) | ||||
| 7697 | return false; | ||||
| 7698 | } | ||||
| 7699 | // Now unmerge between GEPI and UGEPIs. | ||||
| 7700 | for (GetElementPtrInst *UGEPI : UGEPIs) { | ||||
| 7701 | UGEPI->setOperand(0, GEPI); | ||||
| 7702 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); | ||||
| 7703 | Constant *NewUGEPIIdx = | ||||
| 7704 | ConstantInt::get(GEPIIdx->getType(), | ||||
| 7705 | UGEPIIdx->getValue() - GEPIIdx->getValue()); | ||||
| 7706 | UGEPI->setOperand(1, NewUGEPIIdx); | ||||
| 7707 | // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not | ||||
| 7708 | // inbounds to avoid UB. | ||||
| 7709 | if (!GEPI->isInBounds()) { | ||||
| 7710 | UGEPI->setIsInBounds(false); | ||||
| 7711 | } | ||||
| 7712 | } | ||||
| 7713 | // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not | ||||
| 7714 | // alive on IndirectBr edges). | ||||
| 7715 | assert(find_if(GEPIOp->users(), [&](User *Usr) {((void)0) | ||||
| 7716 | return cast<Instruction>(Usr)->getParent() != SrcBlock;((void)0) | ||||
| 7717 | }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock")((void)0); | ||||
| 7718 | return true; | ||||
| 7719 | } | ||||
| 7720 | |||||
| 7721 | static bool optimizeBranch(BranchInst *Branch, const TargetLowering &TLI) { | ||||
| 7722 | // Try and convert | ||||
| 7723 | // %c = icmp ult %x, 8 | ||||
| 7724 | // br %c, bla, blb | ||||
| 7725 | // %tc = lshr %x, 3 | ||||
| 7726 | // to | ||||
| 7727 | // %tc = lshr %x, 3 | ||||
| 7728 | // %c = icmp eq %tc, 0 | ||||
| 7729 | // br %c, bla, blb | ||||
| 7730 | // Creating the cmp to zero can be better for the backend, especially if the | ||||
| 7731 | // lshr produces flags that can be used automatically. | ||||
| 7732 | if (!TLI.preferZeroCompareBranch() || !Branch->isConditional()) | ||||
| 7733 | return false; | ||||
| 7734 | |||||
| 7735 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition()); | ||||
| 7736 | if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse()) | ||||
| 7737 | return false; | ||||
| 7738 | |||||
| 7739 | Value *X = Cmp->getOperand(0); | ||||
| 7740 | APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue(); | ||||
| 7741 | |||||
| 7742 | for (auto *U : X->users()) { | ||||
| 7743 | Instruction *UI = dyn_cast<Instruction>(U); | ||||
| 7744 | // A quick dominance check | ||||
| 7745 | if (!UI || | ||||
| 7746 | (UI->getParent() != Branch->getParent() && | ||||
| 7747 | UI->getParent() != Branch->getSuccessor(0) && | ||||
| 7748 | UI->getParent() != Branch->getSuccessor(1)) || | ||||
| 7749 | (UI->getParent() != Branch->getParent() && | ||||
| 7750 | !UI->getParent()->getSinglePredecessor())) | ||||
| 7751 | continue; | ||||
| 7752 | |||||
| 7753 | if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT && | ||||
| 7754 | match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) { | ||||
| 7755 | IRBuilder<> Builder(Branch); | ||||
| 7756 | if (UI->getParent() != Branch->getParent()) | ||||
| 7757 | UI->moveBefore(Branch); | ||||
| 7758 | Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI, | ||||
| 7759 | ConstantInt::get(UI->getType(), 0)); | ||||
| 7760 | LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n")do { } while (false); | ||||
| 7761 | LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n")do { } while (false); | ||||
| 7762 | Cmp->replaceAllUsesWith(NewCmp); | ||||
| 7763 | return true; | ||||
| 7764 | } | ||||
| 7765 | if (Cmp->isEquality() && | ||||
| 7766 | (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) || | ||||
| 7767 | match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))))) { | ||||
| 7768 | IRBuilder<> Builder(Branch); | ||||
| 7769 | if (UI->getParent() != Branch->getParent()) | ||||
| 7770 | UI->moveBefore(Branch); | ||||
| 7771 | Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI, | ||||
| 7772 | ConstantInt::get(UI->getType(), 0)); | ||||
| 7773 | LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n")do { } while (false); | ||||
| 7774 | LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n")do { } while (false); | ||||
| 7775 | Cmp->replaceAllUsesWith(NewCmp); | ||||
| 7776 | return true; | ||||
| 7777 | } | ||||
| 7778 | } | ||||
| 7779 | return false; | ||||
| 7780 | } | ||||
| 7781 | |||||
| 7782 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) { | ||||
| 7783 | // Bail out if we inserted the instruction to prevent optimizations from | ||||
| 7784 | // stepping on each other's toes. | ||||
| 7785 | if (InsertedInsts.count(I)) | ||||
| 7786 | return false; | ||||
| 7787 | |||||
| 7788 | // TODO: Move into the switch on opcode below here. | ||||
| 7789 | if (PHINode *P = dyn_cast<PHINode>(I)) { | ||||
| 7790 | // It is possible for very late stage optimizations (such as SimplifyCFG) | ||||
| 7791 | // to introduce PHI nodes too late to be cleaned up. If we detect such a | ||||
| 7792 | // trivial PHI, go ahead and zap it here. | ||||
| 7793 | if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) { | ||||
| 7794 | LargeOffsetGEPMap.erase(P); | ||||
| 7795 | P->replaceAllUsesWith(V); | ||||
| 7796 | P->eraseFromParent(); | ||||
| 7797 | ++NumPHIsElim; | ||||
| 7798 | return true; | ||||
| 7799 | } | ||||
| 7800 | return false; | ||||
| 7801 | } | ||||
| 7802 | |||||
| 7803 | if (CastInst *CI = dyn_cast<CastInst>(I)) { | ||||
| 7804 | // If the source of the cast is a constant, then this should have | ||||
| 7805 | // already been constant folded. The only reason NOT to constant fold | ||||
| 7806 | // it is if something (e.g. LSR) was careful to place the constant | ||||
| 7807 | // evaluation in a block other than then one that uses it (e.g. to hoist | ||||
| 7808 | // the address of globals out of a loop). If this is the case, we don't | ||||
| 7809 | // want to forward-subst the cast. | ||||
| 7810 | if (isa<Constant>(CI->getOperand(0))) | ||||
| 7811 | return false; | ||||
| 7812 | |||||
| 7813 | if (OptimizeNoopCopyExpression(CI, *TLI, *DL)) | ||||
| 7814 | return true; | ||||
| 7815 | |||||
| 7816 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { | ||||
| 7817 | /// Sink a zext or sext into its user blocks if the target type doesn't | ||||
| 7818 | /// fit in one register | ||||
| 7819 | if (TLI->getTypeAction(CI->getContext(), | ||||
| 7820 | TLI->getValueType(*DL, CI->getType())) == | ||||
| 7821 | TargetLowering::TypeExpandInteger) { | ||||
| 7822 | return SinkCast(CI); | ||||
| 7823 | } else { | ||||
| 7824 | bool MadeChange = optimizeExt(I); | ||||
| 7825 | return MadeChange | optimizeExtUses(I); | ||||
| 7826 | } | ||||
| 7827 | } | ||||
| 7828 | return false; | ||||
| 7829 | } | ||||
| 7830 | |||||
| 7831 | if (auto *Cmp = dyn_cast<CmpInst>(I)) | ||||
| 7832 | if (optimizeCmp(Cmp, ModifiedDT)) | ||||
| 7833 | return true; | ||||
| 7834 | |||||
| 7835 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { | ||||
| 7836 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); | ||||
| 7837 | bool Modified = optimizeLoadExt(LI); | ||||
| 7838 | unsigned AS = LI->getPointerAddressSpace(); | ||||
| 7839 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); | ||||
| 7840 | return Modified; | ||||
| 7841 | } | ||||
| 7842 | |||||
| 7843 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { | ||||
| 7844 | if (splitMergedValStore(*SI, *DL, *TLI)) | ||||
| 7845 | return true; | ||||
| 7846 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); | ||||
| 7847 | unsigned AS = SI->getPointerAddressSpace(); | ||||
| 7848 | return optimizeMemoryInst(I, SI->getOperand(1), | ||||
| 7849 | SI->getOperand(0)->getType(), AS); | ||||
| 7850 | } | ||||
| 7851 | |||||
| 7852 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { | ||||
| 7853 | unsigned AS = RMW->getPointerAddressSpace(); | ||||
| 7854 | return optimizeMemoryInst(I, RMW->getPointerOperand(), | ||||
| 7855 | RMW->getType(), AS); | ||||
| 7856 | } | ||||
| 7857 | |||||
| 7858 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { | ||||
| 7859 | unsigned AS = CmpX->getPointerAddressSpace(); | ||||
| 7860 | return optimizeMemoryInst(I, CmpX->getPointerOperand(), | ||||
| 7861 | CmpX->getCompareOperand()->getType(), AS); | ||||
| 7862 | } | ||||
| 7863 | |||||
| 7864 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); | ||||
| 7865 | |||||
| 7866 | if (BinOp && (BinOp->getOpcode() == Instruction::And) && EnableAndCmpSinking) | ||||
| 7867 | return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); | ||||
| 7868 | |||||
| 7869 | // TODO: Move this into the switch on opcode - it handles shifts already. | ||||
| 7870 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || | ||||
| 7871 | BinOp->getOpcode() == Instruction::LShr)) { | ||||
| 7872 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); | ||||
| 7873 | if (CI && TLI->hasExtractBitsInsn()) | ||||
| 7874 | if (OptimizeExtractBits(BinOp, CI, *TLI, *DL)) | ||||
| 7875 | return true; | ||||
| 7876 | } | ||||
| 7877 | |||||
| 7878 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { | ||||
| 7879 | if (GEPI->hasAllZeroIndices()) { | ||||
| 7880 | /// The GEP operand must be a pointer, so must its result -> BitCast | ||||
| 7881 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), | ||||
| 7882 | GEPI->getName(), GEPI); | ||||
| 7883 | NC->setDebugLoc(GEPI->getDebugLoc()); | ||||
| 7884 | GEPI->replaceAllUsesWith(NC); | ||||
| 7885 | GEPI->eraseFromParent(); | ||||
| 7886 | ++NumGEPsElim; | ||||
| 7887 | optimizeInst(NC, ModifiedDT); | ||||
| 7888 | return true; | ||||
| 7889 | } | ||||
| 7890 | if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) { | ||||
| 7891 | return true; | ||||
| 7892 | } | ||||
| 7893 | return false; | ||||
| 7894 | } | ||||
| 7895 | |||||
| 7896 | if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) { | ||||
| 7897 | // freeze(icmp a, const)) -> icmp (freeze a), const | ||||
| 7898 | // This helps generate efficient conditional jumps. | ||||
| 7899 | Instruction *CmpI = nullptr; | ||||
| 7900 | if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0))) | ||||
| 7901 | CmpI = II; | ||||
| 7902 | else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0))) | ||||
| 7903 | CmpI = F->getFastMathFlags().none() ? F : nullptr; | ||||
| 7904 | |||||
| 7905 | if (CmpI && CmpI->hasOneUse()) { | ||||
| 7906 | auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1); | ||||
| 7907 | bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) || | ||||
| 7908 | isa<ConstantPointerNull>(Op0); | ||||
| 7909 | bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) || | ||||
| 7910 | isa<ConstantPointerNull>(Op1); | ||||
| 7911 | if (Const0 || Const1) { | ||||
| 7912 | if (!Const0 || !Const1) { | ||||
| 7913 | auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI); | ||||
| 7914 | F->takeName(FI); | ||||
| 7915 | CmpI->setOperand(Const0 ? 1 : 0, F); | ||||
| 7916 | } | ||||
| 7917 | FI->replaceAllUsesWith(CmpI); | ||||
| 7918 | FI->eraseFromParent(); | ||||
| 7919 | return true; | ||||
| 7920 | } | ||||
| 7921 | } | ||||
| 7922 | return false; | ||||
| 7923 | } | ||||
| 7924 | |||||
| 7925 | if (tryToSinkFreeOperands(I)) | ||||
| 7926 | return true; | ||||
| 7927 | |||||
| 7928 | switch (I->getOpcode()) { | ||||
| 7929 | case Instruction::Shl: | ||||
| 7930 | case Instruction::LShr: | ||||
| 7931 | case Instruction::AShr: | ||||
| 7932 | return optimizeShiftInst(cast<BinaryOperator>(I)); | ||||
| 7933 | case Instruction::Call: | ||||
| 7934 | return optimizeCallInst(cast<CallInst>(I), ModifiedDT); | ||||
| 7935 | case Instruction::Select: | ||||
| 7936 | return optimizeSelectInst(cast<SelectInst>(I)); | ||||
| 7937 | case Instruction::ShuffleVector: | ||||
| 7938 | return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I)); | ||||
| 7939 | case Instruction::Switch: | ||||
| 7940 | return optimizeSwitchInst(cast<SwitchInst>(I)); | ||||
| 7941 | case Instruction::ExtractElement: | ||||
| 7942 | return optimizeExtractElementInst(cast<ExtractElementInst>(I)); | ||||
| 7943 | case Instruction::Br: | ||||
| 7944 | return optimizeBranch(cast<BranchInst>(I), *TLI); | ||||
| 7945 | } | ||||
| 7946 | |||||
| 7947 | return false; | ||||
| 7948 | } | ||||
| 7949 | |||||
| 7950 | /// Given an OR instruction, check to see if this is a bitreverse | ||||
| 7951 | /// idiom. If so, insert the new intrinsic and return true. | ||||
| 7952 | bool CodeGenPrepare::makeBitReverse(Instruction &I) { | ||||
| 7953 | if (!I.getType()->isIntegerTy() || | ||||
| 7954 | !TLI->isOperationLegalOrCustom(ISD::BITREVERSE, | ||||
| 7955 | TLI->getValueType(*DL, I.getType(), true))) | ||||
| 7956 | return false; | ||||
| 7957 | |||||
| 7958 | SmallVector<Instruction*, 4> Insts; | ||||
| 7959 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) | ||||
| 7960 | return false; | ||||
| 7961 | Instruction *LastInst = Insts.back(); | ||||
| 7962 | I.replaceAllUsesWith(LastInst); | ||||
| 7963 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
| 7964 | &I, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
| 7965 | return true; | ||||
| 7966 | } | ||||
| 7967 | |||||
| 7968 | // In this pass we look for GEP and cast instructions that are used | ||||
| 7969 | // across basic blocks and rewrite them to improve basic-block-at-a-time | ||||
| 7970 | // selection. | ||||
| 7971 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) { | ||||
| 7972 | SunkAddrs.clear(); | ||||
| 7973 | bool MadeChange = false; | ||||
| 7974 | |||||
| 7975 | CurInstIterator = BB.begin(); | ||||
| 7976 | while (CurInstIterator != BB.end()) { | ||||
| 7977 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); | ||||
| 7978 | if (ModifiedDT) | ||||
| 7979 | return true; | ||||
| 7980 | } | ||||
| 7981 | |||||
| 7982 | bool MadeBitReverse = true; | ||||
| 7983 | while (MadeBitReverse) { | ||||
| 7984 | MadeBitReverse = false; | ||||
| 7985 | for (auto &I : reverse(BB)) { | ||||
| 7986 | if (makeBitReverse(I)) { | ||||
| 7987 | MadeBitReverse = MadeChange = true; | ||||
| 7988 | break; | ||||
| 7989 | } | ||||
| 7990 | } | ||||
| 7991 | } | ||||
| 7992 | MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT); | ||||
| 7993 | |||||
| 7994 | return MadeChange; | ||||
| 7995 | } | ||||
| 7996 | |||||
| 7997 | // Some CGP optimizations may move or alter what's computed in a block. Check | ||||
| 7998 | // whether a dbg.value intrinsic could be pointed at a more appropriate operand. | ||||
| 7999 | bool CodeGenPrepare::fixupDbgValue(Instruction *I) { | ||||
| 8000 | assert(isa<DbgValueInst>(I))((void)0); | ||||
| 8001 | DbgValueInst &DVI = *cast<DbgValueInst>(I); | ||||
| 8002 | |||||
| 8003 | // Does this dbg.value refer to a sunk address calculation? | ||||
| 8004 | bool AnyChange = false; | ||||
| 8005 | SmallDenseSet<Value *> LocationOps(DVI.location_ops().begin(), | ||||
| 8006 | DVI.location_ops().end()); | ||||
| 8007 | for (Value *Location : LocationOps) { | ||||
| 8008 | WeakTrackingVH SunkAddrVH = SunkAddrs[Location]; | ||||
| 8009 | Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; | ||||
| 8010 | if (SunkAddr) { | ||||
| 8011 | // Point dbg.value at locally computed address, which should give the best | ||||
| 8012 | // opportunity to be accurately lowered. This update may change the type | ||||
| 8013 | // of pointer being referred to; however this makes no difference to | ||||
| 8014 | // debugging information, and we can't generate bitcasts that may affect | ||||
| 8015 | // codegen. | ||||
| 8016 | DVI.replaceVariableLocationOp(Location, SunkAddr); | ||||
| 8017 | AnyChange = true; | ||||
| 8018 | } | ||||
| 8019 | } | ||||
| 8020 | return AnyChange; | ||||
| 8021 | } | ||||
| 8022 | |||||
| 8023 | // A llvm.dbg.value may be using a value before its definition, due to | ||||
| 8024 | // optimizations in this pass and others. Scan for such dbg.values, and rescue | ||||
| 8025 | // them by moving the dbg.value to immediately after the value definition. | ||||
| 8026 | // FIXME: Ideally this should never be necessary, and this has the potential | ||||
| 8027 | // to re-order dbg.value intrinsics. | ||||
| 8028 | bool CodeGenPrepare::placeDbgValues(Function &F) { | ||||
| 8029 | bool MadeChange = false; | ||||
| 8030 | DominatorTree DT(F); | ||||
| 8031 | |||||
| 8032 | for (BasicBlock &BB : F) { | ||||
| 8033 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { | ||||
| 8034 | Instruction *Insn = &*BI++; | ||||
| 8035 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); | ||||
| 8036 | if (!DVI) | ||||
| 8037 | continue; | ||||
| 8038 | |||||
| 8039 | SmallVector<Instruction *, 4> VIs; | ||||
| 8040 | for (Value *V : DVI->getValues()) | ||||
| 8041 | if (Instruction *VI = dyn_cast_or_null<Instruction>(V)) | ||||
| 8042 | VIs.push_back(VI); | ||||
| 8043 | |||||
| 8044 | // This DVI may depend on multiple instructions, complicating any | ||||
| 8045 | // potential sink. This block takes the defensive approach, opting to | ||||
| 8046 | // "undef" the DVI if it has more than one instruction and any of them do | ||||
| 8047 | // not dominate DVI. | ||||
| 8048 | for (Instruction *VI : VIs) { | ||||
| 8049 | if (VI->isTerminator()) | ||||
| 8050 | continue; | ||||
| 8051 | |||||
| 8052 | // If VI is a phi in a block with an EHPad terminator, we can't insert | ||||
| 8053 | // after it. | ||||
| 8054 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) | ||||
| 8055 | continue; | ||||
| 8056 | |||||
| 8057 | // If the defining instruction dominates the dbg.value, we do not need | ||||
| 8058 | // to move the dbg.value. | ||||
| 8059 | if (DT.dominates(VI, DVI)) | ||||
| 8060 | continue; | ||||
| 8061 | |||||
| 8062 | // If we depend on multiple instructions and any of them doesn't | ||||
| 8063 | // dominate this DVI, we probably can't salvage it: moving it to | ||||
| 8064 | // after any of the instructions could cause us to lose the others. | ||||
| 8065 | if (VIs.size() > 1) { | ||||
| 8066 | LLVM_DEBUG(do { } while (false) | ||||
| 8067 | dbgs()do { } while (false) | ||||
| 8068 | << "Unable to find valid location for Debug Value, undefing:\n"do { } while (false) | ||||
| 8069 | << *DVI)do { } while (false); | ||||
| 8070 | DVI->setUndef(); | ||||
| 8071 | break; | ||||
| 8072 | } | ||||
| 8073 | |||||
| 8074 | LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"do { } while (false) | ||||
| 8075 | << *DVI << ' ' << *VI)do { } while (false); | ||||
| 8076 | DVI->removeFromParent(); | ||||
| 8077 | if (isa<PHINode>(VI)) | ||||
| 8078 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); | ||||
| 8079 | else | ||||
| 8080 | DVI->insertAfter(VI); | ||||
| 8081 | MadeChange = true; | ||||
| 8082 | ++NumDbgValueMoved; | ||||
| 8083 | } | ||||
| 8084 | } | ||||
| 8085 | } | ||||
| 8086 | return MadeChange; | ||||
| 8087 | } | ||||
| 8088 | |||||
| 8089 | // Group scattered pseudo probes in a block to favor SelectionDAG. Scattered | ||||
| 8090 | // probes can be chained dependencies of other regular DAG nodes and block DAG | ||||
| 8091 | // combine optimizations. | ||||
| 8092 | bool CodeGenPrepare::placePseudoProbes(Function &F) { | ||||
| 8093 | bool MadeChange = false; | ||||
| 8094 | for (auto &Block : F) { | ||||
| 8095 | // Move the rest probes to the beginning of the block. | ||||
| 8096 | auto FirstInst = Block.getFirstInsertionPt(); | ||||
| 8097 | while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst()) | ||||
| 8098 | ++FirstInst; | ||||
| 8099 | BasicBlock::iterator I(FirstInst); | ||||
| 8100 | I++; | ||||
| 8101 | while (I != Block.end()) { | ||||
| 8102 | if (auto *II = dyn_cast<PseudoProbeInst>(I++)) { | ||||
| 8103 | II->moveBefore(&*FirstInst); | ||||
| 8104 | MadeChange = true; | ||||
| 8105 | } | ||||
| 8106 | } | ||||
| 8107 | } | ||||
| 8108 | return MadeChange; | ||||
| 8109 | } | ||||
| 8110 | |||||
| 8111 | /// Scale down both weights to fit into uint32_t. | ||||
| 8112 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { | ||||
| 8113 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; | ||||
| 8114 | uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1; | ||||
| 8115 | NewTrue = NewTrue / Scale; | ||||
| 8116 | NewFalse = NewFalse / Scale; | ||||
| 8117 | } | ||||
| 8118 | |||||
| 8119 | /// Some targets prefer to split a conditional branch like: | ||||
| 8120 | /// \code | ||||
| 8121 | /// %0 = icmp ne i32 %a, 0 | ||||
| 8122 | /// %1 = icmp ne i32 %b, 0 | ||||
| 8123 | /// %or.cond = or i1 %0, %1 | ||||
| 8124 | /// br i1 %or.cond, label %TrueBB, label %FalseBB | ||||
| 8125 | /// \endcode | ||||
| 8126 | /// into multiple branch instructions like: | ||||
| 8127 | /// \code | ||||
| 8128 | /// bb1: | ||||
| 8129 | /// %0 = icmp ne i32 %a, 0 | ||||
| 8130 | /// br i1 %0, label %TrueBB, label %bb2 | ||||
| 8131 | /// bb2: | ||||
| 8132 | /// %1 = icmp ne i32 %b, 0 | ||||
| 8133 | /// br i1 %1, label %TrueBB, label %FalseBB | ||||
| 8134 | /// \endcode | ||||
| 8135 | /// This usually allows instruction selection to do even further optimizations | ||||
| 8136 | /// and combine the compare with the branch instruction. Currently this is | ||||
| 8137 | /// applied for targets which have "cheap" jump instructions. | ||||
| 8138 | /// | ||||
| 8139 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. | ||||
| 8140 | /// | ||||
| 8141 | bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) { | ||||
| 8142 | if (!TM->Options.EnableFastISel || TLI->isJumpExpensive()) | ||||
| 8143 | return false; | ||||
| 8144 | |||||
| 8145 | bool MadeChange = false; | ||||
| 8146 | for (auto &BB : F) { | ||||
| 8147 | // Does this BB end with the following? | ||||
| 8148 | // %cond1 = icmp|fcmp|binary instruction ... | ||||
| 8149 | // %cond2 = icmp|fcmp|binary instruction ... | ||||
| 8150 | // %cond.or = or|and i1 %cond1, cond2 | ||||
| 8151 | // br i1 %cond.or label %dest1, label %dest2" | ||||
| 8152 | Instruction *LogicOp; | ||||
| 8153 | BasicBlock *TBB, *FBB; | ||||
| 8154 | if (!match(BB.getTerminator(), | ||||
| 8155 | m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB))) | ||||
| 8156 | continue; | ||||
| 8157 | |||||
| 8158 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); | ||||
| 8159 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) | ||||
| 8160 | continue; | ||||
| 8161 | |||||
| 8162 | // The merging of mostly empty BB can cause a degenerate branch. | ||||
| 8163 | if (TBB == FBB) | ||||
| 8164 | continue; | ||||
| 8165 | |||||
| 8166 | unsigned Opc; | ||||
| 8167 | Value *Cond1, *Cond2; | ||||
| 8168 | if (match(LogicOp, | ||||
| 8169 | m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2))))) | ||||
| 8170 | Opc = Instruction::And; | ||||
| 8171 | else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)), | ||||
| 8172 | m_OneUse(m_Value(Cond2))))) | ||||
| 8173 | Opc = Instruction::Or; | ||||
| 8174 | else | ||||
| 8175 | continue; | ||||
| 8176 | |||||
| 8177 | auto IsGoodCond = [](Value *Cond) { | ||||
| 8178 | return match( | ||||
| 8179 | Cond, | ||||
| 8180 | m_CombineOr(m_Cmp(), m_CombineOr(m_LogicalAnd(m_Value(), m_Value()), | ||||
| 8181 | m_LogicalOr(m_Value(), m_Value())))); | ||||
| 8182 | }; | ||||
| 8183 | if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2)) | ||||
| 8184 | continue; | ||||
| 8185 | |||||
| 8186 | LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump())do { } while (false); | ||||
| 8187 | |||||
| 8188 | // Create a new BB. | ||||
| 8189 | auto *TmpBB = | ||||
| 8190 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", | ||||
| 8191 | BB.getParent(), BB.getNextNode()); | ||||
| 8192 | |||||
| 8193 | // Update original basic block by using the first condition directly by the | ||||
| 8194 | // branch instruction and removing the no longer needed and/or instruction. | ||||
| 8195 | Br1->setCondition(Cond1); | ||||
| 8196 | LogicOp->eraseFromParent(); | ||||
| 8197 | |||||
| 8198 | // Depending on the condition we have to either replace the true or the | ||||
| 8199 | // false successor of the original branch instruction. | ||||
| 8200 | if (Opc == Instruction::And) | ||||
| 8201 | Br1->setSuccessor(0, TmpBB); | ||||
| 8202 | else | ||||
| 8203 | Br1->setSuccessor(1, TmpBB); | ||||
| 8204 | |||||
| 8205 | // Fill in the new basic block. | ||||
| 8206 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); | ||||
| 8207 | if (auto *I = dyn_cast<Instruction>(Cond2)) { | ||||
| 8208 | I->removeFromParent(); | ||||
| 8209 | I->insertBefore(Br2); | ||||
| 8210 | } | ||||
| 8211 | |||||
| 8212 | // Update PHI nodes in both successors. The original BB needs to be | ||||
| 8213 | // replaced in one successor's PHI nodes, because the branch comes now from | ||||
| 8214 | // the newly generated BB (NewBB). In the other successor we need to add one | ||||
| 8215 | // incoming edge to the PHI nodes, because both branch instructions target | ||||
| 8216 | // now the same successor. Depending on the original branch condition | ||||
| 8217 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that | ||||
| 8218 | // we perform the correct update for the PHI nodes. | ||||
| 8219 | // This doesn't change the successor order of the just created branch | ||||
| 8220 | // instruction (or any other instruction). | ||||
| 8221 | if (Opc == Instruction::Or) | ||||
| 8222 | std::swap(TBB, FBB); | ||||
| 8223 | |||||
| 8224 | // Replace the old BB with the new BB. | ||||
| 8225 | TBB->replacePhiUsesWith(&BB, TmpBB); | ||||
| 8226 | |||||
| 8227 | // Add another incoming edge form the new BB. | ||||
| 8228 | for (PHINode &PN : FBB->phis()) { | ||||
| 8229 | auto *Val = PN.getIncomingValueForBlock(&BB); | ||||
| 8230 | PN.addIncoming(Val, TmpBB); | ||||
| 8231 | } | ||||
| 8232 | |||||
| 8233 | // Update the branch weights (from SelectionDAGBuilder:: | ||||
| 8234 | // FindMergedConditions). | ||||
| 8235 | if (Opc == Instruction::Or) { | ||||
| 8236 | // Codegen X | Y as: | ||||
| 8237 | // BB1: | ||||
| 8238 | // jmp_if_X TBB | ||||
| 8239 | // jmp TmpBB | ||||
| 8240 | // TmpBB: | ||||
| 8241 | // jmp_if_Y TBB | ||||
| 8242 | // jmp FBB | ||||
| 8243 | // | ||||
| 8244 | |||||
| 8245 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. | ||||
| 8246 | // The requirement is that | ||||
| 8247 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) | ||||
| 8248 | // = TrueProb for original BB. | ||||
| 8249 | // Assuming the original weights are A and B, one choice is to set BB1's | ||||
| 8250 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice | ||||
| 8251 | // assumes that | ||||
| 8252 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. | ||||
| 8253 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for | ||||
| 8254 | // TmpBB, but the math is more complicated. | ||||
| 8255 | uint64_t TrueWeight, FalseWeight; | ||||
| 8256 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { | ||||
| 8257 | uint64_t NewTrueWeight = TrueWeight; | ||||
| 8258 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; | ||||
| 8259 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
| 8260 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) | ||||
| 8261 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
| 8262 | |||||
| 8263 | NewTrueWeight = TrueWeight; | ||||
| 8264 | NewFalseWeight = 2 * FalseWeight; | ||||
| 8265 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
| 8266 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) | ||||
| 8267 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
| 8268 | } | ||||
| 8269 | } else { | ||||
| 8270 | // Codegen X & Y as: | ||||
| 8271 | // BB1: | ||||
| 8272 | // jmp_if_X TmpBB | ||||
| 8273 | // jmp FBB | ||||
| 8274 | // TmpBB: | ||||
| 8275 | // jmp_if_Y TBB | ||||
| 8276 | // jmp FBB | ||||
| 8277 | // | ||||
| 8278 | // This requires creation of TmpBB after CurBB. | ||||
| 8279 | |||||
| 8280 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. | ||||
| 8281 | // The requirement is that | ||||
| 8282 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) | ||||
| 8283 | // = FalseProb for original BB. | ||||
| 8284 | // Assuming the original weights are A and B, one choice is to set BB1's | ||||
| 8285 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice | ||||
| 8286 | // assumes that | ||||
| 8287 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. | ||||
| 8288 | uint64_t TrueWeight, FalseWeight; | ||||
| 8289 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { | ||||
| 8290 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; | ||||
| 8291 | uint64_t NewFalseWeight = FalseWeight; | ||||
| 8292 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
| 8293 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) | ||||
| 8294 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
| 8295 | |||||
| 8296 | NewTrueWeight = 2 * TrueWeight; | ||||
| 8297 | NewFalseWeight = FalseWeight; | ||||
| 8298 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
| 8299 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) | ||||
| 8300 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
| 8301 | } | ||||
| 8302 | } | ||||
| 8303 | |||||
| 8304 | ModifiedDT = true; | ||||
| 8305 | MadeChange = true; | ||||
| 8306 | |||||
| 8307 | LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();do { } while (false) | ||||
| 8308 | TmpBB->dump())do { } while (false); | ||||
| 8309 | } | ||||
| 8310 | return MadeChange; | ||||
| 8311 | } |
| 1 | //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file exposes the class definitions of all of the subclasses of the |
| 10 | // Instruction class. This is meant to be an easy way to get access to all |
| 11 | // instruction subclasses. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #ifndef LLVM_IR_INSTRUCTIONS_H |
| 16 | #define LLVM_IR_INSTRUCTIONS_H |
| 17 | |
| 18 | #include "llvm/ADT/ArrayRef.h" |
| 19 | #include "llvm/ADT/Bitfields.h" |
| 20 | #include "llvm/ADT/MapVector.h" |
| 21 | #include "llvm/ADT/None.h" |
| 22 | #include "llvm/ADT/STLExtras.h" |
| 23 | #include "llvm/ADT/SmallVector.h" |
| 24 | #include "llvm/ADT/StringRef.h" |
| 25 | #include "llvm/ADT/Twine.h" |
| 26 | #include "llvm/ADT/iterator.h" |
| 27 | #include "llvm/ADT/iterator_range.h" |
| 28 | #include "llvm/IR/Attributes.h" |
| 29 | #include "llvm/IR/BasicBlock.h" |
| 30 | #include "llvm/IR/CallingConv.h" |
| 31 | #include "llvm/IR/CFG.h" |
| 32 | #include "llvm/IR/Constant.h" |
| 33 | #include "llvm/IR/DerivedTypes.h" |
| 34 | #include "llvm/IR/Function.h" |
| 35 | #include "llvm/IR/InstrTypes.h" |
| 36 | #include "llvm/IR/Instruction.h" |
| 37 | #include "llvm/IR/OperandTraits.h" |
| 38 | #include "llvm/IR/Type.h" |
| 39 | #include "llvm/IR/Use.h" |
| 40 | #include "llvm/IR/User.h" |
| 41 | #include "llvm/IR/Value.h" |
| 42 | #include "llvm/Support/AtomicOrdering.h" |
| 43 | #include "llvm/Support/Casting.h" |
| 44 | #include "llvm/Support/ErrorHandling.h" |
| 45 | #include <cassert> |
| 46 | #include <cstddef> |
| 47 | #include <cstdint> |
| 48 | #include <iterator> |
| 49 | |
| 50 | namespace llvm { |
| 51 | |
| 52 | class APInt; |
| 53 | class ConstantInt; |
| 54 | class DataLayout; |
| 55 | class LLVMContext; |
| 56 | |
| 57 | //===----------------------------------------------------------------------===// |
| 58 | // AllocaInst Class |
| 59 | //===----------------------------------------------------------------------===// |
| 60 | |
| 61 | /// an instruction to allocate memory on the stack |
| 62 | class AllocaInst : public UnaryInstruction { |
| 63 | Type *AllocatedType; |
| 64 | |
| 65 | using AlignmentField = AlignmentBitfieldElementT<0>; |
| 66 | using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>; |
| 67 | using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>; |
| 68 | static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField, |
| 69 | SwiftErrorField>(), |
| 70 | "Bitfields must be contiguous"); |
| 71 | |
| 72 | protected: |
| 73 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 74 | friend class Instruction; |
| 75 | |
| 76 | AllocaInst *cloneImpl() const; |
| 77 | |
| 78 | public: |
| 79 | explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
| 80 | const Twine &Name, Instruction *InsertBefore); |
| 81 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
| 82 | const Twine &Name, BasicBlock *InsertAtEnd); |
| 83 | |
| 84 | AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, |
| 85 | Instruction *InsertBefore); |
| 86 | AllocaInst(Type *Ty, unsigned AddrSpace, |
| 87 | const Twine &Name, BasicBlock *InsertAtEnd); |
| 88 | |
| 89 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
| 90 | const Twine &Name = "", Instruction *InsertBefore = nullptr); |
| 91 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
| 92 | const Twine &Name, BasicBlock *InsertAtEnd); |
| 93 | |
| 94 | /// Return true if there is an allocation size parameter to the allocation |
| 95 | /// instruction that is not 1. |
| 96 | bool isArrayAllocation() const; |
| 97 | |
| 98 | /// Get the number of elements allocated. For a simple allocation of a single |
| 99 | /// element, this will return a constant 1 value. |
| 100 | const Value *getArraySize() const { return getOperand(0); } |
| 101 | Value *getArraySize() { return getOperand(0); } |
| 102 | |
| 103 | /// Overload to return most specific pointer type. |
| 104 | PointerType *getType() const { |
| 105 | return cast<PointerType>(Instruction::getType()); |
| 106 | } |
| 107 | |
| 108 | /// Get allocation size in bits. Returns None if size can't be determined, |
| 109 | /// e.g. in case of a VLA. |
| 110 | Optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const; |
| 111 | |
| 112 | /// Return the type that is being allocated by the instruction. |
| 113 | Type *getAllocatedType() const { return AllocatedType; } |
| 114 | /// for use only in special circumstances that need to generically |
| 115 | /// transform a whole instruction (eg: IR linking and vectorization). |
| 116 | void setAllocatedType(Type *Ty) { AllocatedType = Ty; } |
| 117 | |
| 118 | /// Return the alignment of the memory that is being allocated by the |
| 119 | /// instruction. |
| 120 | Align getAlign() const { |
| 121 | return Align(1ULL << getSubclassData<AlignmentField>()); |
| 122 | } |
| 123 | |
| 124 | void setAlignment(Align Align) { |
| 125 | setSubclassData<AlignmentField>(Log2(Align)); |
| 126 | } |
| 127 | |
| 128 | // FIXME: Remove this one transition to Align is over. |
| 129 | unsigned getAlignment() const { return getAlign().value(); } |
| 130 | |
| 131 | /// Return true if this alloca is in the entry block of the function and is a |
| 132 | /// constant size. If so, the code generator will fold it into the |
| 133 | /// prolog/epilog code, so it is basically free. |
| 134 | bool isStaticAlloca() const; |
| 135 | |
| 136 | /// Return true if this alloca is used as an inalloca argument to a call. Such |
| 137 | /// allocas are never considered static even if they are in the entry block. |
| 138 | bool isUsedWithInAlloca() const { |
| 139 | return getSubclassData<UsedWithInAllocaField>(); |
| 140 | } |
| 141 | |
| 142 | /// Specify whether this alloca is used to represent the arguments to a call. |
| 143 | void setUsedWithInAlloca(bool V) { |
| 144 | setSubclassData<UsedWithInAllocaField>(V); |
| 145 | } |
| 146 | |
| 147 | /// Return true if this alloca is used as a swifterror argument to a call. |
| 148 | bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); } |
| 149 | /// Specify whether this alloca is used to represent a swifterror. |
| 150 | void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); } |
| 151 | |
| 152 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 153 | static bool classof(const Instruction *I) { |
| 154 | return (I->getOpcode() == Instruction::Alloca); |
| 155 | } |
| 156 | static bool classof(const Value *V) { |
| 157 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 158 | } |
| 159 | |
| 160 | private: |
| 161 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 162 | // method so that subclasses cannot accidentally use it. |
| 163 | template <typename Bitfield> |
| 164 | void setSubclassData(typename Bitfield::Type Value) { |
| 165 | Instruction::setSubclassData<Bitfield>(Value); |
| 166 | } |
| 167 | }; |
| 168 | |
| 169 | //===----------------------------------------------------------------------===// |
| 170 | // LoadInst Class |
| 171 | //===----------------------------------------------------------------------===// |
| 172 | |
| 173 | /// An instruction for reading from memory. This uses the SubclassData field in |
| 174 | /// Value to store whether or not the load is volatile. |
| 175 | class LoadInst : public UnaryInstruction { |
| 176 | using VolatileField = BoolBitfieldElementT<0>; |
| 177 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
| 178 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
| 179 | static_assert( |
| 180 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
| 181 | "Bitfields must be contiguous"); |
| 182 | |
| 183 | void AssertOK(); |
| 184 | |
| 185 | protected: |
| 186 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 187 | friend class Instruction; |
| 188 | |
| 189 | LoadInst *cloneImpl() const; |
| 190 | |
| 191 | public: |
| 192 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, |
| 193 | Instruction *InsertBefore); |
| 194 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 195 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
| 196 | Instruction *InsertBefore); |
| 197 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
| 198 | BasicBlock *InsertAtEnd); |
| 199 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
| 200 | Align Align, Instruction *InsertBefore = nullptr); |
| 201 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
| 202 | Align Align, BasicBlock *InsertAtEnd); |
| 203 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
| 204 | Align Align, AtomicOrdering Order, |
| 205 | SyncScope::ID SSID = SyncScope::System, |
| 206 | Instruction *InsertBefore = nullptr); |
| 207 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
| 208 | Align Align, AtomicOrdering Order, SyncScope::ID SSID, |
| 209 | BasicBlock *InsertAtEnd); |
| 210 | |
| 211 | /// Return true if this is a load from a volatile memory location. |
| 212 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
| 213 | |
| 214 | /// Specify whether this is a volatile load or not. |
| 215 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
| 216 | |
| 217 | /// Return the alignment of the access that is being performed. |
| 218 | /// FIXME: Remove this function once transition to Align is over. |
| 219 | /// Use getAlign() instead. |
| 220 | unsigned getAlignment() const { return getAlign().value(); } |
| 221 | |
| 222 | /// Return the alignment of the access that is being performed. |
| 223 | Align getAlign() const { |
| 224 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
| 225 | } |
| 226 | |
| 227 | void setAlignment(Align Align) { |
| 228 | setSubclassData<AlignmentField>(Log2(Align)); |
| 229 | } |
| 230 | |
| 231 | /// Returns the ordering constraint of this load instruction. |
| 232 | AtomicOrdering getOrdering() const { |
| 233 | return getSubclassData<OrderingField>(); |
| 234 | } |
| 235 | /// Sets the ordering constraint of this load instruction. May not be Release |
| 236 | /// or AcquireRelease. |
| 237 | void setOrdering(AtomicOrdering Ordering) { |
| 238 | setSubclassData<OrderingField>(Ordering); |
| 239 | } |
| 240 | |
| 241 | /// Returns the synchronization scope ID of this load instruction. |
| 242 | SyncScope::ID getSyncScopeID() const { |
| 243 | return SSID; |
| 244 | } |
| 245 | |
| 246 | /// Sets the synchronization scope ID of this load instruction. |
| 247 | void setSyncScopeID(SyncScope::ID SSID) { |
| 248 | this->SSID = SSID; |
| 249 | } |
| 250 | |
| 251 | /// Sets the ordering constraint and the synchronization scope ID of this load |
| 252 | /// instruction. |
| 253 | void setAtomic(AtomicOrdering Ordering, |
| 254 | SyncScope::ID SSID = SyncScope::System) { |
| 255 | setOrdering(Ordering); |
| 256 | setSyncScopeID(SSID); |
| 257 | } |
| 258 | |
| 259 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
| 260 | |
| 261 | bool isUnordered() const { |
| 262 | return (getOrdering() == AtomicOrdering::NotAtomic || |
| 263 | getOrdering() == AtomicOrdering::Unordered) && |
| 264 | !isVolatile(); |
| 265 | } |
| 266 | |
| 267 | Value *getPointerOperand() { return getOperand(0); } |
| 268 | const Value *getPointerOperand() const { return getOperand(0); } |
| 269 | static unsigned getPointerOperandIndex() { return 0U; } |
| 270 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
| 271 | |
| 272 | /// Returns the address space of the pointer operand. |
| 273 | unsigned getPointerAddressSpace() const { |
| 274 | return getPointerOperandType()->getPointerAddressSpace(); |
| 275 | } |
| 276 | |
| 277 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 278 | static bool classof(const Instruction *I) { |
| 279 | return I->getOpcode() == Instruction::Load; |
| 280 | } |
| 281 | static bool classof(const Value *V) { |
| 282 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 283 | } |
| 284 | |
| 285 | private: |
| 286 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 287 | // method so that subclasses cannot accidentally use it. |
| 288 | template <typename Bitfield> |
| 289 | void setSubclassData(typename Bitfield::Type Value) { |
| 290 | Instruction::setSubclassData<Bitfield>(Value); |
| 291 | } |
| 292 | |
| 293 | /// The synchronization scope ID of this load instruction. Not quite enough |
| 294 | /// room in SubClassData for everything, so synchronization scope ID gets its |
| 295 | /// own field. |
| 296 | SyncScope::ID SSID; |
| 297 | }; |
| 298 | |
| 299 | //===----------------------------------------------------------------------===// |
| 300 | // StoreInst Class |
| 301 | //===----------------------------------------------------------------------===// |
| 302 | |
| 303 | /// An instruction for storing to memory. |
| 304 | class StoreInst : public Instruction { |
| 305 | using VolatileField = BoolBitfieldElementT<0>; |
| 306 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
| 307 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
| 308 | static_assert( |
| 309 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
| 310 | "Bitfields must be contiguous"); |
| 311 | |
| 312 | void AssertOK(); |
| 313 | |
| 314 | protected: |
| 315 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 316 | friend class Instruction; |
| 317 | |
| 318 | StoreInst *cloneImpl() const; |
| 319 | |
| 320 | public: |
| 321 | StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore); |
| 322 | StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd); |
| 323 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore); |
| 324 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd); |
| 325 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
| 326 | Instruction *InsertBefore = nullptr); |
| 327 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
| 328 | BasicBlock *InsertAtEnd); |
| 329 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
| 330 | AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System, |
| 331 | Instruction *InsertBefore = nullptr); |
| 332 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
| 333 | AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd); |
| 334 | |
| 335 | // allocate space for exactly two operands |
| 336 | void *operator new(size_t S) { return User::operator new(S, 2); } |
| 337 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 338 | |
| 339 | /// Return true if this is a store to a volatile memory location. |
| 340 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
| 341 | |
| 342 | /// Specify whether this is a volatile store or not. |
| 343 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
| 344 | |
| 345 | /// Transparently provide more efficient getOperand methods. |
| 346 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 347 | |
| 348 | /// Return the alignment of the access that is being performed |
| 349 | /// FIXME: Remove this function once transition to Align is over. |
| 350 | /// Use getAlign() instead. |
| 351 | unsigned getAlignment() const { return getAlign().value(); } |
| 352 | |
| 353 | Align getAlign() const { |
| 354 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
| 355 | } |
| 356 | |
| 357 | void setAlignment(Align Align) { |
| 358 | setSubclassData<AlignmentField>(Log2(Align)); |
| 359 | } |
| 360 | |
| 361 | /// Returns the ordering constraint of this store instruction. |
| 362 | AtomicOrdering getOrdering() const { |
| 363 | return getSubclassData<OrderingField>(); |
| 364 | } |
| 365 | |
| 366 | /// Sets the ordering constraint of this store instruction. May not be |
| 367 | /// Acquire or AcquireRelease. |
| 368 | void setOrdering(AtomicOrdering Ordering) { |
| 369 | setSubclassData<OrderingField>(Ordering); |
| 370 | } |
| 371 | |
| 372 | /// Returns the synchronization scope ID of this store instruction. |
| 373 | SyncScope::ID getSyncScopeID() const { |
| 374 | return SSID; |
| 375 | } |
| 376 | |
| 377 | /// Sets the synchronization scope ID of this store instruction. |
| 378 | void setSyncScopeID(SyncScope::ID SSID) { |
| 379 | this->SSID = SSID; |
| 380 | } |
| 381 | |
| 382 | /// Sets the ordering constraint and the synchronization scope ID of this |
| 383 | /// store instruction. |
| 384 | void setAtomic(AtomicOrdering Ordering, |
| 385 | SyncScope::ID SSID = SyncScope::System) { |
| 386 | setOrdering(Ordering); |
| 387 | setSyncScopeID(SSID); |
| 388 | } |
| 389 | |
| 390 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
| 391 | |
| 392 | bool isUnordered() const { |
| 393 | return (getOrdering() == AtomicOrdering::NotAtomic || |
| 394 | getOrdering() == AtomicOrdering::Unordered) && |
| 395 | !isVolatile(); |
| 396 | } |
| 397 | |
| 398 | Value *getValueOperand() { return getOperand(0); } |
| 399 | const Value *getValueOperand() const { return getOperand(0); } |
| 400 | |
| 401 | Value *getPointerOperand() { return getOperand(1); } |
| 402 | const Value *getPointerOperand() const { return getOperand(1); } |
| 403 | static unsigned getPointerOperandIndex() { return 1U; } |
| 404 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
| 405 | |
| 406 | /// Returns the address space of the pointer operand. |
| 407 | unsigned getPointerAddressSpace() const { |
| 408 | return getPointerOperandType()->getPointerAddressSpace(); |
| 409 | } |
| 410 | |
| 411 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 412 | static bool classof(const Instruction *I) { |
| 413 | return I->getOpcode() == Instruction::Store; |
| 414 | } |
| 415 | static bool classof(const Value *V) { |
| 416 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 417 | } |
| 418 | |
| 419 | private: |
| 420 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 421 | // method so that subclasses cannot accidentally use it. |
| 422 | template <typename Bitfield> |
| 423 | void setSubclassData(typename Bitfield::Type Value) { |
| 424 | Instruction::setSubclassData<Bitfield>(Value); |
| 425 | } |
| 426 | |
| 427 | /// The synchronization scope ID of this store instruction. Not quite enough |
| 428 | /// room in SubClassData for everything, so synchronization scope ID gets its |
| 429 | /// own field. |
| 430 | SyncScope::ID SSID; |
| 431 | }; |
| 432 | |
| 433 | template <> |
| 434 | struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> { |
| 435 | }; |
| 436 | |
| 437 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits <StoreInst>::op_begin(this); } StoreInst::const_op_iterator StoreInst::op_begin() const { return OperandTraits<StoreInst >::op_begin(const_cast<StoreInst*>(this)); } StoreInst ::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst >::op_end(this); } StoreInst::const_op_iterator StoreInst:: op_end() const { return OperandTraits<StoreInst>::op_end (const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand (unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<StoreInst>::op_begin(const_cast <StoreInst*>(this))[i_nocapture].get()); } void StoreInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( void)0); OperandTraits<StoreInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned StoreInst::getNumOperands() const { return OperandTraits<StoreInst>::operands(this); } template <int Idx_nocapture> Use &StoreInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &StoreInst::Op() const { return this->OpFrom <Idx_nocapture>(this); } |
| 438 | |
| 439 | //===----------------------------------------------------------------------===// |
| 440 | // FenceInst Class |
| 441 | //===----------------------------------------------------------------------===// |
| 442 | |
| 443 | /// An instruction for ordering other memory operations. |
| 444 | class FenceInst : public Instruction { |
| 445 | using OrderingField = AtomicOrderingBitfieldElementT<0>; |
| 446 | |
| 447 | void Init(AtomicOrdering Ordering, SyncScope::ID SSID); |
| 448 | |
| 449 | protected: |
| 450 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 451 | friend class Instruction; |
| 452 | |
| 453 | FenceInst *cloneImpl() const; |
| 454 | |
| 455 | public: |
| 456 | // Ordering may only be Acquire, Release, AcquireRelease, or |
| 457 | // SequentiallyConsistent. |
| 458 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
| 459 | SyncScope::ID SSID = SyncScope::System, |
| 460 | Instruction *InsertBefore = nullptr); |
| 461 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID, |
| 462 | BasicBlock *InsertAtEnd); |
| 463 | |
| 464 | // allocate space for exactly zero operands |
| 465 | void *operator new(size_t S) { return User::operator new(S, 0); } |
| 466 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 467 | |
| 468 | /// Returns the ordering constraint of this fence instruction. |
| 469 | AtomicOrdering getOrdering() const { |
| 470 | return getSubclassData<OrderingField>(); |
| 471 | } |
| 472 | |
| 473 | /// Sets the ordering constraint of this fence instruction. May only be |
| 474 | /// Acquire, Release, AcquireRelease, or SequentiallyConsistent. |
| 475 | void setOrdering(AtomicOrdering Ordering) { |
| 476 | setSubclassData<OrderingField>(Ordering); |
| 477 | } |
| 478 | |
| 479 | /// Returns the synchronization scope ID of this fence instruction. |
| 480 | SyncScope::ID getSyncScopeID() const { |
| 481 | return SSID; |
| 482 | } |
| 483 | |
| 484 | /// Sets the synchronization scope ID of this fence instruction. |
| 485 | void setSyncScopeID(SyncScope::ID SSID) { |
| 486 | this->SSID = SSID; |
| 487 | } |
| 488 | |
| 489 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 490 | static bool classof(const Instruction *I) { |
| 491 | return I->getOpcode() == Instruction::Fence; |
| 492 | } |
| 493 | static bool classof(const Value *V) { |
| 494 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 495 | } |
| 496 | |
| 497 | private: |
| 498 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 499 | // method so that subclasses cannot accidentally use it. |
| 500 | template <typename Bitfield> |
| 501 | void setSubclassData(typename Bitfield::Type Value) { |
| 502 | Instruction::setSubclassData<Bitfield>(Value); |
| 503 | } |
| 504 | |
| 505 | /// The synchronization scope ID of this fence instruction. Not quite enough |
| 506 | /// room in SubClassData for everything, so synchronization scope ID gets its |
| 507 | /// own field. |
| 508 | SyncScope::ID SSID; |
| 509 | }; |
| 510 | |
| 511 | //===----------------------------------------------------------------------===// |
| 512 | // AtomicCmpXchgInst Class |
| 513 | //===----------------------------------------------------------------------===// |
| 514 | |
| 515 | /// An instruction that atomically checks whether a |
| 516 | /// specified value is in a memory location, and, if it is, stores a new value |
| 517 | /// there. The value returned by this instruction is a pair containing the |
| 518 | /// original value as first element, and an i1 indicating success (true) or |
| 519 | /// failure (false) as second element. |
| 520 | /// |
| 521 | class AtomicCmpXchgInst : public Instruction { |
| 522 | void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align, |
| 523 | AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, |
| 524 | SyncScope::ID SSID); |
| 525 | |
| 526 | template <unsigned Offset> |
| 527 | using AtomicOrderingBitfieldElement = |
| 528 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
| 529 | AtomicOrdering::LAST>; |
| 530 | |
| 531 | protected: |
| 532 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 533 | friend class Instruction; |
| 534 | |
| 535 | AtomicCmpXchgInst *cloneImpl() const; |
| 536 | |
| 537 | public: |
| 538 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
| 539 | AtomicOrdering SuccessOrdering, |
| 540 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
| 541 | Instruction *InsertBefore = nullptr); |
| 542 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
| 543 | AtomicOrdering SuccessOrdering, |
| 544 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
| 545 | BasicBlock *InsertAtEnd); |
| 546 | |
| 547 | // allocate space for exactly three operands |
| 548 | void *operator new(size_t S) { return User::operator new(S, 3); } |
| 549 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 550 | |
| 551 | using VolatileField = BoolBitfieldElementT<0>; |
| 552 | using WeakField = BoolBitfieldElementT<VolatileField::NextBit>; |
| 553 | using SuccessOrderingField = |
| 554 | AtomicOrderingBitfieldElementT<WeakField::NextBit>; |
| 555 | using FailureOrderingField = |
| 556 | AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>; |
| 557 | using AlignmentField = |
| 558 | AlignmentBitfieldElementT<FailureOrderingField::NextBit>; |
| 559 | static_assert( |
| 560 | Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField, |
| 561 | FailureOrderingField, AlignmentField>(), |
| 562 | "Bitfields must be contiguous"); |
| 563 | |
| 564 | /// Return the alignment of the memory that is being allocated by the |
| 565 | /// instruction. |
| 566 | Align getAlign() const { |
| 567 | return Align(1ULL << getSubclassData<AlignmentField>()); |
| 568 | } |
| 569 | |
| 570 | void setAlignment(Align Align) { |
| 571 | setSubclassData<AlignmentField>(Log2(Align)); |
| 572 | } |
| 573 | |
| 574 | /// Return true if this is a cmpxchg from a volatile memory |
| 575 | /// location. |
| 576 | /// |
| 577 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
| 578 | |
| 579 | /// Specify whether this is a volatile cmpxchg. |
| 580 | /// |
| 581 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
| 582 | |
| 583 | /// Return true if this cmpxchg may spuriously fail. |
| 584 | bool isWeak() const { return getSubclassData<WeakField>(); } |
| 585 | |
| 586 | void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); } |
| 587 | |
| 588 | /// Transparently provide more efficient getOperand methods. |
| 589 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 590 | |
| 591 | static bool isValidSuccessOrdering(AtomicOrdering Ordering) { |
| 592 | return Ordering != AtomicOrdering::NotAtomic && |
| 593 | Ordering != AtomicOrdering::Unordered; |
| 594 | } |
| 595 | |
| 596 | static bool isValidFailureOrdering(AtomicOrdering Ordering) { |
| 597 | return Ordering != AtomicOrdering::NotAtomic && |
| 598 | Ordering != AtomicOrdering::Unordered && |
| 599 | Ordering != AtomicOrdering::AcquireRelease && |
| 600 | Ordering != AtomicOrdering::Release; |
| 601 | } |
| 602 | |
| 603 | /// Returns the success ordering constraint of this cmpxchg instruction. |
| 604 | AtomicOrdering getSuccessOrdering() const { |
| 605 | return getSubclassData<SuccessOrderingField>(); |
| 606 | } |
| 607 | |
| 608 | /// Sets the success ordering constraint of this cmpxchg instruction. |
| 609 | void setSuccessOrdering(AtomicOrdering Ordering) { |
| 610 | assert(isValidSuccessOrdering(Ordering) &&((void)0) |
| 611 | "invalid CmpXchg success ordering")((void)0); |
| 612 | setSubclassData<SuccessOrderingField>(Ordering); |
| 613 | } |
| 614 | |
| 615 | /// Returns the failure ordering constraint of this cmpxchg instruction. |
| 616 | AtomicOrdering getFailureOrdering() const { |
| 617 | return getSubclassData<FailureOrderingField>(); |
| 618 | } |
| 619 | |
| 620 | /// Sets the failure ordering constraint of this cmpxchg instruction. |
| 621 | void setFailureOrdering(AtomicOrdering Ordering) { |
| 622 | assert(isValidFailureOrdering(Ordering) &&((void)0) |
| 623 | "invalid CmpXchg failure ordering")((void)0); |
| 624 | setSubclassData<FailureOrderingField>(Ordering); |
| 625 | } |
| 626 | |
| 627 | /// Returns a single ordering which is at least as strong as both the |
| 628 | /// success and failure orderings for this cmpxchg. |
| 629 | AtomicOrdering getMergedOrdering() const { |
| 630 | if (getFailureOrdering() == AtomicOrdering::SequentiallyConsistent) |
| 631 | return AtomicOrdering::SequentiallyConsistent; |
| 632 | if (getFailureOrdering() == AtomicOrdering::Acquire) { |
| 633 | if (getSuccessOrdering() == AtomicOrdering::Monotonic) |
| 634 | return AtomicOrdering::Acquire; |
| 635 | if (getSuccessOrdering() == AtomicOrdering::Release) |
| 636 | return AtomicOrdering::AcquireRelease; |
| 637 | } |
| 638 | return getSuccessOrdering(); |
| 639 | } |
| 640 | |
| 641 | /// Returns the synchronization scope ID of this cmpxchg instruction. |
| 642 | SyncScope::ID getSyncScopeID() const { |
| 643 | return SSID; |
| 644 | } |
| 645 | |
| 646 | /// Sets the synchronization scope ID of this cmpxchg instruction. |
| 647 | void setSyncScopeID(SyncScope::ID SSID) { |
| 648 | this->SSID = SSID; |
| 649 | } |
| 650 | |
| 651 | Value *getPointerOperand() { return getOperand(0); } |
| 652 | const Value *getPointerOperand() const { return getOperand(0); } |
| 653 | static unsigned getPointerOperandIndex() { return 0U; } |
| 654 | |
| 655 | Value *getCompareOperand() { return getOperand(1); } |
| 656 | const Value *getCompareOperand() const { return getOperand(1); } |
| 657 | |
| 658 | Value *getNewValOperand() { return getOperand(2); } |
| 659 | const Value *getNewValOperand() const { return getOperand(2); } |
| 660 | |
| 661 | /// Returns the address space of the pointer operand. |
| 662 | unsigned getPointerAddressSpace() const { |
| 663 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
| 664 | } |
| 665 | |
| 666 | /// Returns the strongest permitted ordering on failure, given the |
| 667 | /// desired ordering on success. |
| 668 | /// |
| 669 | /// If the comparison in a cmpxchg operation fails, there is no atomic store |
| 670 | /// so release semantics cannot be provided. So this function drops explicit |
| 671 | /// Release requests from the AtomicOrdering. A SequentiallyConsistent |
| 672 | /// operation would remain SequentiallyConsistent. |
| 673 | static AtomicOrdering |
| 674 | getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) { |
| 675 | switch (SuccessOrdering) { |
| 676 | default: |
| 677 | llvm_unreachable("invalid cmpxchg success ordering")__builtin_unreachable(); |
| 678 | case AtomicOrdering::Release: |
| 679 | case AtomicOrdering::Monotonic: |
| 680 | return AtomicOrdering::Monotonic; |
| 681 | case AtomicOrdering::AcquireRelease: |
| 682 | case AtomicOrdering::Acquire: |
| 683 | return AtomicOrdering::Acquire; |
| 684 | case AtomicOrdering::SequentiallyConsistent: |
| 685 | return AtomicOrdering::SequentiallyConsistent; |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 690 | static bool classof(const Instruction *I) { |
| 691 | return I->getOpcode() == Instruction::AtomicCmpXchg; |
| 692 | } |
| 693 | static bool classof(const Value *V) { |
| 694 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 695 | } |
| 696 | |
| 697 | private: |
| 698 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 699 | // method so that subclasses cannot accidentally use it. |
| 700 | template <typename Bitfield> |
| 701 | void setSubclassData(typename Bitfield::Type Value) { |
| 702 | Instruction::setSubclassData<Bitfield>(Value); |
| 703 | } |
| 704 | |
| 705 | /// The synchronization scope ID of this cmpxchg instruction. Not quite |
| 706 | /// enough room in SubClassData for everything, so synchronization scope ID |
| 707 | /// gets its own field. |
| 708 | SyncScope::ID SSID; |
| 709 | }; |
| 710 | |
| 711 | template <> |
| 712 | struct OperandTraits<AtomicCmpXchgInst> : |
| 713 | public FixedNumOperandTraits<AtomicCmpXchgInst, 3> { |
| 714 | }; |
| 715 | |
| 716 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() { return OperandTraits<AtomicCmpXchgInst>::op_begin(this ); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst:: op_begin() const { return OperandTraits<AtomicCmpXchgInst> ::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst ::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits <AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst:: const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits <AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst *>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null<Value >( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast <AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((void)0); OperandTraits<AtomicCmpXchgInst>::op_begin (this)[i_nocapture] = Val_nocapture; } unsigned AtomicCmpXchgInst ::getNumOperands() const { return OperandTraits<AtomicCmpXchgInst >::operands(this); } template <int Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & AtomicCmpXchgInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
| 717 | |
| 718 | //===----------------------------------------------------------------------===// |
| 719 | // AtomicRMWInst Class |
| 720 | //===----------------------------------------------------------------------===// |
| 721 | |
| 722 | /// an instruction that atomically reads a memory location, |
| 723 | /// combines it with another value, and then stores the result back. Returns |
| 724 | /// the old value. |
| 725 | /// |
| 726 | class AtomicRMWInst : public Instruction { |
| 727 | protected: |
| 728 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 729 | friend class Instruction; |
| 730 | |
| 731 | AtomicRMWInst *cloneImpl() const; |
| 732 | |
| 733 | public: |
| 734 | /// This enumeration lists the possible modifications atomicrmw can make. In |
| 735 | /// the descriptions, 'p' is the pointer to the instruction's memory location, |
| 736 | /// 'old' is the initial value of *p, and 'v' is the other value passed to the |
| 737 | /// instruction. These instructions always return 'old'. |
| 738 | enum BinOp : unsigned { |
| 739 | /// *p = v |
| 740 | Xchg, |
| 741 | /// *p = old + v |
| 742 | Add, |
| 743 | /// *p = old - v |
| 744 | Sub, |
| 745 | /// *p = old & v |
| 746 | And, |
| 747 | /// *p = ~(old & v) |
| 748 | Nand, |
| 749 | /// *p = old | v |
| 750 | Or, |
| 751 | /// *p = old ^ v |
| 752 | Xor, |
| 753 | /// *p = old >signed v ? old : v |
| 754 | Max, |
| 755 | /// *p = old <signed v ? old : v |
| 756 | Min, |
| 757 | /// *p = old >unsigned v ? old : v |
| 758 | UMax, |
| 759 | /// *p = old <unsigned v ? old : v |
| 760 | UMin, |
| 761 | |
| 762 | /// *p = old + v |
| 763 | FAdd, |
| 764 | |
| 765 | /// *p = old - v |
| 766 | FSub, |
| 767 | |
| 768 | FIRST_BINOP = Xchg, |
| 769 | LAST_BINOP = FSub, |
| 770 | BAD_BINOP |
| 771 | }; |
| 772 | |
| 773 | private: |
| 774 | template <unsigned Offset> |
| 775 | using AtomicOrderingBitfieldElement = |
| 776 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
| 777 | AtomicOrdering::LAST>; |
| 778 | |
| 779 | template <unsigned Offset> |
| 780 | using BinOpBitfieldElement = |
| 781 | typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>; |
| 782 | |
| 783 | public: |
| 784 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
| 785 | AtomicOrdering Ordering, SyncScope::ID SSID, |
| 786 | Instruction *InsertBefore = nullptr); |
| 787 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
| 788 | AtomicOrdering Ordering, SyncScope::ID SSID, |
| 789 | BasicBlock *InsertAtEnd); |
| 790 | |
| 791 | // allocate space for exactly two operands |
| 792 | void *operator new(size_t S) { return User::operator new(S, 2); } |
| 793 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 794 | |
| 795 | using VolatileField = BoolBitfieldElementT<0>; |
| 796 | using AtomicOrderingField = |
| 797 | AtomicOrderingBitfieldElementT<VolatileField::NextBit>; |
| 798 | using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>; |
| 799 | using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>; |
| 800 | static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField, |
| 801 | OperationField, AlignmentField>(), |
| 802 | "Bitfields must be contiguous"); |
| 803 | |
| 804 | BinOp getOperation() const { return getSubclassData<OperationField>(); } |
| 805 | |
| 806 | static StringRef getOperationName(BinOp Op); |
| 807 | |
| 808 | static bool isFPOperation(BinOp Op) { |
| 809 | switch (Op) { |
| 810 | case AtomicRMWInst::FAdd: |
| 811 | case AtomicRMWInst::FSub: |
| 812 | return true; |
| 813 | default: |
| 814 | return false; |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | void setOperation(BinOp Operation) { |
| 819 | setSubclassData<OperationField>(Operation); |
| 820 | } |
| 821 | |
| 822 | /// Return the alignment of the memory that is being allocated by the |
| 823 | /// instruction. |
| 824 | Align getAlign() const { |
| 825 | return Align(1ULL << getSubclassData<AlignmentField>()); |
| 826 | } |
| 827 | |
| 828 | void setAlignment(Align Align) { |
| 829 | setSubclassData<AlignmentField>(Log2(Align)); |
| 830 | } |
| 831 | |
| 832 | /// Return true if this is a RMW on a volatile memory location. |
| 833 | /// |
| 834 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
| 835 | |
| 836 | /// Specify whether this is a volatile RMW or not. |
| 837 | /// |
| 838 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
| 839 | |
| 840 | /// Transparently provide more efficient getOperand methods. |
| 841 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 842 | |
| 843 | /// Returns the ordering constraint of this rmw instruction. |
| 844 | AtomicOrdering getOrdering() const { |
| 845 | return getSubclassData<AtomicOrderingField>(); |
| 846 | } |
| 847 | |
| 848 | /// Sets the ordering constraint of this rmw instruction. |
| 849 | void setOrdering(AtomicOrdering Ordering) { |
| 850 | assert(Ordering != AtomicOrdering::NotAtomic &&((void)0) |
| 851 | "atomicrmw instructions can only be atomic.")((void)0); |
| 852 | setSubclassData<AtomicOrderingField>(Ordering); |
| 853 | } |
| 854 | |
| 855 | /// Returns the synchronization scope ID of this rmw instruction. |
| 856 | SyncScope::ID getSyncScopeID() const { |
| 857 | return SSID; |
| 858 | } |
| 859 | |
| 860 | /// Sets the synchronization scope ID of this rmw instruction. |
| 861 | void setSyncScopeID(SyncScope::ID SSID) { |
| 862 | this->SSID = SSID; |
| 863 | } |
| 864 | |
| 865 | Value *getPointerOperand() { return getOperand(0); } |
| 866 | const Value *getPointerOperand() const { return getOperand(0); } |
| 867 | static unsigned getPointerOperandIndex() { return 0U; } |
| 868 | |
| 869 | Value *getValOperand() { return getOperand(1); } |
| 870 | const Value *getValOperand() const { return getOperand(1); } |
| 871 | |
| 872 | /// Returns the address space of the pointer operand. |
| 873 | unsigned getPointerAddressSpace() const { |
| 874 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
| 875 | } |
| 876 | |
| 877 | bool isFloatingPointOperation() const { |
| 878 | return isFPOperation(getOperation()); |
| 879 | } |
| 880 | |
| 881 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 882 | static bool classof(const Instruction *I) { |
| 883 | return I->getOpcode() == Instruction::AtomicRMW; |
| 884 | } |
| 885 | static bool classof(const Value *V) { |
| 886 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 887 | } |
| 888 | |
| 889 | private: |
| 890 | void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align, |
| 891 | AtomicOrdering Ordering, SyncScope::ID SSID); |
| 892 | |
| 893 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 894 | // method so that subclasses cannot accidentally use it. |
| 895 | template <typename Bitfield> |
| 896 | void setSubclassData(typename Bitfield::Type Value) { |
| 897 | Instruction::setSubclassData<Bitfield>(Value); |
| 898 | } |
| 899 | |
| 900 | /// The synchronization scope ID of this rmw instruction. Not quite enough |
| 901 | /// room in SubClassData for everything, so synchronization scope ID gets its |
| 902 | /// own field. |
| 903 | SyncScope::ID SSID; |
| 904 | }; |
| 905 | |
| 906 | template <> |
| 907 | struct OperandTraits<AtomicRMWInst> |
| 908 | : public FixedNumOperandTraits<AtomicRMWInst,2> { |
| 909 | }; |
| 910 | |
| 911 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst ::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits <AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*> (this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end() { return OperandTraits<AtomicRMWInst>::op_end(this); } AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const { return OperandTraits<AtomicRMWInst>::op_end(const_cast <AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand (unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<AtomicRMWInst>::op_begin(const_cast <AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( void)0); OperandTraits<AtomicRMWInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned AtomicRMWInst::getNumOperands() const { return OperandTraits<AtomicRMWInst>::operands( this); } template <int Idx_nocapture> Use &AtomicRMWInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &AtomicRMWInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
| 912 | |
| 913 | //===----------------------------------------------------------------------===// |
| 914 | // GetElementPtrInst Class |
| 915 | //===----------------------------------------------------------------------===// |
| 916 | |
| 917 | // checkGEPType - Simple wrapper function to give a better assertion failure |
| 918 | // message on bad indexes for a gep instruction. |
| 919 | // |
| 920 | inline Type *checkGEPType(Type *Ty) { |
| 921 | assert(Ty && "Invalid GetElementPtrInst indices for type!")((void)0); |
| 922 | return Ty; |
| 923 | } |
| 924 | |
| 925 | /// an instruction for type-safe pointer arithmetic to |
| 926 | /// access elements of arrays and structs |
| 927 | /// |
| 928 | class GetElementPtrInst : public Instruction { |
| 929 | Type *SourceElementType; |
| 930 | Type *ResultElementType; |
| 931 | |
| 932 | GetElementPtrInst(const GetElementPtrInst &GEPI); |
| 933 | |
| 934 | /// Constructors - Create a getelementptr instruction with a base pointer an |
| 935 | /// list of indices. The first ctor can optionally insert before an existing |
| 936 | /// instruction, the second appends the new instruction to the specified |
| 937 | /// BasicBlock. |
| 938 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
| 939 | ArrayRef<Value *> IdxList, unsigned Values, |
| 940 | const Twine &NameStr, Instruction *InsertBefore); |
| 941 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
| 942 | ArrayRef<Value *> IdxList, unsigned Values, |
| 943 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 944 | |
| 945 | void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); |
| 946 | |
| 947 | protected: |
| 948 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 949 | friend class Instruction; |
| 950 | |
| 951 | GetElementPtrInst *cloneImpl() const; |
| 952 | |
| 953 | public: |
| 954 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
| 955 | ArrayRef<Value *> IdxList, |
| 956 | const Twine &NameStr = "", |
| 957 | Instruction *InsertBefore = nullptr) { |
| 958 | unsigned Values = 1 + unsigned(IdxList.size()); |
| 959 | assert(PointeeType && "Must specify element type")((void)0); |
| 960 | assert(cast<PointerType>(Ptr->getType()->getScalarType())((void)0) |
| 961 | ->isOpaqueOrPointeeTypeMatches(PointeeType))((void)0); |
| 962 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
| 963 | NameStr, InsertBefore); |
| 964 | } |
| 965 | |
| 966 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
| 967 | ArrayRef<Value *> IdxList, |
| 968 | const Twine &NameStr, |
| 969 | BasicBlock *InsertAtEnd) { |
| 970 | unsigned Values = 1 + unsigned(IdxList.size()); |
| 971 | assert(PointeeType && "Must specify element type")((void)0); |
| 972 | assert(cast<PointerType>(Ptr->getType()->getScalarType())((void)0) |
| 973 | ->isOpaqueOrPointeeTypeMatches(PointeeType))((void)0); |
| 974 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
| 975 | NameStr, InsertAtEnd); |
| 976 | } |
| 977 | |
| 978 | LLVM_ATTRIBUTE_DEPRECATED(static GetElementPtrInst *CreateInBounds([[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr = "", Instruction *InsertBefore = nullptr) |
| 979 | Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr = "",[[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr = "", Instruction *InsertBefore = nullptr) |
| 980 | Instruction *InsertBefore = nullptr),[[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr = "", Instruction *InsertBefore = nullptr) |
| 981 | "Use the version with explicit element type instead")[[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr = "", Instruction *InsertBefore = nullptr) { |
| 982 | return CreateInBounds( |
| 983 | Ptr->getType()->getScalarType()->getPointerElementType(), Ptr, IdxList, |
| 984 | NameStr, InsertBefore); |
| 985 | } |
| 986 | |
| 987 | /// Create an "inbounds" getelementptr. See the documentation for the |
| 988 | /// "inbounds" flag in LangRef.html for details. |
| 989 | static GetElementPtrInst * |
| 990 | CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList, |
| 991 | const Twine &NameStr = "", |
| 992 | Instruction *InsertBefore = nullptr) { |
| 993 | GetElementPtrInst *GEP = |
| 994 | Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore); |
| 995 | GEP->setIsInBounds(true); |
| 996 | return GEP; |
| 997 | } |
| 998 | |
| 999 | LLVM_ATTRIBUTE_DEPRECATED(static GetElementPtrInst *CreateInBounds([[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr, BasicBlock *InsertAtEnd) |
| 1000 | Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr,[[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr, BasicBlock *InsertAtEnd) |
| 1001 | BasicBlock *InsertAtEnd),[[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr, BasicBlock *InsertAtEnd) |
| 1002 | "Use the version with explicit element type instead")[[deprecated("Use the version with explicit element type instead" )]] static GetElementPtrInst *CreateInBounds( Value *Ptr, ArrayRef <Value *> IdxList, const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 1003 | return CreateInBounds( |
| 1004 | Ptr->getType()->getScalarType()->getPointerElementType(), Ptr, IdxList, |
| 1005 | NameStr, InsertAtEnd); |
| 1006 | } |
| 1007 | |
| 1008 | static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr, |
| 1009 | ArrayRef<Value *> IdxList, |
| 1010 | const Twine &NameStr, |
| 1011 | BasicBlock *InsertAtEnd) { |
| 1012 | GetElementPtrInst *GEP = |
| 1013 | Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd); |
| 1014 | GEP->setIsInBounds(true); |
| 1015 | return GEP; |
| 1016 | } |
| 1017 | |
| 1018 | /// Transparently provide more efficient getOperand methods. |
| 1019 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 1020 | |
| 1021 | Type *getSourceElementType() const { return SourceElementType; } |
| 1022 | |
| 1023 | void setSourceElementType(Type *Ty) { SourceElementType = Ty; } |
| 1024 | void setResultElementType(Type *Ty) { ResultElementType = Ty; } |
| 1025 | |
| 1026 | Type *getResultElementType() const { |
| 1027 | assert(cast<PointerType>(getType()->getScalarType())((void)0) |
| 1028 | ->isOpaqueOrPointeeTypeMatches(ResultElementType))((void)0); |
| 1029 | return ResultElementType; |
| 1030 | } |
| 1031 | |
| 1032 | /// Returns the address space of this instruction's pointer type. |
| 1033 | unsigned getAddressSpace() const { |
| 1034 | // Note that this is always the same as the pointer operand's address space |
| 1035 | // and that is cheaper to compute, so cheat here. |
| 1036 | return getPointerAddressSpace(); |
| 1037 | } |
| 1038 | |
| 1039 | /// Returns the result type of a getelementptr with the given source |
| 1040 | /// element type and indexes. |
| 1041 | /// |
| 1042 | /// Null is returned if the indices are invalid for the specified |
| 1043 | /// source element type. |
| 1044 | static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList); |
| 1045 | static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList); |
| 1046 | static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList); |
| 1047 | |
| 1048 | /// Return the type of the element at the given index of an indexable |
| 1049 | /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})". |
| 1050 | /// |
| 1051 | /// Returns null if the type can't be indexed, or the given index is not |
| 1052 | /// legal for the given type. |
| 1053 | static Type *getTypeAtIndex(Type *Ty, Value *Idx); |
| 1054 | static Type *getTypeAtIndex(Type *Ty, uint64_t Idx); |
| 1055 | |
| 1056 | inline op_iterator idx_begin() { return op_begin()+1; } |
| 1057 | inline const_op_iterator idx_begin() const { return op_begin()+1; } |
| 1058 | inline op_iterator idx_end() { return op_end(); } |
| 1059 | inline const_op_iterator idx_end() const { return op_end(); } |
| 1060 | |
| 1061 | inline iterator_range<op_iterator> indices() { |
| 1062 | return make_range(idx_begin(), idx_end()); |
| 1063 | } |
| 1064 | |
| 1065 | inline iterator_range<const_op_iterator> indices() const { |
| 1066 | return make_range(idx_begin(), idx_end()); |
| 1067 | } |
| 1068 | |
| 1069 | Value *getPointerOperand() { |
| 1070 | return getOperand(0); |
| 1071 | } |
| 1072 | const Value *getPointerOperand() const { |
| 1073 | return getOperand(0); |
| 1074 | } |
| 1075 | static unsigned getPointerOperandIndex() { |
| 1076 | return 0U; // get index for modifying correct operand. |
| 1077 | } |
| 1078 | |
| 1079 | /// Method to return the pointer operand as a |
| 1080 | /// PointerType. |
| 1081 | Type *getPointerOperandType() const { |
| 1082 | return getPointerOperand()->getType(); |
| 1083 | } |
| 1084 | |
| 1085 | /// Returns the address space of the pointer operand. |
| 1086 | unsigned getPointerAddressSpace() const { |
| 1087 | return getPointerOperandType()->getPointerAddressSpace(); |
| 1088 | } |
| 1089 | |
| 1090 | /// Returns the pointer type returned by the GEP |
| 1091 | /// instruction, which may be a vector of pointers. |
| 1092 | static Type *getGEPReturnType(Type *ElTy, Value *Ptr, |
| 1093 | ArrayRef<Value *> IdxList) { |
| 1094 | PointerType *OrigPtrTy = cast<PointerType>(Ptr->getType()->getScalarType()); |
| 1095 | unsigned AddrSpace = OrigPtrTy->getAddressSpace(); |
| 1096 | Type *ResultElemTy = checkGEPType(getIndexedType(ElTy, IdxList)); |
| 1097 | Type *PtrTy = OrigPtrTy->isOpaque() |
| 1098 | ? PointerType::get(OrigPtrTy->getContext(), AddrSpace) |
| 1099 | : PointerType::get(ResultElemTy, AddrSpace); |
| 1100 | // Vector GEP |
| 1101 | if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) { |
| 1102 | ElementCount EltCount = PtrVTy->getElementCount(); |
| 1103 | return VectorType::get(PtrTy, EltCount); |
| 1104 | } |
| 1105 | for (Value *Index : IdxList) |
| 1106 | if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) { |
| 1107 | ElementCount EltCount = IndexVTy->getElementCount(); |
| 1108 | return VectorType::get(PtrTy, EltCount); |
| 1109 | } |
| 1110 | // Scalar GEP |
| 1111 | return PtrTy; |
| 1112 | } |
| 1113 | |
| 1114 | unsigned getNumIndices() const { // Note: always non-negative |
| 1115 | return getNumOperands() - 1; |
| 1116 | } |
| 1117 | |
| 1118 | bool hasIndices() const { |
| 1119 | return getNumOperands() > 1; |
| 1120 | } |
| 1121 | |
| 1122 | /// Return true if all of the indices of this GEP are |
| 1123 | /// zeros. If so, the result pointer and the first operand have the same |
| 1124 | /// value, just potentially different types. |
| 1125 | bool hasAllZeroIndices() const; |
| 1126 | |
| 1127 | /// Return true if all of the indices of this GEP are |
| 1128 | /// constant integers. If so, the result pointer and the first operand have |
| 1129 | /// a constant offset between them. |
| 1130 | bool hasAllConstantIndices() const; |
| 1131 | |
| 1132 | /// Set or clear the inbounds flag on this GEP instruction. |
| 1133 | /// See LangRef.html for the meaning of inbounds on a getelementptr. |
| 1134 | void setIsInBounds(bool b = true); |
| 1135 | |
| 1136 | /// Determine whether the GEP has the inbounds flag. |
| 1137 | bool isInBounds() const; |
| 1138 | |
| 1139 | /// Accumulate the constant address offset of this GEP if possible. |
| 1140 | /// |
| 1141 | /// This routine accepts an APInt into which it will accumulate the constant |
| 1142 | /// offset of this GEP if the GEP is in fact constant. If the GEP is not |
| 1143 | /// all-constant, it returns false and the value of the offset APInt is |
| 1144 | /// undefined (it is *not* preserved!). The APInt passed into this routine |
| 1145 | /// must be at least as wide as the IntPtr type for the address space of |
| 1146 | /// the base GEP pointer. |
| 1147 | bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const; |
| 1148 | bool collectOffset(const DataLayout &DL, unsigned BitWidth, |
| 1149 | MapVector<Value *, APInt> &VariableOffsets, |
| 1150 | APInt &ConstantOffset) const; |
| 1151 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1152 | static bool classof(const Instruction *I) { |
| 1153 | return (I->getOpcode() == Instruction::GetElementPtr); |
| 1154 | } |
| 1155 | static bool classof(const Value *V) { |
| 1156 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1157 | } |
| 1158 | }; |
| 1159 | |
| 1160 | template <> |
| 1161 | struct OperandTraits<GetElementPtrInst> : |
| 1162 | public VariadicOperandTraits<GetElementPtrInst, 1> { |
| 1163 | }; |
| 1164 | |
| 1165 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
| 1166 | ArrayRef<Value *> IdxList, unsigned Values, |
| 1167 | const Twine &NameStr, |
| 1168 | Instruction *InsertBefore) |
| 1169 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
| 1170 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
| 1171 | Values, InsertBefore), |
| 1172 | SourceElementType(PointeeType), |
| 1173 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
| 1174 | assert(cast<PointerType>(getType()->getScalarType())((void)0) |
| 1175 | ->isOpaqueOrPointeeTypeMatches(ResultElementType))((void)0); |
| 1176 | init(Ptr, IdxList, NameStr); |
| 1177 | } |
| 1178 | |
| 1179 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
| 1180 | ArrayRef<Value *> IdxList, unsigned Values, |
| 1181 | const Twine &NameStr, |
| 1182 | BasicBlock *InsertAtEnd) |
| 1183 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
| 1184 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
| 1185 | Values, InsertAtEnd), |
| 1186 | SourceElementType(PointeeType), |
| 1187 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
| 1188 | assert(cast<PointerType>(getType()->getScalarType())((void)0) |
| 1189 | ->isOpaqueOrPointeeTypeMatches(ResultElementType))((void)0); |
| 1190 | init(Ptr, IdxList, NameStr); |
| 1191 | } |
| 1192 | |
| 1193 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() { return OperandTraits<GetElementPtrInst>::op_begin(this ); } GetElementPtrInst::const_op_iterator GetElementPtrInst:: op_begin() const { return OperandTraits<GetElementPtrInst> ::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst ::op_iterator GetElementPtrInst::op_end() { return OperandTraits <GetElementPtrInst>::op_end(this); } GetElementPtrInst:: const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits <GetElementPtrInst>::op_end(const_cast<GetElementPtrInst *>(this)); } Value *GetElementPtrInst::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null<Value >( OperandTraits<GetElementPtrInst>::op_begin(const_cast <GetElementPtrInst*>(this))[i_nocapture].get()); } void GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((void)0); OperandTraits<GetElementPtrInst>::op_begin (this)[i_nocapture] = Val_nocapture; } unsigned GetElementPtrInst ::getNumOperands() const { return OperandTraits<GetElementPtrInst >::operands(this); } template <int Idx_nocapture> Use &GetElementPtrInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & GetElementPtrInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
| 1194 | |
| 1195 | //===----------------------------------------------------------------------===// |
| 1196 | // ICmpInst Class |
| 1197 | //===----------------------------------------------------------------------===// |
| 1198 | |
| 1199 | /// This instruction compares its operands according to the predicate given |
| 1200 | /// to the constructor. It only operates on integers or pointers. The operands |
| 1201 | /// must be identical types. |
| 1202 | /// Represent an integer comparison operator. |
| 1203 | class ICmpInst: public CmpInst { |
| 1204 | void AssertOK() { |
| 1205 | assert(isIntPredicate() &&((void)0) |
| 1206 | "Invalid ICmp predicate value")((void)0); |
| 1207 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((void)0) |
| 1208 | "Both operands to ICmp instruction are not of the same type!")((void)0); |
| 1209 | // Check that the operands are the right type |
| 1210 | assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||((void)0) |
| 1211 | getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&((void)0) |
| 1212 | "Invalid operand types for ICmp instruction")((void)0); |
| 1213 | } |
| 1214 | |
| 1215 | protected: |
| 1216 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 1217 | friend class Instruction; |
| 1218 | |
| 1219 | /// Clone an identical ICmpInst |
| 1220 | ICmpInst *cloneImpl() const; |
| 1221 | |
| 1222 | public: |
| 1223 | /// Constructor with insert-before-instruction semantics. |
| 1224 | ICmpInst( |
| 1225 | Instruction *InsertBefore, ///< Where to insert |
| 1226 | Predicate pred, ///< The predicate to use for the comparison |
| 1227 | Value *LHS, ///< The left-hand-side of the expression |
| 1228 | Value *RHS, ///< The right-hand-side of the expression |
| 1229 | const Twine &NameStr = "" ///< Name of the instruction |
| 1230 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
| 1231 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
| 1232 | InsertBefore) { |
| 1233 | #ifndef NDEBUG1 |
| 1234 | AssertOK(); |
| 1235 | #endif |
| 1236 | } |
| 1237 | |
| 1238 | /// Constructor with insert-at-end semantics. |
| 1239 | ICmpInst( |
| 1240 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
| 1241 | Predicate pred, ///< The predicate to use for the comparison |
| 1242 | Value *LHS, ///< The left-hand-side of the expression |
| 1243 | Value *RHS, ///< The right-hand-side of the expression |
| 1244 | const Twine &NameStr = "" ///< Name of the instruction |
| 1245 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
| 1246 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
| 1247 | &InsertAtEnd) { |
| 1248 | #ifndef NDEBUG1 |
| 1249 | AssertOK(); |
| 1250 | #endif |
| 1251 | } |
| 1252 | |
| 1253 | /// Constructor with no-insertion semantics |
| 1254 | ICmpInst( |
| 1255 | Predicate pred, ///< The predicate to use for the comparison |
| 1256 | Value *LHS, ///< The left-hand-side of the expression |
| 1257 | Value *RHS, ///< The right-hand-side of the expression |
| 1258 | const Twine &NameStr = "" ///< Name of the instruction |
| 1259 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
| 1260 | Instruction::ICmp, pred, LHS, RHS, NameStr) { |
| 1261 | #ifndef NDEBUG1 |
| 1262 | AssertOK(); |
| 1263 | #endif |
| 1264 | } |
| 1265 | |
| 1266 | /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc. |
| 1267 | /// @returns the predicate that would be the result if the operand were |
| 1268 | /// regarded as signed. |
| 1269 | /// Return the signed version of the predicate |
| 1270 | Predicate getSignedPredicate() const { |
| 1271 | return getSignedPredicate(getPredicate()); |
| 1272 | } |
| 1273 | |
| 1274 | /// This is a static version that you can use without an instruction. |
| 1275 | /// Return the signed version of the predicate. |
| 1276 | static Predicate getSignedPredicate(Predicate pred); |
| 1277 | |
| 1278 | /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc. |
| 1279 | /// @returns the predicate that would be the result if the operand were |
| 1280 | /// regarded as unsigned. |
| 1281 | /// Return the unsigned version of the predicate |
| 1282 | Predicate getUnsignedPredicate() const { |
| 1283 | return getUnsignedPredicate(getPredicate()); |
| 1284 | } |
| 1285 | |
| 1286 | /// This is a static version that you can use without an instruction. |
| 1287 | /// Return the unsigned version of the predicate. |
| 1288 | static Predicate getUnsignedPredicate(Predicate pred); |
| 1289 | |
| 1290 | /// Return true if this predicate is either EQ or NE. This also |
| 1291 | /// tests for commutativity. |
| 1292 | static bool isEquality(Predicate P) { |
| 1293 | return P == ICMP_EQ || P == ICMP_NE; |
| 1294 | } |
| 1295 | |
| 1296 | /// Return true if this predicate is either EQ or NE. This also |
| 1297 | /// tests for commutativity. |
| 1298 | bool isEquality() const { |
| 1299 | return isEquality(getPredicate()); |
| 1300 | } |
| 1301 | |
| 1302 | /// @returns true if the predicate of this ICmpInst is commutative |
| 1303 | /// Determine if this relation is commutative. |
| 1304 | bool isCommutative() const { return isEquality(); } |
| 1305 | |
| 1306 | /// Return true if the predicate is relational (not EQ or NE). |
| 1307 | /// |
| 1308 | bool isRelational() const { |
| 1309 | return !isEquality(); |
| 1310 | } |
| 1311 | |
| 1312 | /// Return true if the predicate is relational (not EQ or NE). |
| 1313 | /// |
| 1314 | static bool isRelational(Predicate P) { |
| 1315 | return !isEquality(P); |
| 1316 | } |
| 1317 | |
| 1318 | /// Return true if the predicate is SGT or UGT. |
| 1319 | /// |
| 1320 | static bool isGT(Predicate P) { |
| 1321 | return P == ICMP_SGT || P == ICMP_UGT; |
| 1322 | } |
| 1323 | |
| 1324 | /// Return true if the predicate is SLT or ULT. |
| 1325 | /// |
| 1326 | static bool isLT(Predicate P) { |
| 1327 | return P == ICMP_SLT || P == ICMP_ULT; |
| 1328 | } |
| 1329 | |
| 1330 | /// Return true if the predicate is SGE or UGE. |
| 1331 | /// |
| 1332 | static bool isGE(Predicate P) { |
| 1333 | return P == ICMP_SGE || P == ICMP_UGE; |
| 1334 | } |
| 1335 | |
| 1336 | /// Return true if the predicate is SLE or ULE. |
| 1337 | /// |
| 1338 | static bool isLE(Predicate P) { |
| 1339 | return P == ICMP_SLE || P == ICMP_ULE; |
| 1340 | } |
| 1341 | |
| 1342 | /// Exchange the two operands to this instruction in such a way that it does |
| 1343 | /// not modify the semantics of the instruction. The predicate value may be |
| 1344 | /// changed to retain the same result if the predicate is order dependent |
| 1345 | /// (e.g. ult). |
| 1346 | /// Swap operands and adjust predicate. |
| 1347 | void swapOperands() { |
| 1348 | setPredicate(getSwappedPredicate()); |
| 1349 | Op<0>().swap(Op<1>()); |
| 1350 | } |
| 1351 | |
| 1352 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1353 | static bool classof(const Instruction *I) { |
| 1354 | return I->getOpcode() == Instruction::ICmp; |
| 1355 | } |
| 1356 | static bool classof(const Value *V) { |
| 1357 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1358 | } |
| 1359 | }; |
| 1360 | |
| 1361 | //===----------------------------------------------------------------------===// |
| 1362 | // FCmpInst Class |
| 1363 | //===----------------------------------------------------------------------===// |
| 1364 | |
| 1365 | /// This instruction compares its operands according to the predicate given |
| 1366 | /// to the constructor. It only operates on floating point values or packed |
| 1367 | /// vectors of floating point values. The operands must be identical types. |
| 1368 | /// Represents a floating point comparison operator. |
| 1369 | class FCmpInst: public CmpInst { |
| 1370 | void AssertOK() { |
| 1371 | assert(isFPPredicate() && "Invalid FCmp predicate value")((void)0); |
| 1372 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((void)0) |
| 1373 | "Both operands to FCmp instruction are not of the same type!")((void)0); |
| 1374 | // Check that the operands are the right type |
| 1375 | assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((void)0) |
| 1376 | "Invalid operand types for FCmp instruction")((void)0); |
| 1377 | } |
| 1378 | |
| 1379 | protected: |
| 1380 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 1381 | friend class Instruction; |
| 1382 | |
| 1383 | /// Clone an identical FCmpInst |
| 1384 | FCmpInst *cloneImpl() const; |
| 1385 | |
| 1386 | public: |
| 1387 | /// Constructor with insert-before-instruction semantics. |
| 1388 | FCmpInst( |
| 1389 | Instruction *InsertBefore, ///< Where to insert |
| 1390 | Predicate pred, ///< The predicate to use for the comparison |
| 1391 | Value *LHS, ///< The left-hand-side of the expression |
| 1392 | Value *RHS, ///< The right-hand-side of the expression |
| 1393 | const Twine &NameStr = "" ///< Name of the instruction |
| 1394 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
| 1395 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
| 1396 | InsertBefore) { |
| 1397 | AssertOK(); |
| 1398 | } |
| 1399 | |
| 1400 | /// Constructor with insert-at-end semantics. |
| 1401 | FCmpInst( |
| 1402 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
| 1403 | Predicate pred, ///< The predicate to use for the comparison |
| 1404 | Value *LHS, ///< The left-hand-side of the expression |
| 1405 | Value *RHS, ///< The right-hand-side of the expression |
| 1406 | const Twine &NameStr = "" ///< Name of the instruction |
| 1407 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
| 1408 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
| 1409 | &InsertAtEnd) { |
| 1410 | AssertOK(); |
| 1411 | } |
| 1412 | |
| 1413 | /// Constructor with no-insertion semantics |
| 1414 | FCmpInst( |
| 1415 | Predicate Pred, ///< The predicate to use for the comparison |
| 1416 | Value *LHS, ///< The left-hand-side of the expression |
| 1417 | Value *RHS, ///< The right-hand-side of the expression |
| 1418 | const Twine &NameStr = "", ///< Name of the instruction |
| 1419 | Instruction *FlagsSource = nullptr |
| 1420 | ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS, |
| 1421 | RHS, NameStr, nullptr, FlagsSource) { |
| 1422 | AssertOK(); |
| 1423 | } |
| 1424 | |
| 1425 | /// @returns true if the predicate of this instruction is EQ or NE. |
| 1426 | /// Determine if this is an equality predicate. |
| 1427 | static bool isEquality(Predicate Pred) { |
| 1428 | return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ || |
| 1429 | Pred == FCMP_UNE; |
| 1430 | } |
| 1431 | |
| 1432 | /// @returns true if the predicate of this instruction is EQ or NE. |
| 1433 | /// Determine if this is an equality predicate. |
| 1434 | bool isEquality() const { return isEquality(getPredicate()); } |
| 1435 | |
| 1436 | /// @returns true if the predicate of this instruction is commutative. |
| 1437 | /// Determine if this is a commutative predicate. |
| 1438 | bool isCommutative() const { |
| 1439 | return isEquality() || |
| 1440 | getPredicate() == FCMP_FALSE || |
| 1441 | getPredicate() == FCMP_TRUE || |
| 1442 | getPredicate() == FCMP_ORD || |
| 1443 | getPredicate() == FCMP_UNO; |
| 1444 | } |
| 1445 | |
| 1446 | /// @returns true if the predicate is relational (not EQ or NE). |
| 1447 | /// Determine if this a relational predicate. |
| 1448 | bool isRelational() const { return !isEquality(); } |
| 1449 | |
| 1450 | /// Exchange the two operands to this instruction in such a way that it does |
| 1451 | /// not modify the semantics of the instruction. The predicate value may be |
| 1452 | /// changed to retain the same result if the predicate is order dependent |
| 1453 | /// (e.g. ult). |
| 1454 | /// Swap operands and adjust predicate. |
| 1455 | void swapOperands() { |
| 1456 | setPredicate(getSwappedPredicate()); |
| 1457 | Op<0>().swap(Op<1>()); |
| 1458 | } |
| 1459 | |
| 1460 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1461 | static bool classof(const Instruction *I) { |
| 1462 | return I->getOpcode() == Instruction::FCmp; |
| 1463 | } |
| 1464 | static bool classof(const Value *V) { |
| 1465 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1466 | } |
| 1467 | }; |
| 1468 | |
| 1469 | //===----------------------------------------------------------------------===// |
| 1470 | /// This class represents a function call, abstracting a target |
| 1471 | /// machine's calling convention. This class uses low bit of the SubClassData |
| 1472 | /// field to indicate whether or not this is a tail call. The rest of the bits |
| 1473 | /// hold the calling convention of the call. |
| 1474 | /// |
| 1475 | class CallInst : public CallBase { |
| 1476 | CallInst(const CallInst &CI); |
| 1477 | |
| 1478 | /// Construct a CallInst given a range of arguments. |
| 1479 | /// Construct a CallInst from a range of arguments |
| 1480 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1481 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
| 1482 | Instruction *InsertBefore); |
| 1483 | |
| 1484 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1485 | const Twine &NameStr, Instruction *InsertBefore) |
| 1486 | : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {} |
| 1487 | |
| 1488 | /// Construct a CallInst given a range of arguments. |
| 1489 | /// Construct a CallInst from a range of arguments |
| 1490 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1491 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
| 1492 | BasicBlock *InsertAtEnd); |
| 1493 | |
| 1494 | explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr, |
| 1495 | Instruction *InsertBefore); |
| 1496 | |
| 1497 | CallInst(FunctionType *ty, Value *F, const Twine &NameStr, |
| 1498 | BasicBlock *InsertAtEnd); |
| 1499 | |
| 1500 | void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, |
| 1501 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
| 1502 | void init(FunctionType *FTy, Value *Func, const Twine &NameStr); |
| 1503 | |
| 1504 | /// Compute the number of operands to allocate. |
| 1505 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
| 1506 | // We need one operand for the called function, plus the input operand |
| 1507 | // counts provided. |
| 1508 | return 1 + NumArgs + NumBundleInputs; |
| 1509 | } |
| 1510 | |
| 1511 | protected: |
| 1512 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 1513 | friend class Instruction; |
| 1514 | |
| 1515 | CallInst *cloneImpl() const; |
| 1516 | |
| 1517 | public: |
| 1518 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "", |
| 1519 | Instruction *InsertBefore = nullptr) { |
| 1520 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore); |
| 1521 | } |
| 1522 | |
| 1523 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1524 | const Twine &NameStr, |
| 1525 | Instruction *InsertBefore = nullptr) { |
| 1526 | return new (ComputeNumOperands(Args.size())) |
| 1527 | CallInst(Ty, Func, Args, None, NameStr, InsertBefore); |
| 1528 | } |
| 1529 | |
| 1530 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1531 | ArrayRef<OperandBundleDef> Bundles = None, |
| 1532 | const Twine &NameStr = "", |
| 1533 | Instruction *InsertBefore = nullptr) { |
| 1534 | const int NumOperands = |
| 1535 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
| 1536 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
| 1537 | |
| 1538 | return new (NumOperands, DescriptorBytes) |
| 1539 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore); |
| 1540 | } |
| 1541 | |
| 1542 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr, |
| 1543 | BasicBlock *InsertAtEnd) { |
| 1544 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd); |
| 1545 | } |
| 1546 | |
| 1547 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1548 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 1549 | return new (ComputeNumOperands(Args.size())) |
| 1550 | CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd); |
| 1551 | } |
| 1552 | |
| 1553 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1554 | ArrayRef<OperandBundleDef> Bundles, |
| 1555 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 1556 | const int NumOperands = |
| 1557 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
| 1558 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
| 1559 | |
| 1560 | return new (NumOperands, DescriptorBytes) |
| 1561 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd); |
| 1562 | } |
| 1563 | |
| 1564 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "", |
| 1565 | Instruction *InsertBefore = nullptr) { |
| 1566 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
| 1567 | InsertBefore); |
| 1568 | } |
| 1569 | |
| 1570 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
| 1571 | ArrayRef<OperandBundleDef> Bundles = None, |
| 1572 | const Twine &NameStr = "", |
| 1573 | Instruction *InsertBefore = nullptr) { |
| 1574 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
| 1575 | NameStr, InsertBefore); |
| 1576 | } |
| 1577 | |
| 1578 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
| 1579 | const Twine &NameStr, |
| 1580 | Instruction *InsertBefore = nullptr) { |
| 1581 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
| 1582 | InsertBefore); |
| 1583 | } |
| 1584 | |
| 1585 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr, |
| 1586 | BasicBlock *InsertAtEnd) { |
| 1587 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
| 1588 | InsertAtEnd); |
| 1589 | } |
| 1590 | |
| 1591 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
| 1592 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 1593 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
| 1594 | InsertAtEnd); |
| 1595 | } |
| 1596 | |
| 1597 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
| 1598 | ArrayRef<OperandBundleDef> Bundles, |
| 1599 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 1600 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
| 1601 | NameStr, InsertAtEnd); |
| 1602 | } |
| 1603 | |
| 1604 | /// Create a clone of \p CI with a different set of operand bundles and |
| 1605 | /// insert it before \p InsertPt. |
| 1606 | /// |
| 1607 | /// The returned call instruction is identical \p CI in every way except that |
| 1608 | /// the operand bundles for the new instruction are set to the operand bundles |
| 1609 | /// in \p Bundles. |
| 1610 | static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles, |
| 1611 | Instruction *InsertPt = nullptr); |
| 1612 | |
| 1613 | /// Generate the IR for a call to malloc: |
| 1614 | /// 1. Compute the malloc call's argument as the specified type's size, |
| 1615 | /// possibly multiplied by the array size if the array size is not |
| 1616 | /// constant 1. |
| 1617 | /// 2. Call malloc with that argument. |
| 1618 | /// 3. Bitcast the result of the malloc call to the specified type. |
| 1619 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
| 1620 | Type *AllocTy, Value *AllocSize, |
| 1621 | Value *ArraySize = nullptr, |
| 1622 | Function *MallocF = nullptr, |
| 1623 | const Twine &Name = ""); |
| 1624 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
| 1625 | Type *AllocTy, Value *AllocSize, |
| 1626 | Value *ArraySize = nullptr, |
| 1627 | Function *MallocF = nullptr, |
| 1628 | const Twine &Name = ""); |
| 1629 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
| 1630 | Type *AllocTy, Value *AllocSize, |
| 1631 | Value *ArraySize = nullptr, |
| 1632 | ArrayRef<OperandBundleDef> Bundles = None, |
| 1633 | Function *MallocF = nullptr, |
| 1634 | const Twine &Name = ""); |
| 1635 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
| 1636 | Type *AllocTy, Value *AllocSize, |
| 1637 | Value *ArraySize = nullptr, |
| 1638 | ArrayRef<OperandBundleDef> Bundles = None, |
| 1639 | Function *MallocF = nullptr, |
| 1640 | const Twine &Name = ""); |
| 1641 | /// Generate the IR for a call to the builtin free function. |
| 1642 | static Instruction *CreateFree(Value *Source, Instruction *InsertBefore); |
| 1643 | static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd); |
| 1644 | static Instruction *CreateFree(Value *Source, |
| 1645 | ArrayRef<OperandBundleDef> Bundles, |
| 1646 | Instruction *InsertBefore); |
| 1647 | static Instruction *CreateFree(Value *Source, |
| 1648 | ArrayRef<OperandBundleDef> Bundles, |
| 1649 | BasicBlock *InsertAtEnd); |
| 1650 | |
| 1651 | // Note that 'musttail' implies 'tail'. |
| 1652 | enum TailCallKind : unsigned { |
| 1653 | TCK_None = 0, |
| 1654 | TCK_Tail = 1, |
| 1655 | TCK_MustTail = 2, |
| 1656 | TCK_NoTail = 3, |
| 1657 | TCK_LAST = TCK_NoTail |
| 1658 | }; |
| 1659 | |
| 1660 | using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>; |
| 1661 | static_assert( |
| 1662 | Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(), |
| 1663 | "Bitfields must be contiguous"); |
| 1664 | |
| 1665 | TailCallKind getTailCallKind() const { |
| 1666 | return getSubclassData<TailCallKindField>(); |
| 1667 | } |
| 1668 | |
| 1669 | bool isTailCall() const { |
| 1670 | TailCallKind Kind = getTailCallKind(); |
| 1671 | return Kind == TCK_Tail || Kind == TCK_MustTail; |
| 1672 | } |
| 1673 | |
| 1674 | bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; } |
| 1675 | |
| 1676 | bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; } |
| 1677 | |
| 1678 | void setTailCallKind(TailCallKind TCK) { |
| 1679 | setSubclassData<TailCallKindField>(TCK); |
| 1680 | } |
| 1681 | |
| 1682 | void setTailCall(bool IsTc = true) { |
| 1683 | setTailCallKind(IsTc ? TCK_Tail : TCK_None); |
| 1684 | } |
| 1685 | |
| 1686 | /// Return true if the call can return twice |
| 1687 | bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); } |
| 1688 | void setCanReturnTwice() { |
| 1689 | addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice); |
| 1690 | } |
| 1691 | |
| 1692 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1693 | static bool classof(const Instruction *I) { |
| 1694 | return I->getOpcode() == Instruction::Call; |
| 1695 | } |
| 1696 | static bool classof(const Value *V) { |
| 1697 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1698 | } |
| 1699 | |
| 1700 | /// Updates profile metadata by scaling it by \p S / \p T. |
| 1701 | void updateProfWeight(uint64_t S, uint64_t T); |
| 1702 | |
| 1703 | private: |
| 1704 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 1705 | // method so that subclasses cannot accidentally use it. |
| 1706 | template <typename Bitfield> |
| 1707 | void setSubclassData(typename Bitfield::Type Value) { |
| 1708 | Instruction::setSubclassData<Bitfield>(Value); |
| 1709 | } |
| 1710 | }; |
| 1711 | |
| 1712 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1713 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
| 1714 | BasicBlock *InsertAtEnd) |
| 1715 | : CallBase(Ty->getReturnType(), Instruction::Call, |
| 1716 | OperandTraits<CallBase>::op_end(this) - |
| 1717 | (Args.size() + CountBundleInputs(Bundles) + 1), |
| 1718 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
| 1719 | InsertAtEnd) { |
| 1720 | init(Ty, Func, Args, Bundles, NameStr); |
| 1721 | } |
| 1722 | |
| 1723 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
| 1724 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
| 1725 | Instruction *InsertBefore) |
| 1726 | : CallBase(Ty->getReturnType(), Instruction::Call, |
| 1727 | OperandTraits<CallBase>::op_end(this) - |
| 1728 | (Args.size() + CountBundleInputs(Bundles) + 1), |
| 1729 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
| 1730 | InsertBefore) { |
| 1731 | init(Ty, Func, Args, Bundles, NameStr); |
| 1732 | } |
| 1733 | |
| 1734 | //===----------------------------------------------------------------------===// |
| 1735 | // SelectInst Class |
| 1736 | //===----------------------------------------------------------------------===// |
| 1737 | |
| 1738 | /// This class represents the LLVM 'select' instruction. |
| 1739 | /// |
| 1740 | class SelectInst : public Instruction { |
| 1741 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
| 1742 | Instruction *InsertBefore) |
| 1743 | : Instruction(S1->getType(), Instruction::Select, |
| 1744 | &Op<0>(), 3, InsertBefore) { |
| 1745 | init(C, S1, S2); |
| 1746 | setName(NameStr); |
| 1747 | } |
| 1748 | |
| 1749 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
| 1750 | BasicBlock *InsertAtEnd) |
| 1751 | : Instruction(S1->getType(), Instruction::Select, |
| 1752 | &Op<0>(), 3, InsertAtEnd) { |
| 1753 | init(C, S1, S2); |
| 1754 | setName(NameStr); |
| 1755 | } |
| 1756 | |
| 1757 | void init(Value *C, Value *S1, Value *S2) { |
| 1758 | assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((void)0); |
| 1759 | Op<0>() = C; |
| 1760 | Op<1>() = S1; |
| 1761 | Op<2>() = S2; |
| 1762 | } |
| 1763 | |
| 1764 | protected: |
| 1765 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 1766 | friend class Instruction; |
| 1767 | |
| 1768 | SelectInst *cloneImpl() const; |
| 1769 | |
| 1770 | public: |
| 1771 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
| 1772 | const Twine &NameStr = "", |
| 1773 | Instruction *InsertBefore = nullptr, |
| 1774 | Instruction *MDFrom = nullptr) { |
| 1775 | SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore); |
| 1776 | if (MDFrom) |
| 1777 | Sel->copyMetadata(*MDFrom); |
| 1778 | return Sel; |
| 1779 | } |
| 1780 | |
| 1781 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
| 1782 | const Twine &NameStr, |
| 1783 | BasicBlock *InsertAtEnd) { |
| 1784 | return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd); |
| 1785 | } |
| 1786 | |
| 1787 | const Value *getCondition() const { return Op<0>(); } |
| 1788 | const Value *getTrueValue() const { return Op<1>(); } |
| 1789 | const Value *getFalseValue() const { return Op<2>(); } |
| 1790 | Value *getCondition() { return Op<0>(); } |
| 1791 | Value *getTrueValue() { return Op<1>(); } |
| 1792 | Value *getFalseValue() { return Op<2>(); } |
| 1793 | |
| 1794 | void setCondition(Value *V) { Op<0>() = V; } |
| 1795 | void setTrueValue(Value *V) { Op<1>() = V; } |
| 1796 | void setFalseValue(Value *V) { Op<2>() = V; } |
| 1797 | |
| 1798 | /// Swap the true and false values of the select instruction. |
| 1799 | /// This doesn't swap prof metadata. |
| 1800 | void swapValues() { Op<1>().swap(Op<2>()); } |
| 1801 | |
| 1802 | /// Return a string if the specified operands are invalid |
| 1803 | /// for a select operation, otherwise return null. |
| 1804 | static const char *areInvalidOperands(Value *Cond, Value *True, Value *False); |
| 1805 | |
| 1806 | /// Transparently provide more efficient getOperand methods. |
| 1807 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 1808 | |
| 1809 | OtherOps getOpcode() const { |
| 1810 | return static_cast<OtherOps>(Instruction::getOpcode()); |
| 1811 | } |
| 1812 | |
| 1813 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1814 | static bool classof(const Instruction *I) { |
| 1815 | return I->getOpcode() == Instruction::Select; |
| 1816 | } |
| 1817 | static bool classof(const Value *V) { |
| 1818 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1819 | } |
| 1820 | }; |
| 1821 | |
| 1822 | template <> |
| 1823 | struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> { |
| 1824 | }; |
| 1825 | |
| 1826 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits <SelectInst>::op_begin(this); } SelectInst::const_op_iterator SelectInst::op_begin() const { return OperandTraits<SelectInst >::op_begin(const_cast<SelectInst*>(this)); } SelectInst ::op_iterator SelectInst::op_end() { return OperandTraits< SelectInst>::op_end(this); } SelectInst::const_op_iterator SelectInst::op_end() const { return OperandTraits<SelectInst >::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<SelectInst>::op_begin(const_cast <SelectInst*>(this))[i_nocapture].get()); } void SelectInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( void)0); OperandTraits<SelectInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned SelectInst::getNumOperands() const { return OperandTraits<SelectInst>::operands(this); } template <int Idx_nocapture> Use &SelectInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &SelectInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
| 1827 | |
| 1828 | //===----------------------------------------------------------------------===// |
| 1829 | // VAArgInst Class |
| 1830 | //===----------------------------------------------------------------------===// |
| 1831 | |
| 1832 | /// This class represents the va_arg llvm instruction, which returns |
| 1833 | /// an argument of the specified type given a va_list and increments that list |
| 1834 | /// |
| 1835 | class VAArgInst : public UnaryInstruction { |
| 1836 | protected: |
| 1837 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 1838 | friend class Instruction; |
| 1839 | |
| 1840 | VAArgInst *cloneImpl() const; |
| 1841 | |
| 1842 | public: |
| 1843 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "", |
| 1844 | Instruction *InsertBefore = nullptr) |
| 1845 | : UnaryInstruction(Ty, VAArg, List, InsertBefore) { |
| 1846 | setName(NameStr); |
| 1847 | } |
| 1848 | |
| 1849 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr, |
| 1850 | BasicBlock *InsertAtEnd) |
| 1851 | : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) { |
| 1852 | setName(NameStr); |
| 1853 | } |
| 1854 | |
| 1855 | Value *getPointerOperand() { return getOperand(0); } |
| 1856 | const Value *getPointerOperand() const { return getOperand(0); } |
| 1857 | static unsigned getPointerOperandIndex() { return 0U; } |
| 1858 | |
| 1859 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1860 | static bool classof(const Instruction *I) { |
| 1861 | return I->getOpcode() == VAArg; |
| 1862 | } |
| 1863 | static bool classof(const Value *V) { |
| 1864 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1865 | } |
| 1866 | }; |
| 1867 | |
| 1868 | //===----------------------------------------------------------------------===// |
| 1869 | // ExtractElementInst Class |
| 1870 | //===----------------------------------------------------------------------===// |
| 1871 | |
| 1872 | /// This instruction extracts a single (scalar) |
| 1873 | /// element from a VectorType value |
| 1874 | /// |
| 1875 | class ExtractElementInst : public Instruction { |
| 1876 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "", |
| 1877 | Instruction *InsertBefore = nullptr); |
| 1878 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr, |
| 1879 | BasicBlock *InsertAtEnd); |
| 1880 | |
| 1881 | protected: |
| 1882 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 1883 | friend class Instruction; |
| 1884 | |
| 1885 | ExtractElementInst *cloneImpl() const; |
| 1886 | |
| 1887 | public: |
| 1888 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
| 1889 | const Twine &NameStr = "", |
| 1890 | Instruction *InsertBefore = nullptr) { |
| 1891 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore); |
| 1892 | } |
| 1893 | |
| 1894 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
| 1895 | const Twine &NameStr, |
| 1896 | BasicBlock *InsertAtEnd) { |
| 1897 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd); |
| 1898 | } |
| 1899 | |
| 1900 | /// Return true if an extractelement instruction can be |
| 1901 | /// formed with the specified operands. |
| 1902 | static bool isValidOperands(const Value *Vec, const Value *Idx); |
| 1903 | |
| 1904 | Value *getVectorOperand() { return Op<0>(); } |
| 1905 | Value *getIndexOperand() { return Op<1>(); } |
| 1906 | const Value *getVectorOperand() const { return Op<0>(); } |
| 1907 | const Value *getIndexOperand() const { return Op<1>(); } |
| 1908 | |
| 1909 | VectorType *getVectorOperandType() const { |
| 1910 | return cast<VectorType>(getVectorOperand()->getType()); |
| 1911 | } |
| 1912 | |
| 1913 | /// Transparently provide more efficient getOperand methods. |
| 1914 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 1915 | |
| 1916 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1917 | static bool classof(const Instruction *I) { |
| 1918 | return I->getOpcode() == Instruction::ExtractElement; |
| 1919 | } |
| 1920 | static bool classof(const Value *V) { |
| 1921 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1922 | } |
| 1923 | }; |
| 1924 | |
| 1925 | template <> |
| 1926 | struct OperandTraits<ExtractElementInst> : |
| 1927 | public FixedNumOperandTraits<ExtractElementInst, 2> { |
| 1928 | }; |
| 1929 | |
| 1930 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin( ) { return OperandTraits<ExtractElementInst>::op_begin( this); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_begin() const { return OperandTraits<ExtractElementInst >::op_begin(const_cast<ExtractElementInst*>(this)); } ExtractElementInst::op_iterator ExtractElementInst::op_end() { return OperandTraits<ExtractElementInst>::op_end(this ); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_end() const { return OperandTraits<ExtractElementInst >::op_end(const_cast<ExtractElementInst*>(this)); } Value *ExtractElementInst::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null<Value>( OperandTraits< ExtractElementInst>::op_begin(const_cast<ExtractElementInst *>(this))[i_nocapture].get()); } void ExtractElementInst:: setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((void )0); OperandTraits<ExtractElementInst>::op_begin(this)[ i_nocapture] = Val_nocapture; } unsigned ExtractElementInst:: getNumOperands() const { return OperandTraits<ExtractElementInst >::operands(this); } template <int Idx_nocapture> Use &ExtractElementInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & ExtractElementInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
| 1931 | |
| 1932 | //===----------------------------------------------------------------------===// |
| 1933 | // InsertElementInst Class |
| 1934 | //===----------------------------------------------------------------------===// |
| 1935 | |
| 1936 | /// This instruction inserts a single (scalar) |
| 1937 | /// element into a VectorType value |
| 1938 | /// |
| 1939 | class InsertElementInst : public Instruction { |
| 1940 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, |
| 1941 | const Twine &NameStr = "", |
| 1942 | Instruction *InsertBefore = nullptr); |
| 1943 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, |
| 1944 | BasicBlock *InsertAtEnd); |
| 1945 | |
| 1946 | protected: |
| 1947 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 1948 | friend class Instruction; |
| 1949 | |
| 1950 | InsertElementInst *cloneImpl() const; |
| 1951 | |
| 1952 | public: |
| 1953 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
| 1954 | const Twine &NameStr = "", |
| 1955 | Instruction *InsertBefore = nullptr) { |
| 1956 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore); |
| 1957 | } |
| 1958 | |
| 1959 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
| 1960 | const Twine &NameStr, |
| 1961 | BasicBlock *InsertAtEnd) { |
| 1962 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd); |
| 1963 | } |
| 1964 | |
| 1965 | /// Return true if an insertelement instruction can be |
| 1966 | /// formed with the specified operands. |
| 1967 | static bool isValidOperands(const Value *Vec, const Value *NewElt, |
| 1968 | const Value *Idx); |
| 1969 | |
| 1970 | /// Overload to return most specific vector type. |
| 1971 | /// |
| 1972 | VectorType *getType() const { |
| 1973 | return cast<VectorType>(Instruction::getType()); |
| 1974 | } |
| 1975 | |
| 1976 | /// Transparently provide more efficient getOperand methods. |
| 1977 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 1978 | |
| 1979 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 1980 | static bool classof(const Instruction *I) { |
| 1981 | return I->getOpcode() == Instruction::InsertElement; |
| 1982 | } |
| 1983 | static bool classof(const Value *V) { |
| 1984 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 1985 | } |
| 1986 | }; |
| 1987 | |
| 1988 | template <> |
| 1989 | struct OperandTraits<InsertElementInst> : |
| 1990 | public FixedNumOperandTraits<InsertElementInst, 3> { |
| 1991 | }; |
| 1992 | |
| 1993 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() { return OperandTraits<InsertElementInst>::op_begin(this ); } InsertElementInst::const_op_iterator InsertElementInst:: op_begin() const { return OperandTraits<InsertElementInst> ::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst ::op_iterator InsertElementInst::op_end() { return OperandTraits <InsertElementInst>::op_end(this); } InsertElementInst:: const_op_iterator InsertElementInst::op_end() const { return OperandTraits <InsertElementInst>::op_end(const_cast<InsertElementInst *>(this)); } Value *InsertElementInst::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null<Value >( OperandTraits<InsertElementInst>::op_begin(const_cast <InsertElementInst*>(this))[i_nocapture].get()); } void InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((void)0); OperandTraits<InsertElementInst>::op_begin (this)[i_nocapture] = Val_nocapture; } unsigned InsertElementInst ::getNumOperands() const { return OperandTraits<InsertElementInst >::operands(this); } template <int Idx_nocapture> Use &InsertElementInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & InsertElementInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
| 1994 | |
| 1995 | //===----------------------------------------------------------------------===// |
| 1996 | // ShuffleVectorInst Class |
| 1997 | //===----------------------------------------------------------------------===// |
| 1998 | |
| 1999 | constexpr int UndefMaskElem = -1; |
| 2000 | |
| 2001 | /// This instruction constructs a fixed permutation of two |
| 2002 | /// input vectors. |
| 2003 | /// |
| 2004 | /// For each element of the result vector, the shuffle mask selects an element |
| 2005 | /// from one of the input vectors to copy to the result. Non-negative elements |
| 2006 | /// in the mask represent an index into the concatenated pair of input vectors. |
| 2007 | /// UndefMaskElem (-1) specifies that the result element is undefined. |
| 2008 | /// |
| 2009 | /// For scalable vectors, all the elements of the mask must be 0 or -1. This |
| 2010 | /// requirement may be relaxed in the future. |
| 2011 | class ShuffleVectorInst : public Instruction { |
| 2012 | SmallVector<int, 4> ShuffleMask; |
| 2013 | Constant *ShuffleMaskForBitcode; |
| 2014 | |
| 2015 | protected: |
| 2016 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 2017 | friend class Instruction; |
| 2018 | |
| 2019 | ShuffleVectorInst *cloneImpl() const; |
| 2020 | |
| 2021 | public: |
| 2022 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
| 2023 | const Twine &NameStr = "", |
| 2024 | Instruction *InsertBefor = nullptr); |
| 2025 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
| 2026 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 2027 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
| 2028 | const Twine &NameStr = "", |
| 2029 | Instruction *InsertBefor = nullptr); |
| 2030 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
| 2031 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 2032 | |
| 2033 | void *operator new(size_t S) { return User::operator new(S, 2); } |
| 2034 | void operator delete(void *Ptr) { return User::operator delete(Ptr); } |
| 2035 | |
| 2036 | /// Swap the operands and adjust the mask to preserve the semantics |
| 2037 | /// of the instruction. |
| 2038 | void commute(); |
| 2039 | |
| 2040 | /// Return true if a shufflevector instruction can be |
| 2041 | /// formed with the specified operands. |
| 2042 | static bool isValidOperands(const Value *V1, const Value *V2, |
| 2043 | const Value *Mask); |
| 2044 | static bool isValidOperands(const Value *V1, const Value *V2, |
| 2045 | ArrayRef<int> Mask); |
| 2046 | |
| 2047 | /// Overload to return most specific vector type. |
| 2048 | /// |
| 2049 | VectorType *getType() const { |
| 2050 | return cast<VectorType>(Instruction::getType()); |
| 2051 | } |
| 2052 | |
| 2053 | /// Transparently provide more efficient getOperand methods. |
| 2054 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 2055 | |
| 2056 | /// Return the shuffle mask value of this instruction for the given element |
| 2057 | /// index. Return UndefMaskElem if the element is undef. |
| 2058 | int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; } |
| 2059 | |
| 2060 | /// Convert the input shuffle mask operand to a vector of integers. Undefined |
| 2061 | /// elements of the mask are returned as UndefMaskElem. |
| 2062 | static void getShuffleMask(const Constant *Mask, |
| 2063 | SmallVectorImpl<int> &Result); |
| 2064 | |
| 2065 | /// Return the mask for this instruction as a vector of integers. Undefined |
| 2066 | /// elements of the mask are returned as UndefMaskElem. |
| 2067 | void getShuffleMask(SmallVectorImpl<int> &Result) const { |
| 2068 | Result.assign(ShuffleMask.begin(), ShuffleMask.end()); |
| 2069 | } |
| 2070 | |
| 2071 | /// Return the mask for this instruction, for use in bitcode. |
| 2072 | /// |
| 2073 | /// TODO: This is temporary until we decide a new bitcode encoding for |
| 2074 | /// shufflevector. |
| 2075 | Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; } |
| 2076 | |
| 2077 | static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask, |
| 2078 | Type *ResultTy); |
| 2079 | |
| 2080 | void setShuffleMask(ArrayRef<int> Mask); |
| 2081 | |
| 2082 | ArrayRef<int> getShuffleMask() const { return ShuffleMask; } |
| 2083 | |
| 2084 | /// Return true if this shuffle returns a vector with a different number of |
| 2085 | /// elements than its source vectors. |
| 2086 | /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3> |
| 2087 | /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5> |
| 2088 | bool changesLength() const { |
| 2089 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
| 2090 | ->getElementCount() |
| 2091 | .getKnownMinValue(); |
| 2092 | unsigned NumMaskElts = ShuffleMask.size(); |
| 2093 | return NumSourceElts != NumMaskElts; |
| 2094 | } |
| 2095 | |
| 2096 | /// Return true if this shuffle returns a vector with a greater number of |
| 2097 | /// elements than its source vectors. |
| 2098 | /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3> |
| 2099 | bool increasesLength() const { |
| 2100 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
| 2101 | ->getElementCount() |
| 2102 | .getKnownMinValue(); |
| 2103 | unsigned NumMaskElts = ShuffleMask.size(); |
| 2104 | return NumSourceElts < NumMaskElts; |
| 2105 | } |
| 2106 | |
| 2107 | /// Return true if this shuffle mask chooses elements from exactly one source |
| 2108 | /// vector. |
| 2109 | /// Example: <7,5,undef,7> |
| 2110 | /// This assumes that vector operands are the same length as the mask. |
| 2111 | static bool isSingleSourceMask(ArrayRef<int> Mask); |
| 2112 | static bool isSingleSourceMask(const Constant *Mask) { |
| 2113 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((void)0); |
| 2114 | SmallVector<int, 16> MaskAsInts; |
| 2115 | getShuffleMask(Mask, MaskAsInts); |
| 2116 | return isSingleSourceMask(MaskAsInts); |
| 2117 | } |
| 2118 | |
| 2119 | /// Return true if this shuffle chooses elements from exactly one source |
| 2120 | /// vector without changing the length of that vector. |
| 2121 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3> |
| 2122 | /// TODO: Optionally allow length-changing shuffles. |
| 2123 | bool isSingleSource() const { |
| 2124 | return !changesLength() && isSingleSourceMask(ShuffleMask); |
| 2125 | } |
| 2126 | |
| 2127 | /// Return true if this shuffle mask chooses elements from exactly one source |
| 2128 | /// vector without lane crossings. A shuffle using this mask is not |
| 2129 | /// necessarily a no-op because it may change the number of elements from its |
| 2130 | /// input vectors or it may provide demanded bits knowledge via undef lanes. |
| 2131 | /// Example: <undef,undef,2,3> |
| 2132 | static bool isIdentityMask(ArrayRef<int> Mask); |
| 2133 | static bool isIdentityMask(const Constant *Mask) { |
| 2134 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((void)0); |
| 2135 | SmallVector<int, 16> MaskAsInts; |
| 2136 | getShuffleMask(Mask, MaskAsInts); |
| 2137 | return isIdentityMask(MaskAsInts); |
| 2138 | } |
| 2139 | |
| 2140 | /// Return true if this shuffle chooses elements from exactly one source |
| 2141 | /// vector without lane crossings and does not change the number of elements |
| 2142 | /// from its input vectors. |
| 2143 | /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef> |
| 2144 | bool isIdentity() const { |
| 2145 | return !changesLength() && isIdentityMask(ShuffleMask); |
| 2146 | } |
| 2147 | |
| 2148 | /// Return true if this shuffle lengthens exactly one source vector with |
| 2149 | /// undefs in the high elements. |
| 2150 | bool isIdentityWithPadding() const; |
| 2151 | |
| 2152 | /// Return true if this shuffle extracts the first N elements of exactly one |
| 2153 | /// source vector. |
| 2154 | bool isIdentityWithExtract() const; |
| 2155 | |
| 2156 | /// Return true if this shuffle concatenates its 2 source vectors. This |
| 2157 | /// returns false if either input is undefined. In that case, the shuffle is |
| 2158 | /// is better classified as an identity with padding operation. |
| 2159 | bool isConcat() const; |
| 2160 | |
| 2161 | /// Return true if this shuffle mask chooses elements from its source vectors |
| 2162 | /// without lane crossings. A shuffle using this mask would be |
| 2163 | /// equivalent to a vector select with a constant condition operand. |
| 2164 | /// Example: <4,1,6,undef> |
| 2165 | /// This returns false if the mask does not choose from both input vectors. |
| 2166 | /// In that case, the shuffle is better classified as an identity shuffle. |
| 2167 | /// This assumes that vector operands are the same length as the mask |
| 2168 | /// (a length-changing shuffle can never be equivalent to a vector select). |
| 2169 | static bool isSelectMask(ArrayRef<int> Mask); |
| 2170 | static bool isSelectMask(const Constant *Mask) { |
| 2171 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((void)0); |
| 2172 | SmallVector<int, 16> MaskAsInts; |
| 2173 | getShuffleMask(Mask, MaskAsInts); |
| 2174 | return isSelectMask(MaskAsInts); |
| 2175 | } |
| 2176 | |
| 2177 | /// Return true if this shuffle chooses elements from its source vectors |
| 2178 | /// without lane crossings and all operands have the same number of elements. |
| 2179 | /// In other words, this shuffle is equivalent to a vector select with a |
| 2180 | /// constant condition operand. |
| 2181 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3> |
| 2182 | /// This returns false if the mask does not choose from both input vectors. |
| 2183 | /// In that case, the shuffle is better classified as an identity shuffle. |
| 2184 | /// TODO: Optionally allow length-changing shuffles. |
| 2185 | bool isSelect() const { |
| 2186 | return !changesLength() && isSelectMask(ShuffleMask); |
| 2187 | } |
| 2188 | |
| 2189 | /// Return true if this shuffle mask swaps the order of elements from exactly |
| 2190 | /// one source vector. |
| 2191 | /// Example: <7,6,undef,4> |
| 2192 | /// This assumes that vector operands are the same length as the mask. |
| 2193 | static bool isReverseMask(ArrayRef<int> Mask); |
| 2194 | static bool isReverseMask(const Constant *Mask) { |
| 2195 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((void)0); |
| 2196 | SmallVector<int, 16> MaskAsInts; |
| 2197 | getShuffleMask(Mask, MaskAsInts); |
| 2198 | return isReverseMask(MaskAsInts); |
| 2199 | } |
| 2200 | |
| 2201 | /// Return true if this shuffle swaps the order of elements from exactly |
| 2202 | /// one source vector. |
| 2203 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef> |
| 2204 | /// TODO: Optionally allow length-changing shuffles. |
| 2205 | bool isReverse() const { |
| 2206 | return !changesLength() && isReverseMask(ShuffleMask); |
| 2207 | } |
| 2208 | |
| 2209 | /// Return true if this shuffle mask chooses all elements with the same value |
| 2210 | /// as the first element of exactly one source vector. |
| 2211 | /// Example: <4,undef,undef,4> |
| 2212 | /// This assumes that vector operands are the same length as the mask. |
| 2213 | static bool isZeroEltSplatMask(ArrayRef<int> Mask); |
| 2214 | static bool isZeroEltSplatMask(const Constant *Mask) { |
| 2215 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((void)0); |
| 2216 | SmallVector<int, 16> MaskAsInts; |
| 2217 | getShuffleMask(Mask, MaskAsInts); |
| 2218 | return isZeroEltSplatMask(MaskAsInts); |
| 2219 | } |
| 2220 | |
| 2221 | /// Return true if all elements of this shuffle are the same value as the |
| 2222 | /// first element of exactly one source vector without changing the length |
| 2223 | /// of that vector. |
| 2224 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0> |
| 2225 | /// TODO: Optionally allow length-changing shuffles. |
| 2226 | /// TODO: Optionally allow splats from other elements. |
| 2227 | bool isZeroEltSplat() const { |
| 2228 | return !changesLength() && isZeroEltSplatMask(ShuffleMask); |
| 2229 | } |
| 2230 | |
| 2231 | /// Return true if this shuffle mask is a transpose mask. |
| 2232 | /// Transpose vector masks transpose a 2xn matrix. They read corresponding |
| 2233 | /// even- or odd-numbered vector elements from two n-dimensional source |
| 2234 | /// vectors and write each result into consecutive elements of an |
| 2235 | /// n-dimensional destination vector. Two shuffles are necessary to complete |
| 2236 | /// the transpose, one for the even elements and another for the odd elements. |
| 2237 | /// This description closely follows how the TRN1 and TRN2 AArch64 |
| 2238 | /// instructions operate. |
| 2239 | /// |
| 2240 | /// For example, a simple 2x2 matrix can be transposed with: |
| 2241 | /// |
| 2242 | /// ; Original matrix |
| 2243 | /// m0 = < a, b > |
| 2244 | /// m1 = < c, d > |
| 2245 | /// |
| 2246 | /// ; Transposed matrix |
| 2247 | /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 > |
| 2248 | /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 > |
| 2249 | /// |
| 2250 | /// For matrices having greater than n columns, the resulting nx2 transposed |
| 2251 | /// matrix is stored in two result vectors such that one vector contains |
| 2252 | /// interleaved elements from all the even-numbered rows and the other vector |
| 2253 | /// contains interleaved elements from all the odd-numbered rows. For example, |
| 2254 | /// a 2x4 matrix can be transposed with: |
| 2255 | /// |
| 2256 | /// ; Original matrix |
| 2257 | /// m0 = < a, b, c, d > |
| 2258 | /// m1 = < e, f, g, h > |
| 2259 | /// |
| 2260 | /// ; Transposed matrix |
| 2261 | /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 > |
| 2262 | /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 > |
| 2263 | static bool isTransposeMask(ArrayRef<int> Mask); |
| 2264 | static bool isTransposeMask(const Constant *Mask) { |
| 2265 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((void)0); |
| 2266 | SmallVector<int, 16> MaskAsInts; |
| 2267 | getShuffleMask(Mask, MaskAsInts); |
| 2268 | return isTransposeMask(MaskAsInts); |
| 2269 | } |
| 2270 | |
| 2271 | /// Return true if this shuffle transposes the elements of its inputs without |
| 2272 | /// changing the length of the vectors. This operation may also be known as a |
| 2273 | /// merge or interleave. See the description for isTransposeMask() for the |
| 2274 | /// exact specification. |
| 2275 | /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6> |
| 2276 | bool isTranspose() const { |
| 2277 | return !changesLength() && isTransposeMask(ShuffleMask); |
| 2278 | } |
| 2279 | |
| 2280 | /// Return true if this shuffle mask is an extract subvector mask. |
| 2281 | /// A valid extract subvector mask returns a smaller vector from a single |
| 2282 | /// source operand. The base extraction index is returned as well. |
| 2283 | static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, |
| 2284 | int &Index); |
| 2285 | static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts, |
| 2286 | int &Index) { |
| 2287 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((void)0); |
| 2288 | // Not possible to express a shuffle mask for a scalable vector for this |
| 2289 | // case. |
| 2290 | if (isa<ScalableVectorType>(Mask->getType())) |
| 2291 | return false; |
| 2292 | SmallVector<int, 16> MaskAsInts; |
| 2293 | getShuffleMask(Mask, MaskAsInts); |
| 2294 | return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index); |
| 2295 | } |
| 2296 | |
| 2297 | /// Return true if this shuffle mask is an extract subvector mask. |
| 2298 | bool isExtractSubvectorMask(int &Index) const { |
| 2299 | // Not possible to express a shuffle mask for a scalable vector for this |
| 2300 | // case. |
| 2301 | if (isa<ScalableVectorType>(getType())) |
| 2302 | return false; |
| 2303 | |
| 2304 | int NumSrcElts = |
| 2305 | cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
| 2306 | return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index); |
| 2307 | } |
| 2308 | |
| 2309 | /// Change values in a shuffle permute mask assuming the two vector operands |
| 2310 | /// of length InVecNumElts have swapped position. |
| 2311 | static void commuteShuffleMask(MutableArrayRef<int> Mask, |
| 2312 | unsigned InVecNumElts) { |
| 2313 | for (int &Idx : Mask) { |
| 2314 | if (Idx == -1) |
| 2315 | continue; |
| 2316 | Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; |
| 2317 | assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((void)0) |
| 2318 | "shufflevector mask index out of range")((void)0); |
| 2319 | } |
| 2320 | } |
| 2321 | |
| 2322 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 2323 | static bool classof(const Instruction *I) { |
| 2324 | return I->getOpcode() == Instruction::ShuffleVector; |
| 2325 | } |
| 2326 | static bool classof(const Value *V) { |
| 2327 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 2328 | } |
| 2329 | }; |
| 2330 | |
| 2331 | template <> |
| 2332 | struct OperandTraits<ShuffleVectorInst> |
| 2333 | : public FixedNumOperandTraits<ShuffleVectorInst, 2> {}; |
| 2334 | |
| 2335 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() { return OperandTraits<ShuffleVectorInst>::op_begin(this ); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst:: op_begin() const { return OperandTraits<ShuffleVectorInst> ::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst ::op_iterator ShuffleVectorInst::op_end() { return OperandTraits <ShuffleVectorInst>::op_end(this); } ShuffleVectorInst:: const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits <ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst *>(this)); } Value *ShuffleVectorInst::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null<Value >( OperandTraits<ShuffleVectorInst>::op_begin(const_cast <ShuffleVectorInst*>(this))[i_nocapture].get()); } void ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((void)0); OperandTraits<ShuffleVectorInst>::op_begin (this)[i_nocapture] = Val_nocapture; } unsigned ShuffleVectorInst ::getNumOperands() const { return OperandTraits<ShuffleVectorInst >::operands(this); } template <int Idx_nocapture> Use &ShuffleVectorInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & ShuffleVectorInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
| 2336 | |
| 2337 | //===----------------------------------------------------------------------===// |
| 2338 | // ExtractValueInst Class |
| 2339 | //===----------------------------------------------------------------------===// |
| 2340 | |
| 2341 | /// This instruction extracts a struct member or array |
| 2342 | /// element value from an aggregate value. |
| 2343 | /// |
| 2344 | class ExtractValueInst : public UnaryInstruction { |
| 2345 | SmallVector<unsigned, 4> Indices; |
| 2346 | |
| 2347 | ExtractValueInst(const ExtractValueInst &EVI); |
| 2348 | |
| 2349 | /// Constructors - Create a extractvalue instruction with a base aggregate |
| 2350 | /// value and a list of indices. The first ctor can optionally insert before |
| 2351 | /// an existing instruction, the second appends the new instruction to the |
| 2352 | /// specified BasicBlock. |
| 2353 | inline ExtractValueInst(Value *Agg, |
| 2354 | ArrayRef<unsigned> Idxs, |
| 2355 | const Twine &NameStr, |
| 2356 | Instruction *InsertBefore); |
| 2357 | inline ExtractValueInst(Value *Agg, |
| 2358 | ArrayRef<unsigned> Idxs, |
| 2359 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 2360 | |
| 2361 | void init(ArrayRef<unsigned> Idxs, const Twine &NameStr); |
| 2362 | |
| 2363 | protected: |
| 2364 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 2365 | friend class Instruction; |
| 2366 | |
| 2367 | ExtractValueInst *cloneImpl() const; |
| 2368 | |
| 2369 | public: |
| 2370 | static ExtractValueInst *Create(Value *Agg, |
| 2371 | ArrayRef<unsigned> Idxs, |
| 2372 | const Twine &NameStr = "", |
| 2373 | Instruction *InsertBefore = nullptr) { |
| 2374 | return new |
| 2375 | ExtractValueInst(Agg, Idxs, NameStr, InsertBefore); |
| 2376 | } |
| 2377 | |
| 2378 | static ExtractValueInst *Create(Value *Agg, |
| 2379 | ArrayRef<unsigned> Idxs, |
| 2380 | const Twine &NameStr, |
| 2381 | BasicBlock *InsertAtEnd) { |
| 2382 | return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd); |
| 2383 | } |
| 2384 | |
| 2385 | /// Returns the type of the element that would be extracted |
| 2386 | /// with an extractvalue instruction with the specified parameters. |
| 2387 | /// |
| 2388 | /// Null is returned if the indices are invalid for the specified type. |
| 2389 | static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs); |
| 2390 | |
| 2391 | using idx_iterator = const unsigned*; |
| 2392 | |
| 2393 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
| 2394 | inline idx_iterator idx_end() const { return Indices.end(); } |
| 2395 | inline iterator_range<idx_iterator> indices() const { |
| 2396 | return make_range(idx_begin(), idx_end()); |
| 2397 | } |
| 2398 | |
| 2399 | Value *getAggregateOperand() { |
| 2400 | return getOperand(0); |
| 2401 | } |
| 2402 | const Value *getAggregateOperand() const { |
| 2403 | return getOperand(0); |
| 2404 | } |
| 2405 | static unsigned getAggregateOperandIndex() { |
| 2406 | return 0U; // get index for modifying correct operand |
| 2407 | } |
| 2408 | |
| 2409 | ArrayRef<unsigned> getIndices() const { |
| 2410 | return Indices; |
| 2411 | } |
| 2412 | |
| 2413 | unsigned getNumIndices() const { |
| 2414 | return (unsigned)Indices.size(); |
| 2415 | } |
| 2416 | |
| 2417 | bool hasIndices() const { |
| 2418 | return true; |
| 2419 | } |
| 2420 | |
| 2421 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 2422 | static bool classof(const Instruction *I) { |
| 2423 | return I->getOpcode() == Instruction::ExtractValue; |
| 2424 | } |
| 2425 | static bool classof(const Value *V) { |
| 2426 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 2427 | } |
| 2428 | }; |
| 2429 | |
| 2430 | ExtractValueInst::ExtractValueInst(Value *Agg, |
| 2431 | ArrayRef<unsigned> Idxs, |
| 2432 | const Twine &NameStr, |
| 2433 | Instruction *InsertBefore) |
| 2434 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
| 2435 | ExtractValue, Agg, InsertBefore) { |
| 2436 | init(Idxs, NameStr); |
| 2437 | } |
| 2438 | |
| 2439 | ExtractValueInst::ExtractValueInst(Value *Agg, |
| 2440 | ArrayRef<unsigned> Idxs, |
| 2441 | const Twine &NameStr, |
| 2442 | BasicBlock *InsertAtEnd) |
| 2443 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
| 2444 | ExtractValue, Agg, InsertAtEnd) { |
| 2445 | init(Idxs, NameStr); |
| 2446 | } |
| 2447 | |
| 2448 | //===----------------------------------------------------------------------===// |
| 2449 | // InsertValueInst Class |
| 2450 | //===----------------------------------------------------------------------===// |
| 2451 | |
| 2452 | /// This instruction inserts a struct field of array element |
| 2453 | /// value into an aggregate value. |
| 2454 | /// |
| 2455 | class InsertValueInst : public Instruction { |
| 2456 | SmallVector<unsigned, 4> Indices; |
| 2457 | |
| 2458 | InsertValueInst(const InsertValueInst &IVI); |
| 2459 | |
| 2460 | /// Constructors - Create a insertvalue instruction with a base aggregate |
| 2461 | /// value, a value to insert, and a list of indices. The first ctor can |
| 2462 | /// optionally insert before an existing instruction, the second appends |
| 2463 | /// the new instruction to the specified BasicBlock. |
| 2464 | inline InsertValueInst(Value *Agg, Value *Val, |
| 2465 | ArrayRef<unsigned> Idxs, |
| 2466 | const Twine &NameStr, |
| 2467 | Instruction *InsertBefore); |
| 2468 | inline InsertValueInst(Value *Agg, Value *Val, |
| 2469 | ArrayRef<unsigned> Idxs, |
| 2470 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 2471 | |
| 2472 | /// Constructors - These two constructors are convenience methods because one |
| 2473 | /// and two index insertvalue instructions are so common. |
| 2474 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, |
| 2475 | const Twine &NameStr = "", |
| 2476 | Instruction *InsertBefore = nullptr); |
| 2477 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr, |
| 2478 | BasicBlock *InsertAtEnd); |
| 2479 | |
| 2480 | void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, |
| 2481 | const Twine &NameStr); |
| 2482 | |
| 2483 | protected: |
| 2484 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 2485 | friend class Instruction; |
| 2486 | |
| 2487 | InsertValueInst *cloneImpl() const; |
| 2488 | |
| 2489 | public: |
| 2490 | // allocate space for exactly two operands |
| 2491 | void *operator new(size_t S) { return User::operator new(S, 2); } |
| 2492 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 2493 | |
| 2494 | static InsertValueInst *Create(Value *Agg, Value *Val, |
| 2495 | ArrayRef<unsigned> Idxs, |
| 2496 | const Twine &NameStr = "", |
| 2497 | Instruction *InsertBefore = nullptr) { |
| 2498 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore); |
| 2499 | } |
| 2500 | |
| 2501 | static InsertValueInst *Create(Value *Agg, Value *Val, |
| 2502 | ArrayRef<unsigned> Idxs, |
| 2503 | const Twine &NameStr, |
| 2504 | BasicBlock *InsertAtEnd) { |
| 2505 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd); |
| 2506 | } |
| 2507 | |
| 2508 | /// Transparently provide more efficient getOperand methods. |
| 2509 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 2510 | |
| 2511 | using idx_iterator = const unsigned*; |
| 2512 | |
| 2513 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
| 2514 | inline idx_iterator idx_end() const { return Indices.end(); } |
| 2515 | inline iterator_range<idx_iterator> indices() const { |
| 2516 | return make_range(idx_begin(), idx_end()); |
| 2517 | } |
| 2518 | |
| 2519 | Value *getAggregateOperand() { |
| 2520 | return getOperand(0); |
| 2521 | } |
| 2522 | const Value *getAggregateOperand() const { |
| 2523 | return getOperand(0); |
| 2524 | } |
| 2525 | static unsigned getAggregateOperandIndex() { |
| 2526 | return 0U; // get index for modifying correct operand |
| 2527 | } |
| 2528 | |
| 2529 | Value *getInsertedValueOperand() { |
| 2530 | return getOperand(1); |
| 2531 | } |
| 2532 | const Value *getInsertedValueOperand() const { |
| 2533 | return getOperand(1); |
| 2534 | } |
| 2535 | static unsigned getInsertedValueOperandIndex() { |
| 2536 | return 1U; // get index for modifying correct operand |
| 2537 | } |
| 2538 | |
| 2539 | ArrayRef<unsigned> getIndices() const { |
| 2540 | return Indices; |
| 2541 | } |
| 2542 | |
| 2543 | unsigned getNumIndices() const { |
| 2544 | return (unsigned)Indices.size(); |
| 2545 | } |
| 2546 | |
| 2547 | bool hasIndices() const { |
| 2548 | return true; |
| 2549 | } |
| 2550 | |
| 2551 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 2552 | static bool classof(const Instruction *I) { |
| 2553 | return I->getOpcode() == Instruction::InsertValue; |
| 2554 | } |
| 2555 | static bool classof(const Value *V) { |
| 2556 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 2557 | } |
| 2558 | }; |
| 2559 | |
| 2560 | template <> |
| 2561 | struct OperandTraits<InsertValueInst> : |
| 2562 | public FixedNumOperandTraits<InsertValueInst, 2> { |
| 2563 | }; |
| 2564 | |
| 2565 | InsertValueInst::InsertValueInst(Value *Agg, |
| 2566 | Value *Val, |
| 2567 | ArrayRef<unsigned> Idxs, |
| 2568 | const Twine &NameStr, |
| 2569 | Instruction *InsertBefore) |
| 2570 | : Instruction(Agg->getType(), InsertValue, |
| 2571 | OperandTraits<InsertValueInst>::op_begin(this), |
| 2572 | 2, InsertBefore) { |
| 2573 | init(Agg, Val, Idxs, NameStr); |
| 2574 | } |
| 2575 | |
| 2576 | InsertValueInst::InsertValueInst(Value *Agg, |
| 2577 | Value *Val, |
| 2578 | ArrayRef<unsigned> Idxs, |
| 2579 | const Twine &NameStr, |
| 2580 | BasicBlock *InsertAtEnd) |
| 2581 | : Instruction(Agg->getType(), InsertValue, |
| 2582 | OperandTraits<InsertValueInst>::op_begin(this), |
| 2583 | 2, InsertAtEnd) { |
| 2584 | init(Agg, Val, Idxs, NameStr); |
| 2585 | } |
| 2586 | |
| 2587 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst ::const_op_iterator InsertValueInst::op_begin() const { return OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst ::op_end() { return OperandTraits<InsertValueInst>::op_end (this); } InsertValueInst::const_op_iterator InsertValueInst:: op_end() const { return OperandTraits<InsertValueInst>:: op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<InsertValueInst>::op_begin (const_cast<InsertValueInst*>(this))[i_nocapture].get() ); } void InsertValueInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((void)0); OperandTraits<InsertValueInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned InsertValueInst::getNumOperands() const { return OperandTraits <InsertValueInst>::operands(this); } template <int Idx_nocapture > Use &InsertValueInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &InsertValueInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
| 2588 | |
| 2589 | //===----------------------------------------------------------------------===// |
| 2590 | // PHINode Class |
| 2591 | //===----------------------------------------------------------------------===// |
| 2592 | |
| 2593 | // PHINode - The PHINode class is used to represent the magical mystical PHI |
| 2594 | // node, that can not exist in nature, but can be synthesized in a computer |
| 2595 | // scientist's overactive imagination. |
| 2596 | // |
| 2597 | class PHINode : public Instruction { |
| 2598 | /// The number of operands actually allocated. NumOperands is |
| 2599 | /// the number actually in use. |
| 2600 | unsigned ReservedSpace; |
| 2601 | |
| 2602 | PHINode(const PHINode &PN); |
| 2603 | |
| 2604 | explicit PHINode(Type *Ty, unsigned NumReservedValues, |
| 2605 | const Twine &NameStr = "", |
| 2606 | Instruction *InsertBefore = nullptr) |
| 2607 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore), |
| 2608 | ReservedSpace(NumReservedValues) { |
| 2609 | assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!")((void)0); |
| 2610 | setName(NameStr); |
| 2611 | allocHungoffUses(ReservedSpace); |
| 2612 | } |
| 2613 | |
| 2614 | PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, |
| 2615 | BasicBlock *InsertAtEnd) |
| 2616 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd), |
| 2617 | ReservedSpace(NumReservedValues) { |
| 2618 | assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!")((void)0); |
| 2619 | setName(NameStr); |
| 2620 | allocHungoffUses(ReservedSpace); |
| 2621 | } |
| 2622 | |
| 2623 | protected: |
| 2624 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 2625 | friend class Instruction; |
| 2626 | |
| 2627 | PHINode *cloneImpl() const; |
| 2628 | |
| 2629 | // allocHungoffUses - this is more complicated than the generic |
| 2630 | // User::allocHungoffUses, because we have to allocate Uses for the incoming |
| 2631 | // values and pointers to the incoming blocks, all in one allocation. |
| 2632 | void allocHungoffUses(unsigned N) { |
| 2633 | User::allocHungoffUses(N, /* IsPhi */ true); |
| 2634 | } |
| 2635 | |
| 2636 | public: |
| 2637 | /// Constructors - NumReservedValues is a hint for the number of incoming |
| 2638 | /// edges that this phi node will have (use 0 if you really have no idea). |
| 2639 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
| 2640 | const Twine &NameStr = "", |
| 2641 | Instruction *InsertBefore = nullptr) { |
| 2642 | return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore); |
| 2643 | } |
| 2644 | |
| 2645 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
| 2646 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 2647 | return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd); |
| 2648 | } |
| 2649 | |
| 2650 | /// Provide fast operand accessors |
| 2651 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 2652 | |
| 2653 | // Block iterator interface. This provides access to the list of incoming |
| 2654 | // basic blocks, which parallels the list of incoming values. |
| 2655 | |
| 2656 | using block_iterator = BasicBlock **; |
| 2657 | using const_block_iterator = BasicBlock * const *; |
| 2658 | |
| 2659 | block_iterator block_begin() { |
| 2660 | return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace); |
| 2661 | } |
| 2662 | |
| 2663 | const_block_iterator block_begin() const { |
| 2664 | return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace); |
| 2665 | } |
| 2666 | |
| 2667 | block_iterator block_end() { |
| 2668 | return block_begin() + getNumOperands(); |
| 2669 | } |
| 2670 | |
| 2671 | const_block_iterator block_end() const { |
| 2672 | return block_begin() + getNumOperands(); |
| 2673 | } |
| 2674 | |
| 2675 | iterator_range<block_iterator> blocks() { |
| 2676 | return make_range(block_begin(), block_end()); |
| 2677 | } |
| 2678 | |
| 2679 | iterator_range<const_block_iterator> blocks() const { |
| 2680 | return make_range(block_begin(), block_end()); |
| 2681 | } |
| 2682 | |
| 2683 | op_range incoming_values() { return operands(); } |
| 2684 | |
| 2685 | const_op_range incoming_values() const { return operands(); } |
| 2686 | |
| 2687 | /// Return the number of incoming edges |
| 2688 | /// |
| 2689 | unsigned getNumIncomingValues() const { return getNumOperands(); } |
| 2690 | |
| 2691 | /// Return incoming value number x |
| 2692 | /// |
| 2693 | Value *getIncomingValue(unsigned i) const { |
| 2694 | return getOperand(i); |
| 2695 | } |
| 2696 | void setIncomingValue(unsigned i, Value *V) { |
| 2697 | assert(V && "PHI node got a null value!")((void)0); |
| 2698 | assert(getType() == V->getType() &&((void)0) |
| 2699 | "All operands to PHI node must be the same type as the PHI node!")((void)0); |
| 2700 | setOperand(i, V); |
| 2701 | } |
| 2702 | |
| 2703 | static unsigned getOperandNumForIncomingValue(unsigned i) { |
| 2704 | return i; |
| 2705 | } |
| 2706 | |
| 2707 | static unsigned getIncomingValueNumForOperand(unsigned i) { |
| 2708 | return i; |
| 2709 | } |
| 2710 | |
| 2711 | /// Return incoming basic block number @p i. |
| 2712 | /// |
| 2713 | BasicBlock *getIncomingBlock(unsigned i) const { |
| 2714 | return block_begin()[i]; |
| 2715 | } |
| 2716 | |
| 2717 | /// Return incoming basic block corresponding |
| 2718 | /// to an operand of the PHI. |
| 2719 | /// |
| 2720 | BasicBlock *getIncomingBlock(const Use &U) const { |
| 2721 | assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((void)0); |
| 2722 | return getIncomingBlock(unsigned(&U - op_begin())); |
| 2723 | } |
| 2724 | |
| 2725 | /// Return incoming basic block corresponding |
| 2726 | /// to value use iterator. |
| 2727 | /// |
| 2728 | BasicBlock *getIncomingBlock(Value::const_user_iterator I) const { |
| 2729 | return getIncomingBlock(I.getUse()); |
| 2730 | } |
| 2731 | |
| 2732 | void setIncomingBlock(unsigned i, BasicBlock *BB) { |
| 2733 | assert(BB && "PHI node got a null basic block!")((void)0); |
| 2734 | block_begin()[i] = BB; |
| 2735 | } |
| 2736 | |
| 2737 | /// Replace every incoming basic block \p Old to basic block \p New. |
| 2738 | void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) { |
| 2739 | assert(New && Old && "PHI node got a null basic block!")((void)0); |
| 2740 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
| 2741 | if (getIncomingBlock(Op) == Old) |
| 2742 | setIncomingBlock(Op, New); |
| 2743 | } |
| 2744 | |
| 2745 | /// Add an incoming value to the end of the PHI list |
| 2746 | /// |
| 2747 | void addIncoming(Value *V, BasicBlock *BB) { |
| 2748 | if (getNumOperands() == ReservedSpace) |
| 2749 | growOperands(); // Get more space! |
| 2750 | // Initialize some new operands. |
| 2751 | setNumHungOffUseOperands(getNumOperands() + 1); |
| 2752 | setIncomingValue(getNumOperands() - 1, V); |
| 2753 | setIncomingBlock(getNumOperands() - 1, BB); |
| 2754 | } |
| 2755 | |
| 2756 | /// Remove an incoming value. This is useful if a |
| 2757 | /// predecessor basic block is deleted. The value removed is returned. |
| 2758 | /// |
| 2759 | /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty |
| 2760 | /// is true), the PHI node is destroyed and any uses of it are replaced with |
| 2761 | /// dummy values. The only time there should be zero incoming values to a PHI |
| 2762 | /// node is when the block is dead, so this strategy is sound. |
| 2763 | /// |
| 2764 | Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true); |
| 2765 | |
| 2766 | Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) { |
| 2767 | int Idx = getBasicBlockIndex(BB); |
| 2768 | assert(Idx >= 0 && "Invalid basic block argument to remove!")((void)0); |
| 2769 | return removeIncomingValue(Idx, DeletePHIIfEmpty); |
| 2770 | } |
| 2771 | |
| 2772 | /// Return the first index of the specified basic |
| 2773 | /// block in the value list for this PHI. Returns -1 if no instance. |
| 2774 | /// |
| 2775 | int getBasicBlockIndex(const BasicBlock *BB) const { |
| 2776 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
| 2777 | if (block_begin()[i] == BB) |
| 2778 | return i; |
| 2779 | return -1; |
| 2780 | } |
| 2781 | |
| 2782 | Value *getIncomingValueForBlock(const BasicBlock *BB) const { |
| 2783 | int Idx = getBasicBlockIndex(BB); |
| 2784 | assert(Idx >= 0 && "Invalid basic block argument!")((void)0); |
| 2785 | return getIncomingValue(Idx); |
| 2786 | } |
| 2787 | |
| 2788 | /// Set every incoming value(s) for block \p BB to \p V. |
| 2789 | void setIncomingValueForBlock(const BasicBlock *BB, Value *V) { |
| 2790 | assert(BB && "PHI node got a null basic block!")((void)0); |
| 2791 | bool Found = false; |
| 2792 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
| 2793 | if (getIncomingBlock(Op) == BB) { |
| 2794 | Found = true; |
| 2795 | setIncomingValue(Op, V); |
| 2796 | } |
| 2797 | (void)Found; |
| 2798 | assert(Found && "Invalid basic block argument to set!")((void)0); |
| 2799 | } |
| 2800 | |
| 2801 | /// If the specified PHI node always merges together the |
| 2802 | /// same value, return the value, otherwise return null. |
| 2803 | Value *hasConstantValue() const; |
| 2804 | |
| 2805 | /// Whether the specified PHI node always merges |
| 2806 | /// together the same value, assuming undefs are equal to a unique |
| 2807 | /// non-undef value. |
| 2808 | bool hasConstantOrUndefValue() const; |
| 2809 | |
| 2810 | /// If the PHI node is complete which means all of its parent's predecessors |
| 2811 | /// have incoming value in this PHI, return true, otherwise return false. |
| 2812 | bool isComplete() const { |
| 2813 | return llvm::all_of(predecessors(getParent()), |
| 2814 | [this](const BasicBlock *Pred) { |
| 2815 | return getBasicBlockIndex(Pred) >= 0; |
| 2816 | }); |
| 2817 | } |
| 2818 | |
| 2819 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 2820 | static bool classof(const Instruction *I) { |
| 2821 | return I->getOpcode() == Instruction::PHI; |
| 2822 | } |
| 2823 | static bool classof(const Value *V) { |
| 2824 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 2825 | } |
| 2826 | |
| 2827 | private: |
| 2828 | void growOperands(); |
| 2829 | }; |
| 2830 | |
| 2831 | template <> |
| 2832 | struct OperandTraits<PHINode> : public HungoffOperandTraits<2> { |
| 2833 | }; |
| 2834 | |
| 2835 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits <PHINode>::op_begin(this); } PHINode::const_op_iterator PHINode::op_begin() const { return OperandTraits<PHINode> ::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator PHINode::op_end() { return OperandTraits<PHINode>::op_end (this); } PHINode::const_op_iterator PHINode::op_end() const { return OperandTraits<PHINode>::op_end(const_cast<PHINode *>(this)); } Value *PHINode::getOperand(unsigned i_nocapture ) const { ((void)0); return cast_or_null<Value>( OperandTraits <PHINode>::op_begin(const_cast<PHINode*>(this))[i_nocapture ].get()); } void PHINode::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((void)0); OperandTraits<PHINode>::op_begin (this)[i_nocapture] = Val_nocapture; } unsigned PHINode::getNumOperands () const { return OperandTraits<PHINode>::operands(this ); } template <int Idx_nocapture> Use &PHINode::Op( ) { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &PHINode::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
| 2836 | |
| 2837 | //===----------------------------------------------------------------------===// |
| 2838 | // LandingPadInst Class |
| 2839 | //===----------------------------------------------------------------------===// |
| 2840 | |
| 2841 | //===--------------------------------------------------------------------------- |
| 2842 | /// The landingpad instruction holds all of the information |
| 2843 | /// necessary to generate correct exception handling. The landingpad instruction |
| 2844 | /// cannot be moved from the top of a landing pad block, which itself is |
| 2845 | /// accessible only from the 'unwind' edge of an invoke. This uses the |
| 2846 | /// SubclassData field in Value to store whether or not the landingpad is a |
| 2847 | /// cleanup. |
| 2848 | /// |
| 2849 | class LandingPadInst : public Instruction { |
| 2850 | using CleanupField = BoolBitfieldElementT<0>; |
| 2851 | |
| 2852 | /// The number of operands actually allocated. NumOperands is |
| 2853 | /// the number actually in use. |
| 2854 | unsigned ReservedSpace; |
| 2855 | |
| 2856 | LandingPadInst(const LandingPadInst &LP); |
| 2857 | |
| 2858 | public: |
| 2859 | enum ClauseType { Catch, Filter }; |
| 2860 | |
| 2861 | private: |
| 2862 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
| 2863 | const Twine &NameStr, Instruction *InsertBefore); |
| 2864 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
| 2865 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 2866 | |
| 2867 | // Allocate space for exactly zero operands. |
| 2868 | void *operator new(size_t S) { return User::operator new(S); } |
| 2869 | |
| 2870 | void growOperands(unsigned Size); |
| 2871 | void init(unsigned NumReservedValues, const Twine &NameStr); |
| 2872 | |
| 2873 | protected: |
| 2874 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 2875 | friend class Instruction; |
| 2876 | |
| 2877 | LandingPadInst *cloneImpl() const; |
| 2878 | |
| 2879 | public: |
| 2880 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 2881 | |
| 2882 | /// Constructors - NumReservedClauses is a hint for the number of incoming |
| 2883 | /// clauses that this landingpad will have (use 0 if you really have no idea). |
| 2884 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
| 2885 | const Twine &NameStr = "", |
| 2886 | Instruction *InsertBefore = nullptr); |
| 2887 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
| 2888 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 2889 | |
| 2890 | /// Provide fast operand accessors |
| 2891 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 2892 | |
| 2893 | /// Return 'true' if this landingpad instruction is a |
| 2894 | /// cleanup. I.e., it should be run when unwinding even if its landing pad |
| 2895 | /// doesn't catch the exception. |
| 2896 | bool isCleanup() const { return getSubclassData<CleanupField>(); } |
| 2897 | |
| 2898 | /// Indicate that this landingpad instruction is a cleanup. |
| 2899 | void setCleanup(bool V) { setSubclassData<CleanupField>(V); } |
| 2900 | |
| 2901 | /// Add a catch or filter clause to the landing pad. |
| 2902 | void addClause(Constant *ClauseVal); |
| 2903 | |
| 2904 | /// Get the value of the clause at index Idx. Use isCatch/isFilter to |
| 2905 | /// determine what type of clause this is. |
| 2906 | Constant *getClause(unsigned Idx) const { |
| 2907 | return cast<Constant>(getOperandList()[Idx]); |
| 2908 | } |
| 2909 | |
| 2910 | /// Return 'true' if the clause and index Idx is a catch clause. |
| 2911 | bool isCatch(unsigned Idx) const { |
| 2912 | return !isa<ArrayType>(getOperandList()[Idx]->getType()); |
| 2913 | } |
| 2914 | |
| 2915 | /// Return 'true' if the clause and index Idx is a filter clause. |
| 2916 | bool isFilter(unsigned Idx) const { |
| 2917 | return isa<ArrayType>(getOperandList()[Idx]->getType()); |
| 2918 | } |
| 2919 | |
| 2920 | /// Get the number of clauses for this landing pad. |
| 2921 | unsigned getNumClauses() const { return getNumOperands(); } |
| 2922 | |
| 2923 | /// Grow the size of the operand list to accommodate the new |
| 2924 | /// number of clauses. |
| 2925 | void reserveClauses(unsigned Size) { growOperands(Size); } |
| 2926 | |
| 2927 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 2928 | static bool classof(const Instruction *I) { |
| 2929 | return I->getOpcode() == Instruction::LandingPad; |
| 2930 | } |
| 2931 | static bool classof(const Value *V) { |
| 2932 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 2933 | } |
| 2934 | }; |
| 2935 | |
| 2936 | template <> |
| 2937 | struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> { |
| 2938 | }; |
| 2939 | |
| 2940 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst ::const_op_iterator LandingPadInst::op_begin() const { return OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst ::op_end() { return OperandTraits<LandingPadInst>::op_end (this); } LandingPadInst::const_op_iterator LandingPadInst::op_end () const { return OperandTraits<LandingPadInst>::op_end (const_cast<LandingPadInst*>(this)); } Value *LandingPadInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<LandingPadInst>::op_begin( const_cast<LandingPadInst*>(this))[i_nocapture].get()); } void LandingPadInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((void)0); OperandTraits<LandingPadInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned LandingPadInst::getNumOperands() const { return OperandTraits <LandingPadInst>::operands(this); } template <int Idx_nocapture > Use &LandingPadInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &LandingPadInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
| 2941 | |
| 2942 | //===----------------------------------------------------------------------===// |
| 2943 | // ReturnInst Class |
| 2944 | //===----------------------------------------------------------------------===// |
| 2945 | |
| 2946 | //===--------------------------------------------------------------------------- |
| 2947 | /// Return a value (possibly void), from a function. Execution |
| 2948 | /// does not continue in this function any longer. |
| 2949 | /// |
| 2950 | class ReturnInst : public Instruction { |
| 2951 | ReturnInst(const ReturnInst &RI); |
| 2952 | |
| 2953 | private: |
| 2954 | // ReturnInst constructors: |
| 2955 | // ReturnInst() - 'ret void' instruction |
| 2956 | // ReturnInst( null) - 'ret void' instruction |
| 2957 | // ReturnInst(Value* X) - 'ret X' instruction |
| 2958 | // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I |
| 2959 | // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I |
| 2960 | // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B |
| 2961 | // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B |
| 2962 | // |
| 2963 | // NOTE: If the Value* passed is of type void then the constructor behaves as |
| 2964 | // if it was passed NULL. |
| 2965 | explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr, |
| 2966 | Instruction *InsertBefore = nullptr); |
| 2967 | ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd); |
| 2968 | explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
| 2969 | |
| 2970 | protected: |
| 2971 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 2972 | friend class Instruction; |
| 2973 | |
| 2974 | ReturnInst *cloneImpl() const; |
| 2975 | |
| 2976 | public: |
| 2977 | static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr, |
| 2978 | Instruction *InsertBefore = nullptr) { |
| 2979 | return new(!!retVal) ReturnInst(C, retVal, InsertBefore); |
| 2980 | } |
| 2981 | |
| 2982 | static ReturnInst* Create(LLVMContext &C, Value *retVal, |
| 2983 | BasicBlock *InsertAtEnd) { |
| 2984 | return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd); |
| 2985 | } |
| 2986 | |
| 2987 | static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) { |
| 2988 | return new(0) ReturnInst(C, InsertAtEnd); |
| 2989 | } |
| 2990 | |
| 2991 | /// Provide fast operand accessors |
| 2992 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 2993 | |
| 2994 | /// Convenience accessor. Returns null if there is no return value. |
| 2995 | Value *getReturnValue() const { |
| 2996 | return getNumOperands() != 0 ? getOperand(0) : nullptr; |
| 2997 | } |
| 2998 | |
| 2999 | unsigned getNumSuccessors() const { return 0; } |
| 3000 | |
| 3001 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 3002 | static bool classof(const Instruction *I) { |
| 3003 | return (I->getOpcode() == Instruction::Ret); |
| 3004 | } |
| 3005 | static bool classof(const Value *V) { |
| 3006 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 3007 | } |
| 3008 | |
| 3009 | private: |
| 3010 | BasicBlock *getSuccessor(unsigned idx) const { |
| 3011 | llvm_unreachable("ReturnInst has no successors!")__builtin_unreachable(); |
| 3012 | } |
| 3013 | |
| 3014 | void setSuccessor(unsigned idx, BasicBlock *B) { |
| 3015 | llvm_unreachable("ReturnInst has no successors!")__builtin_unreachable(); |
| 3016 | } |
| 3017 | }; |
| 3018 | |
| 3019 | template <> |
| 3020 | struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> { |
| 3021 | }; |
| 3022 | |
| 3023 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits <ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator ReturnInst::op_begin() const { return OperandTraits<ReturnInst >::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst ::op_iterator ReturnInst::op_end() { return OperandTraits< ReturnInst>::op_end(this); } ReturnInst::const_op_iterator ReturnInst::op_end() const { return OperandTraits<ReturnInst >::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<ReturnInst>::op_begin(const_cast <ReturnInst*>(this))[i_nocapture].get()); } void ReturnInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( void)0); OperandTraits<ReturnInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned ReturnInst::getNumOperands() const { return OperandTraits<ReturnInst>::operands(this); } template <int Idx_nocapture> Use &ReturnInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ReturnInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
| 3024 | |
| 3025 | //===----------------------------------------------------------------------===// |
| 3026 | // BranchInst Class |
| 3027 | //===----------------------------------------------------------------------===// |
| 3028 | |
| 3029 | //===--------------------------------------------------------------------------- |
| 3030 | /// Conditional or Unconditional Branch instruction. |
| 3031 | /// |
| 3032 | class BranchInst : public Instruction { |
| 3033 | /// Ops list - Branches are strange. The operands are ordered: |
| 3034 | /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because |
| 3035 | /// they don't have to check for cond/uncond branchness. These are mostly |
| 3036 | /// accessed relative from op_end(). |
| 3037 | BranchInst(const BranchInst &BI); |
| 3038 | // BranchInst constructors (where {B, T, F} are blocks, and C is a condition): |
| 3039 | // BranchInst(BB *B) - 'br B' |
| 3040 | // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F' |
| 3041 | // BranchInst(BB* B, Inst *I) - 'br B' insert before I |
| 3042 | // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I |
| 3043 | // BranchInst(BB* B, BB *I) - 'br B' insert at end |
| 3044 | // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end |
| 3045 | explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr); |
| 3046 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
| 3047 | Instruction *InsertBefore = nullptr); |
| 3048 | BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd); |
| 3049 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
| 3050 | BasicBlock *InsertAtEnd); |
| 3051 | |
| 3052 | void AssertOK(); |
| 3053 | |
| 3054 | protected: |
| 3055 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 3056 | friend class Instruction; |
| 3057 | |
| 3058 | BranchInst *cloneImpl() const; |
| 3059 | |
| 3060 | public: |
| 3061 | /// Iterator type that casts an operand to a basic block. |
| 3062 | /// |
| 3063 | /// This only makes sense because the successors are stored as adjacent |
| 3064 | /// operands for branch instructions. |
| 3065 | struct succ_op_iterator |
| 3066 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
| 3067 | std::random_access_iterator_tag, BasicBlock *, |
| 3068 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
| 3069 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
| 3070 | |
| 3071 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
| 3072 | BasicBlock *operator->() const { return operator*(); } |
| 3073 | }; |
| 3074 | |
| 3075 | /// The const version of `succ_op_iterator`. |
| 3076 | struct const_succ_op_iterator |
| 3077 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
| 3078 | std::random_access_iterator_tag, |
| 3079 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
| 3080 | const BasicBlock *> { |
| 3081 | explicit const_succ_op_iterator(const_value_op_iterator I) |
| 3082 | : iterator_adaptor_base(I) {} |
| 3083 | |
| 3084 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
| 3085 | const BasicBlock *operator->() const { return operator*(); } |
| 3086 | }; |
| 3087 | |
| 3088 | static BranchInst *Create(BasicBlock *IfTrue, |
| 3089 | Instruction *InsertBefore = nullptr) { |
| 3090 | return new(1) BranchInst(IfTrue, InsertBefore); |
| 3091 | } |
| 3092 | |
| 3093 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
| 3094 | Value *Cond, Instruction *InsertBefore = nullptr) { |
| 3095 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore); |
| 3096 | } |
| 3097 | |
| 3098 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) { |
| 3099 | return new(1) BranchInst(IfTrue, InsertAtEnd); |
| 3100 | } |
| 3101 | |
| 3102 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
| 3103 | Value *Cond, BasicBlock *InsertAtEnd) { |
| 3104 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd); |
| 3105 | } |
| 3106 | |
| 3107 | /// Transparently provide more efficient getOperand methods. |
| 3108 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 3109 | |
| 3110 | bool isUnconditional() const { return getNumOperands() == 1; } |
| 3111 | bool isConditional() const { return getNumOperands() == 3; } |
| 3112 | |
| 3113 | Value *getCondition() const { |
| 3114 | assert(isConditional() && "Cannot get condition of an uncond branch!")((void)0); |
| 3115 | return Op<-3>(); |
| 3116 | } |
| 3117 | |
| 3118 | void setCondition(Value *V) { |
| 3119 | assert(isConditional() && "Cannot set condition of unconditional branch!")((void)0); |
| 3120 | Op<-3>() = V; |
| 3121 | } |
| 3122 | |
| 3123 | unsigned getNumSuccessors() const { return 1+isConditional(); } |
| 3124 | |
| 3125 | BasicBlock *getSuccessor(unsigned i) const { |
| 3126 | assert(i < getNumSuccessors() && "Successor # out of range for Branch!")((void)0); |
| 3127 | return cast_or_null<BasicBlock>((&Op<-1>() - i)->get()); |
| 3128 | } |
| 3129 | |
| 3130 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
| 3131 | assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")((void)0); |
| 3132 | *(&Op<-1>() - idx) = NewSucc; |
| 3133 | } |
| 3134 | |
| 3135 | /// Swap the successors of this branch instruction. |
| 3136 | /// |
| 3137 | /// Swaps the successors of the branch instruction. This also swaps any |
| 3138 | /// branch weight metadata associated with the instruction so that it |
| 3139 | /// continues to map correctly to each operand. |
| 3140 | void swapSuccessors(); |
| 3141 | |
| 3142 | iterator_range<succ_op_iterator> successors() { |
| 3143 | return make_range( |
| 3144 | succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)), |
| 3145 | succ_op_iterator(value_op_end())); |
| 3146 | } |
| 3147 | |
| 3148 | iterator_range<const_succ_op_iterator> successors() const { |
| 3149 | return make_range(const_succ_op_iterator( |
| 3150 | std::next(value_op_begin(), isConditional() ? 1 : 0)), |
| 3151 | const_succ_op_iterator(value_op_end())); |
| 3152 | } |
| 3153 | |
| 3154 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 3155 | static bool classof(const Instruction *I) { |
| 3156 | return (I->getOpcode() == Instruction::Br); |
| 3157 | } |
| 3158 | static bool classof(const Value *V) { |
| 3159 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 3160 | } |
| 3161 | }; |
| 3162 | |
| 3163 | template <> |
| 3164 | struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> { |
| 3165 | }; |
| 3166 | |
| 3167 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits <BranchInst>::op_begin(this); } BranchInst::const_op_iterator BranchInst::op_begin() const { return OperandTraits<BranchInst >::op_begin(const_cast<BranchInst*>(this)); } BranchInst ::op_iterator BranchInst::op_end() { return OperandTraits< BranchInst>::op_end(this); } BranchInst::const_op_iterator BranchInst::op_end() const { return OperandTraits<BranchInst >::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<BranchInst>::op_begin(const_cast <BranchInst*>(this))[i_nocapture].get()); } void BranchInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( void)0); OperandTraits<BranchInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned BranchInst::getNumOperands() const { return OperandTraits<BranchInst>::operands(this); } template <int Idx_nocapture> Use &BranchInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &BranchInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
| 3168 | |
| 3169 | //===----------------------------------------------------------------------===// |
| 3170 | // SwitchInst Class |
| 3171 | //===----------------------------------------------------------------------===// |
| 3172 | |
| 3173 | //===--------------------------------------------------------------------------- |
| 3174 | /// Multiway switch |
| 3175 | /// |
| 3176 | class SwitchInst : public Instruction { |
| 3177 | unsigned ReservedSpace; |
| 3178 | |
| 3179 | // Operand[0] = Value to switch on |
| 3180 | // Operand[1] = Default basic block destination |
| 3181 | // Operand[2n ] = Value to match |
| 3182 | // Operand[2n+1] = BasicBlock to go to on match |
| 3183 | SwitchInst(const SwitchInst &SI); |
| 3184 | |
| 3185 | /// Create a new switch instruction, specifying a value to switch on and a |
| 3186 | /// default destination. The number of additional cases can be specified here |
| 3187 | /// to make memory allocation more efficient. This constructor can also |
| 3188 | /// auto-insert before another instruction. |
| 3189 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
| 3190 | Instruction *InsertBefore); |
| 3191 | |
| 3192 | /// Create a new switch instruction, specifying a value to switch on and a |
| 3193 | /// default destination. The number of additional cases can be specified here |
| 3194 | /// to make memory allocation more efficient. This constructor also |
| 3195 | /// auto-inserts at the end of the specified BasicBlock. |
| 3196 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
| 3197 | BasicBlock *InsertAtEnd); |
| 3198 | |
| 3199 | // allocate space for exactly zero operands |
| 3200 | void *operator new(size_t S) { return User::operator new(S); } |
| 3201 | |
| 3202 | void init(Value *Value, BasicBlock *Default, unsigned NumReserved); |
| 3203 | void growOperands(); |
| 3204 | |
| 3205 | protected: |
| 3206 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 3207 | friend class Instruction; |
| 3208 | |
| 3209 | SwitchInst *cloneImpl() const; |
| 3210 | |
| 3211 | public: |
| 3212 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 3213 | |
| 3214 | // -2 |
| 3215 | static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1); |
| 3216 | |
| 3217 | template <typename CaseHandleT> class CaseIteratorImpl; |
| 3218 | |
| 3219 | /// A handle to a particular switch case. It exposes a convenient interface |
| 3220 | /// to both the case value and the successor block. |
| 3221 | /// |
| 3222 | /// We define this as a template and instantiate it to form both a const and |
| 3223 | /// non-const handle. |
| 3224 | template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT> |
| 3225 | class CaseHandleImpl { |
| 3226 | // Directly befriend both const and non-const iterators. |
| 3227 | friend class SwitchInst::CaseIteratorImpl< |
| 3228 | CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>; |
| 3229 | |
| 3230 | protected: |
| 3231 | // Expose the switch type we're parameterized with to the iterator. |
| 3232 | using SwitchInstType = SwitchInstT; |
| 3233 | |
| 3234 | SwitchInstT *SI; |
| 3235 | ptrdiff_t Index; |
| 3236 | |
| 3237 | CaseHandleImpl() = default; |
| 3238 | CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {} |
| 3239 | |
| 3240 | public: |
| 3241 | /// Resolves case value for current case. |
| 3242 | ConstantIntT *getCaseValue() const { |
| 3243 | assert((unsigned)Index < SI->getNumCases() &&((void)0) |
| 3244 | "Index out the number of cases.")((void)0); |
| 3245 | return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2)); |
| 3246 | } |
| 3247 | |
| 3248 | /// Resolves successor for current case. |
| 3249 | BasicBlockT *getCaseSuccessor() const { |
| 3250 | assert(((unsigned)Index < SI->getNumCases() ||((void)0) |
| 3251 | (unsigned)Index == DefaultPseudoIndex) &&((void)0) |
| 3252 | "Index out the number of cases.")((void)0); |
| 3253 | return SI->getSuccessor(getSuccessorIndex()); |
| 3254 | } |
| 3255 | |
| 3256 | /// Returns number of current case. |
| 3257 | unsigned getCaseIndex() const { return Index; } |
| 3258 | |
| 3259 | /// Returns successor index for current case successor. |
| 3260 | unsigned getSuccessorIndex() const { |
| 3261 | assert(((unsigned)Index == DefaultPseudoIndex ||((void)0) |
| 3262 | (unsigned)Index < SI->getNumCases()) &&((void)0) |
| 3263 | "Index out the number of cases.")((void)0); |
| 3264 | return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0; |
| 3265 | } |
| 3266 | |
| 3267 | bool operator==(const CaseHandleImpl &RHS) const { |
| 3268 | assert(SI == RHS.SI && "Incompatible operators.")((void)0); |
| 3269 | return Index == RHS.Index; |
| 3270 | } |
| 3271 | }; |
| 3272 | |
| 3273 | using ConstCaseHandle = |
| 3274 | CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>; |
| 3275 | |
| 3276 | class CaseHandle |
| 3277 | : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> { |
| 3278 | friend class SwitchInst::CaseIteratorImpl<CaseHandle>; |
| 3279 | |
| 3280 | public: |
| 3281 | CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {} |
| 3282 | |
| 3283 | /// Sets the new value for current case. |
| 3284 | void setValue(ConstantInt *V) { |
| 3285 | assert((unsigned)Index < SI->getNumCases() &&((void)0) |
| 3286 | "Index out the number of cases.")((void)0); |
| 3287 | SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V)); |
| 3288 | } |
| 3289 | |
| 3290 | /// Sets the new successor for current case. |
| 3291 | void setSuccessor(BasicBlock *S) { |
| 3292 | SI->setSuccessor(getSuccessorIndex(), S); |
| 3293 | } |
| 3294 | }; |
| 3295 | |
| 3296 | template <typename CaseHandleT> |
| 3297 | class CaseIteratorImpl |
| 3298 | : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>, |
| 3299 | std::random_access_iterator_tag, |
| 3300 | CaseHandleT> { |
| 3301 | using SwitchInstT = typename CaseHandleT::SwitchInstType; |
| 3302 | |
| 3303 | CaseHandleT Case; |
| 3304 | |
| 3305 | public: |
| 3306 | /// Default constructed iterator is in an invalid state until assigned to |
| 3307 | /// a case for a particular switch. |
| 3308 | CaseIteratorImpl() = default; |
| 3309 | |
| 3310 | /// Initializes case iterator for given SwitchInst and for given |
| 3311 | /// case number. |
| 3312 | CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {} |
| 3313 | |
| 3314 | /// Initializes case iterator for given SwitchInst and for given |
| 3315 | /// successor index. |
| 3316 | static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI, |
| 3317 | unsigned SuccessorIndex) { |
| 3318 | assert(SuccessorIndex < SI->getNumSuccessors() &&((void)0) |
| 3319 | "Successor index # out of range!")((void)0); |
| 3320 | return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1) |
| 3321 | : CaseIteratorImpl(SI, DefaultPseudoIndex); |
| 3322 | } |
| 3323 | |
| 3324 | /// Support converting to the const variant. This will be a no-op for const |
| 3325 | /// variant. |
| 3326 | operator CaseIteratorImpl<ConstCaseHandle>() const { |
| 3327 | return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index); |
| 3328 | } |
| 3329 | |
| 3330 | CaseIteratorImpl &operator+=(ptrdiff_t N) { |
| 3331 | // Check index correctness after addition. |
| 3332 | // Note: Index == getNumCases() means end(). |
| 3333 | assert(Case.Index + N >= 0 &&((void)0) |
| 3334 | (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&((void)0) |
| 3335 | "Case.Index out the number of cases.")((void)0); |
| 3336 | Case.Index += N; |
| 3337 | return *this; |
| 3338 | } |
| 3339 | CaseIteratorImpl &operator-=(ptrdiff_t N) { |
| 3340 | // Check index correctness after subtraction. |
| 3341 | // Note: Case.Index == getNumCases() means end(). |
| 3342 | assert(Case.Index - N >= 0 &&((void)0) |
| 3343 | (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&((void)0) |
| 3344 | "Case.Index out the number of cases.")((void)0); |
| 3345 | Case.Index -= N; |
| 3346 | return *this; |
| 3347 | } |
| 3348 | ptrdiff_t operator-(const CaseIteratorImpl &RHS) const { |
| 3349 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((void)0); |
| 3350 | return Case.Index - RHS.Case.Index; |
| 3351 | } |
| 3352 | bool operator==(const CaseIteratorImpl &RHS) const { |
| 3353 | return Case == RHS.Case; |
| 3354 | } |
| 3355 | bool operator<(const CaseIteratorImpl &RHS) const { |
| 3356 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((void)0); |
| 3357 | return Case.Index < RHS.Case.Index; |
| 3358 | } |
| 3359 | CaseHandleT &operator*() { return Case; } |
| 3360 | const CaseHandleT &operator*() const { return Case; } |
| 3361 | }; |
| 3362 | |
| 3363 | using CaseIt = CaseIteratorImpl<CaseHandle>; |
| 3364 | using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>; |
| 3365 | |
| 3366 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
| 3367 | unsigned NumCases, |
| 3368 | Instruction *InsertBefore = nullptr) { |
| 3369 | return new SwitchInst(Value, Default, NumCases, InsertBefore); |
| 3370 | } |
| 3371 | |
| 3372 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
| 3373 | unsigned NumCases, BasicBlock *InsertAtEnd) { |
| 3374 | return new SwitchInst(Value, Default, NumCases, InsertAtEnd); |
| 3375 | } |
| 3376 | |
| 3377 | /// Provide fast operand accessors |
| 3378 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 3379 | |
| 3380 | // Accessor Methods for Switch stmt |
| 3381 | Value *getCondition() const { return getOperand(0); } |
| 3382 | void setCondition(Value *V) { setOperand(0, V); } |
| 3383 | |
| 3384 | BasicBlock *getDefaultDest() const { |
| 3385 | return cast<BasicBlock>(getOperand(1)); |
| 3386 | } |
| 3387 | |
| 3388 | void setDefaultDest(BasicBlock *DefaultCase) { |
| 3389 | setOperand(1, reinterpret_cast<Value*>(DefaultCase)); |
| 3390 | } |
| 3391 | |
| 3392 | /// Return the number of 'cases' in this switch instruction, excluding the |
| 3393 | /// default case. |
| 3394 | unsigned getNumCases() const { |
| 3395 | return getNumOperands()/2 - 1; |
| 3396 | } |
| 3397 | |
| 3398 | /// Returns a read/write iterator that points to the first case in the |
| 3399 | /// SwitchInst. |
| 3400 | CaseIt case_begin() { |
| 3401 | return CaseIt(this, 0); |
| 3402 | } |
| 3403 | |
| 3404 | /// Returns a read-only iterator that points to the first case in the |
| 3405 | /// SwitchInst. |
| 3406 | ConstCaseIt case_begin() const { |
| 3407 | return ConstCaseIt(this, 0); |
| 3408 | } |
| 3409 | |
| 3410 | /// Returns a read/write iterator that points one past the last in the |
| 3411 | /// SwitchInst. |
| 3412 | CaseIt case_end() { |
| 3413 | return CaseIt(this, getNumCases()); |
| 3414 | } |
| 3415 | |
| 3416 | /// Returns a read-only iterator that points one past the last in the |
| 3417 | /// SwitchInst. |
| 3418 | ConstCaseIt case_end() const { |
| 3419 | return ConstCaseIt(this, getNumCases()); |
| 3420 | } |
| 3421 | |
| 3422 | /// Iteration adapter for range-for loops. |
| 3423 | iterator_range<CaseIt> cases() { |
| 3424 | return make_range(case_begin(), case_end()); |
| 3425 | } |
| 3426 | |
| 3427 | /// Constant iteration adapter for range-for loops. |
| 3428 | iterator_range<ConstCaseIt> cases() const { |
| 3429 | return make_range(case_begin(), case_end()); |
| 3430 | } |
| 3431 | |
| 3432 | /// Returns an iterator that points to the default case. |
| 3433 | /// Note: this iterator allows to resolve successor only. Attempt |
| 3434 | /// to resolve case value causes an assertion. |
| 3435 | /// Also note, that increment and decrement also causes an assertion and |
| 3436 | /// makes iterator invalid. |
| 3437 | CaseIt case_default() { |
| 3438 | return CaseIt(this, DefaultPseudoIndex); |
| 3439 | } |
| 3440 | ConstCaseIt case_default() const { |
| 3441 | return ConstCaseIt(this, DefaultPseudoIndex); |
| 3442 | } |
| 3443 | |
| 3444 | /// Search all of the case values for the specified constant. If it is |
| 3445 | /// explicitly handled, return the case iterator of it, otherwise return |
| 3446 | /// default case iterator to indicate that it is handled by the default |
| 3447 | /// handler. |
| 3448 | CaseIt findCaseValue(const ConstantInt *C) { |
| 3449 | CaseIt I = llvm::find_if( |
| 3450 | cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; }); |
| 3451 | if (I != case_end()) |
| 3452 | return I; |
| 3453 | |
| 3454 | return case_default(); |
| 3455 | } |
| 3456 | ConstCaseIt findCaseValue(const ConstantInt *C) const { |
| 3457 | ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) { |
| 3458 | return Case.getCaseValue() == C; |
| 3459 | }); |
| 3460 | if (I != case_end()) |
| 3461 | return I; |
| 3462 | |
| 3463 | return case_default(); |
| 3464 | } |
| 3465 | |
| 3466 | /// Finds the unique case value for a given successor. Returns null if the |
| 3467 | /// successor is not found, not unique, or is the default case. |
| 3468 | ConstantInt *findCaseDest(BasicBlock *BB) { |
| 3469 | if (BB == getDefaultDest()) |
| 3470 | return nullptr; |
| 3471 | |
| 3472 | ConstantInt *CI = nullptr; |
| 3473 | for (auto Case : cases()) { |
| 3474 | if (Case.getCaseSuccessor() != BB) |
| 3475 | continue; |
| 3476 | |
| 3477 | if (CI) |
| 3478 | return nullptr; // Multiple cases lead to BB. |
| 3479 | |
| 3480 | CI = Case.getCaseValue(); |
| 3481 | } |
| 3482 | |
| 3483 | return CI; |
| 3484 | } |
| 3485 | |
| 3486 | /// Add an entry to the switch instruction. |
| 3487 | /// Note: |
| 3488 | /// This action invalidates case_end(). Old case_end() iterator will |
| 3489 | /// point to the added case. |
| 3490 | void addCase(ConstantInt *OnVal, BasicBlock *Dest); |
| 3491 | |
| 3492 | /// This method removes the specified case and its successor from the switch |
| 3493 | /// instruction. Note that this operation may reorder the remaining cases at |
| 3494 | /// index idx and above. |
| 3495 | /// Note: |
| 3496 | /// This action invalidates iterators for all cases following the one removed, |
| 3497 | /// including the case_end() iterator. It returns an iterator for the next |
| 3498 | /// case. |
| 3499 | CaseIt removeCase(CaseIt I); |
| 3500 | |
| 3501 | unsigned getNumSuccessors() const { return getNumOperands()/2; } |
| 3502 | BasicBlock *getSuccessor(unsigned idx) const { |
| 3503 | assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")((void)0); |
| 3504 | return cast<BasicBlock>(getOperand(idx*2+1)); |
| 3505 | } |
| 3506 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
| 3507 | assert(idx < getNumSuccessors() && "Successor # out of range for switch!")((void)0); |
| 3508 | setOperand(idx * 2 + 1, NewSucc); |
| 3509 | } |
| 3510 | |
| 3511 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 3512 | static bool classof(const Instruction *I) { |
| 3513 | return I->getOpcode() == Instruction::Switch; |
| 3514 | } |
| 3515 | static bool classof(const Value *V) { |
| 3516 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 3517 | } |
| 3518 | }; |
| 3519 | |
| 3520 | /// A wrapper class to simplify modification of SwitchInst cases along with |
| 3521 | /// their prof branch_weights metadata. |
| 3522 | class SwitchInstProfUpdateWrapper { |
| 3523 | SwitchInst &SI; |
| 3524 | Optional<SmallVector<uint32_t, 8> > Weights = None; |
| 3525 | bool Changed = false; |
| 3526 | |
| 3527 | protected: |
| 3528 | static MDNode *getProfBranchWeightsMD(const SwitchInst &SI); |
| 3529 | |
| 3530 | MDNode *buildProfBranchWeightsMD(); |
| 3531 | |
| 3532 | void init(); |
| 3533 | |
| 3534 | public: |
| 3535 | using CaseWeightOpt = Optional<uint32_t>; |
| 3536 | SwitchInst *operator->() { return &SI; } |
| 3537 | SwitchInst &operator*() { return SI; } |
| 3538 | operator SwitchInst *() { return &SI; } |
| 3539 | |
| 3540 | SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); } |
| 3541 | |
| 3542 | ~SwitchInstProfUpdateWrapper() { |
| 3543 | if (Changed) |
| 3544 | SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD()); |
| 3545 | } |
| 3546 | |
| 3547 | /// Delegate the call to the underlying SwitchInst::removeCase() and remove |
| 3548 | /// correspondent branch weight. |
| 3549 | SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I); |
| 3550 | |
| 3551 | /// Delegate the call to the underlying SwitchInst::addCase() and set the |
| 3552 | /// specified branch weight for the added case. |
| 3553 | void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W); |
| 3554 | |
| 3555 | /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark |
| 3556 | /// this object to not touch the underlying SwitchInst in destructor. |
| 3557 | SymbolTableList<Instruction>::iterator eraseFromParent(); |
| 3558 | |
| 3559 | void setSuccessorWeight(unsigned idx, CaseWeightOpt W); |
| 3560 | CaseWeightOpt getSuccessorWeight(unsigned idx); |
| 3561 | |
| 3562 | static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx); |
| 3563 | }; |
| 3564 | |
| 3565 | template <> |
| 3566 | struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> { |
| 3567 | }; |
| 3568 | |
| 3569 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits <SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator SwitchInst::op_begin() const { return OperandTraits<SwitchInst >::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst ::op_iterator SwitchInst::op_end() { return OperandTraits< SwitchInst>::op_end(this); } SwitchInst::const_op_iterator SwitchInst::op_end() const { return OperandTraits<SwitchInst >::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<SwitchInst>::op_begin(const_cast <SwitchInst*>(this))[i_nocapture].get()); } void SwitchInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( void)0); OperandTraits<SwitchInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned SwitchInst::getNumOperands() const { return OperandTraits<SwitchInst>::operands(this); } template <int Idx_nocapture> Use &SwitchInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &SwitchInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
| 3570 | |
| 3571 | //===----------------------------------------------------------------------===// |
| 3572 | // IndirectBrInst Class |
| 3573 | //===----------------------------------------------------------------------===// |
| 3574 | |
| 3575 | //===--------------------------------------------------------------------------- |
| 3576 | /// Indirect Branch Instruction. |
| 3577 | /// |
| 3578 | class IndirectBrInst : public Instruction { |
| 3579 | unsigned ReservedSpace; |
| 3580 | |
| 3581 | // Operand[0] = Address to jump to |
| 3582 | // Operand[n+1] = n-th destination |
| 3583 | IndirectBrInst(const IndirectBrInst &IBI); |
| 3584 | |
| 3585 | /// Create a new indirectbr instruction, specifying an |
| 3586 | /// Address to jump to. The number of expected destinations can be specified |
| 3587 | /// here to make memory allocation more efficient. This constructor can also |
| 3588 | /// autoinsert before another instruction. |
| 3589 | IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore); |
| 3590 | |
| 3591 | /// Create a new indirectbr instruction, specifying an |
| 3592 | /// Address to jump to. The number of expected destinations can be specified |
| 3593 | /// here to make memory allocation more efficient. This constructor also |
| 3594 | /// autoinserts at the end of the specified BasicBlock. |
| 3595 | IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd); |
| 3596 | |
| 3597 | // allocate space for exactly zero operands |
| 3598 | void *operator new(size_t S) { return User::operator new(S); } |
| 3599 | |
| 3600 | void init(Value *Address, unsigned NumDests); |
| 3601 | void growOperands(); |
| 3602 | |
| 3603 | protected: |
| 3604 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 3605 | friend class Instruction; |
| 3606 | |
| 3607 | IndirectBrInst *cloneImpl() const; |
| 3608 | |
| 3609 | public: |
| 3610 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 3611 | |
| 3612 | /// Iterator type that casts an operand to a basic block. |
| 3613 | /// |
| 3614 | /// This only makes sense because the successors are stored as adjacent |
| 3615 | /// operands for indirectbr instructions. |
| 3616 | struct succ_op_iterator |
| 3617 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
| 3618 | std::random_access_iterator_tag, BasicBlock *, |
| 3619 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
| 3620 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
| 3621 | |
| 3622 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
| 3623 | BasicBlock *operator->() const { return operator*(); } |
| 3624 | }; |
| 3625 | |
| 3626 | /// The const version of `succ_op_iterator`. |
| 3627 | struct const_succ_op_iterator |
| 3628 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
| 3629 | std::random_access_iterator_tag, |
| 3630 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
| 3631 | const BasicBlock *> { |
| 3632 | explicit const_succ_op_iterator(const_value_op_iterator I) |
| 3633 | : iterator_adaptor_base(I) {} |
| 3634 | |
| 3635 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
| 3636 | const BasicBlock *operator->() const { return operator*(); } |
| 3637 | }; |
| 3638 | |
| 3639 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
| 3640 | Instruction *InsertBefore = nullptr) { |
| 3641 | return new IndirectBrInst(Address, NumDests, InsertBefore); |
| 3642 | } |
| 3643 | |
| 3644 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
| 3645 | BasicBlock *InsertAtEnd) { |
| 3646 | return new IndirectBrInst(Address, NumDests, InsertAtEnd); |
| 3647 | } |
| 3648 | |
| 3649 | /// Provide fast operand accessors. |
| 3650 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 3651 | |
| 3652 | // Accessor Methods for IndirectBrInst instruction. |
| 3653 | Value *getAddress() { return getOperand(0); } |
| 3654 | const Value *getAddress() const { return getOperand(0); } |
| 3655 | void setAddress(Value *V) { setOperand(0, V); } |
| 3656 | |
| 3657 | /// return the number of possible destinations in this |
| 3658 | /// indirectbr instruction. |
| 3659 | unsigned getNumDestinations() const { return getNumOperands()-1; } |
| 3660 | |
| 3661 | /// Return the specified destination. |
| 3662 | BasicBlock *getDestination(unsigned i) { return getSuccessor(i); } |
| 3663 | const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); } |
| 3664 | |
| 3665 | /// Add a destination. |
| 3666 | /// |
| 3667 | void addDestination(BasicBlock *Dest); |
| 3668 | |
| 3669 | /// This method removes the specified successor from the |
| 3670 | /// indirectbr instruction. |
| 3671 | void removeDestination(unsigned i); |
| 3672 | |
| 3673 | unsigned getNumSuccessors() const { return getNumOperands()-1; } |
| 3674 | BasicBlock *getSuccessor(unsigned i) const { |
| 3675 | return cast<BasicBlock>(getOperand(i+1)); |
| 3676 | } |
| 3677 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
| 3678 | setOperand(i + 1, NewSucc); |
| 3679 | } |
| 3680 | |
| 3681 | iterator_range<succ_op_iterator> successors() { |
| 3682 | return make_range(succ_op_iterator(std::next(value_op_begin())), |
| 3683 | succ_op_iterator(value_op_end())); |
| 3684 | } |
| 3685 | |
| 3686 | iterator_range<const_succ_op_iterator> successors() const { |
| 3687 | return make_range(const_succ_op_iterator(std::next(value_op_begin())), |
| 3688 | const_succ_op_iterator(value_op_end())); |
| 3689 | } |
| 3690 | |
| 3691 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 3692 | static bool classof(const Instruction *I) { |
| 3693 | return I->getOpcode() == Instruction::IndirectBr; |
| 3694 | } |
| 3695 | static bool classof(const Value *V) { |
| 3696 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 3697 | } |
| 3698 | }; |
| 3699 | |
| 3700 | template <> |
| 3701 | struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> { |
| 3702 | }; |
| 3703 | |
| 3704 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst ::const_op_iterator IndirectBrInst::op_begin() const { return OperandTraits<IndirectBrInst>::op_begin(const_cast< IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst ::op_end() { return OperandTraits<IndirectBrInst>::op_end (this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end () const { return OperandTraits<IndirectBrInst>::op_end (const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<IndirectBrInst>::op_begin( const_cast<IndirectBrInst*>(this))[i_nocapture].get()); } void IndirectBrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((void)0); OperandTraits<IndirectBrInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned IndirectBrInst::getNumOperands() const { return OperandTraits <IndirectBrInst>::operands(this); } template <int Idx_nocapture > Use &IndirectBrInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &IndirectBrInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
| 3705 | |
| 3706 | //===----------------------------------------------------------------------===// |
| 3707 | // InvokeInst Class |
| 3708 | //===----------------------------------------------------------------------===// |
| 3709 | |
| 3710 | /// Invoke instruction. The SubclassData field is used to hold the |
| 3711 | /// calling convention of the call. |
| 3712 | /// |
| 3713 | class InvokeInst : public CallBase { |
| 3714 | /// The number of operands for this call beyond the called function, |
| 3715 | /// arguments, and operand bundles. |
| 3716 | static constexpr int NumExtraOperands = 2; |
| 3717 | |
| 3718 | /// The index from the end of the operand array to the normal destination. |
| 3719 | static constexpr int NormalDestOpEndIdx = -3; |
| 3720 | |
| 3721 | /// The index from the end of the operand array to the unwind destination. |
| 3722 | static constexpr int UnwindDestOpEndIdx = -2; |
| 3723 | |
| 3724 | InvokeInst(const InvokeInst &BI); |
| 3725 | |
| 3726 | /// Construct an InvokeInst given a range of arguments. |
| 3727 | /// |
| 3728 | /// Construct an InvokeInst from a range of arguments |
| 3729 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3730 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3731 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 3732 | const Twine &NameStr, Instruction *InsertBefore); |
| 3733 | |
| 3734 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3735 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3736 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 3737 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 3738 | |
| 3739 | void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3740 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3741 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
| 3742 | |
| 3743 | /// Compute the number of operands to allocate. |
| 3744 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
| 3745 | // We need one operand for the called function, plus our extra operands and |
| 3746 | // the input operand counts provided. |
| 3747 | return 1 + NumExtraOperands + NumArgs + NumBundleInputs; |
| 3748 | } |
| 3749 | |
| 3750 | protected: |
| 3751 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 3752 | friend class Instruction; |
| 3753 | |
| 3754 | InvokeInst *cloneImpl() const; |
| 3755 | |
| 3756 | public: |
| 3757 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3758 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3759 | const Twine &NameStr, |
| 3760 | Instruction *InsertBefore = nullptr) { |
| 3761 | int NumOperands = ComputeNumOperands(Args.size()); |
| 3762 | return new (NumOperands) |
| 3763 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
| 3764 | NameStr, InsertBefore); |
| 3765 | } |
| 3766 | |
| 3767 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3768 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3769 | ArrayRef<OperandBundleDef> Bundles = None, |
| 3770 | const Twine &NameStr = "", |
| 3771 | Instruction *InsertBefore = nullptr) { |
| 3772 | int NumOperands = |
| 3773 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
| 3774 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
| 3775 | |
| 3776 | return new (NumOperands, DescriptorBytes) |
| 3777 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
| 3778 | NameStr, InsertBefore); |
| 3779 | } |
| 3780 | |
| 3781 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3782 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3783 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 3784 | int NumOperands = ComputeNumOperands(Args.size()); |
| 3785 | return new (NumOperands) |
| 3786 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
| 3787 | NameStr, InsertAtEnd); |
| 3788 | } |
| 3789 | |
| 3790 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3791 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3792 | ArrayRef<OperandBundleDef> Bundles, |
| 3793 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 3794 | int NumOperands = |
| 3795 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
| 3796 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
| 3797 | |
| 3798 | return new (NumOperands, DescriptorBytes) |
| 3799 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
| 3800 | NameStr, InsertAtEnd); |
| 3801 | } |
| 3802 | |
| 3803 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
| 3804 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3805 | const Twine &NameStr, |
| 3806 | Instruction *InsertBefore = nullptr) { |
| 3807 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
| 3808 | IfException, Args, None, NameStr, InsertBefore); |
| 3809 | } |
| 3810 | |
| 3811 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
| 3812 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3813 | ArrayRef<OperandBundleDef> Bundles = None, |
| 3814 | const Twine &NameStr = "", |
| 3815 | Instruction *InsertBefore = nullptr) { |
| 3816 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
| 3817 | IfException, Args, Bundles, NameStr, InsertBefore); |
| 3818 | } |
| 3819 | |
| 3820 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
| 3821 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3822 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 3823 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
| 3824 | IfException, Args, NameStr, InsertAtEnd); |
| 3825 | } |
| 3826 | |
| 3827 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
| 3828 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3829 | ArrayRef<OperandBundleDef> Bundles, |
| 3830 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 3831 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
| 3832 | IfException, Args, Bundles, NameStr, InsertAtEnd); |
| 3833 | } |
| 3834 | |
| 3835 | /// Create a clone of \p II with a different set of operand bundles and |
| 3836 | /// insert it before \p InsertPt. |
| 3837 | /// |
| 3838 | /// The returned invoke instruction is identical to \p II in every way except |
| 3839 | /// that the operand bundles for the new instruction are set to the operand |
| 3840 | /// bundles in \p Bundles. |
| 3841 | static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles, |
| 3842 | Instruction *InsertPt = nullptr); |
| 3843 | |
| 3844 | // get*Dest - Return the destination basic blocks... |
| 3845 | BasicBlock *getNormalDest() const { |
| 3846 | return cast<BasicBlock>(Op<NormalDestOpEndIdx>()); |
| 3847 | } |
| 3848 | BasicBlock *getUnwindDest() const { |
| 3849 | return cast<BasicBlock>(Op<UnwindDestOpEndIdx>()); |
| 3850 | } |
| 3851 | void setNormalDest(BasicBlock *B) { |
| 3852 | Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
| 3853 | } |
| 3854 | void setUnwindDest(BasicBlock *B) { |
| 3855 | Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
| 3856 | } |
| 3857 | |
| 3858 | /// Get the landingpad instruction from the landing pad |
| 3859 | /// block (the unwind destination). |
| 3860 | LandingPadInst *getLandingPadInst() const; |
| 3861 | |
| 3862 | BasicBlock *getSuccessor(unsigned i) const { |
| 3863 | assert(i < 2 && "Successor # out of range for invoke!")((void)0); |
| 3864 | return i == 0 ? getNormalDest() : getUnwindDest(); |
| 3865 | } |
| 3866 | |
| 3867 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
| 3868 | assert(i < 2 && "Successor # out of range for invoke!")((void)0); |
| 3869 | if (i == 0) |
| 3870 | setNormalDest(NewSucc); |
| 3871 | else |
| 3872 | setUnwindDest(NewSucc); |
| 3873 | } |
| 3874 | |
| 3875 | unsigned getNumSuccessors() const { return 2; } |
| 3876 | |
| 3877 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 3878 | static bool classof(const Instruction *I) { |
| 3879 | return (I->getOpcode() == Instruction::Invoke); |
| 3880 | } |
| 3881 | static bool classof(const Value *V) { |
| 3882 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 3883 | } |
| 3884 | |
| 3885 | private: |
| 3886 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 3887 | // method so that subclasses cannot accidentally use it. |
| 3888 | template <typename Bitfield> |
| 3889 | void setSubclassData(typename Bitfield::Type Value) { |
| 3890 | Instruction::setSubclassData<Bitfield>(Value); |
| 3891 | } |
| 3892 | }; |
| 3893 | |
| 3894 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3895 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3896 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 3897 | const Twine &NameStr, Instruction *InsertBefore) |
| 3898 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
| 3899 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
| 3900 | InsertBefore) { |
| 3901 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
| 3902 | } |
| 3903 | |
| 3904 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
| 3905 | BasicBlock *IfException, ArrayRef<Value *> Args, |
| 3906 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 3907 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
| 3908 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
| 3909 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
| 3910 | InsertAtEnd) { |
| 3911 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
| 3912 | } |
| 3913 | |
| 3914 | //===----------------------------------------------------------------------===// |
| 3915 | // CallBrInst Class |
| 3916 | //===----------------------------------------------------------------------===// |
| 3917 | |
| 3918 | /// CallBr instruction, tracking function calls that may not return control but |
| 3919 | /// instead transfer it to a third location. The SubclassData field is used to |
| 3920 | /// hold the calling convention of the call. |
| 3921 | /// |
| 3922 | class CallBrInst : public CallBase { |
| 3923 | |
| 3924 | unsigned NumIndirectDests; |
| 3925 | |
| 3926 | CallBrInst(const CallBrInst &BI); |
| 3927 | |
| 3928 | /// Construct a CallBrInst given a range of arguments. |
| 3929 | /// |
| 3930 | /// Construct a CallBrInst from a range of arguments |
| 3931 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
| 3932 | ArrayRef<BasicBlock *> IndirectDests, |
| 3933 | ArrayRef<Value *> Args, |
| 3934 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 3935 | const Twine &NameStr, Instruction *InsertBefore); |
| 3936 | |
| 3937 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
| 3938 | ArrayRef<BasicBlock *> IndirectDests, |
| 3939 | ArrayRef<Value *> Args, |
| 3940 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 3941 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 3942 | |
| 3943 | void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest, |
| 3944 | ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args, |
| 3945 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
| 3946 | |
| 3947 | /// Should the Indirect Destinations change, scan + update the Arg list. |
| 3948 | void updateArgBlockAddresses(unsigned i, BasicBlock *B); |
| 3949 | |
| 3950 | /// Compute the number of operands to allocate. |
| 3951 | static int ComputeNumOperands(int NumArgs, int NumIndirectDests, |
| 3952 | int NumBundleInputs = 0) { |
| 3953 | // We need one operand for the called function, plus our extra operands and |
| 3954 | // the input operand counts provided. |
| 3955 | return 2 + NumIndirectDests + NumArgs + NumBundleInputs; |
| 3956 | } |
| 3957 | |
| 3958 | protected: |
| 3959 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 3960 | friend class Instruction; |
| 3961 | |
| 3962 | CallBrInst *cloneImpl() const; |
| 3963 | |
| 3964 | public: |
| 3965 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
| 3966 | BasicBlock *DefaultDest, |
| 3967 | ArrayRef<BasicBlock *> IndirectDests, |
| 3968 | ArrayRef<Value *> Args, const Twine &NameStr, |
| 3969 | Instruction *InsertBefore = nullptr) { |
| 3970 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
| 3971 | return new (NumOperands) |
| 3972 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
| 3973 | NumOperands, NameStr, InsertBefore); |
| 3974 | } |
| 3975 | |
| 3976 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
| 3977 | BasicBlock *DefaultDest, |
| 3978 | ArrayRef<BasicBlock *> IndirectDests, |
| 3979 | ArrayRef<Value *> Args, |
| 3980 | ArrayRef<OperandBundleDef> Bundles = None, |
| 3981 | const Twine &NameStr = "", |
| 3982 | Instruction *InsertBefore = nullptr) { |
| 3983 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
| 3984 | CountBundleInputs(Bundles)); |
| 3985 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
| 3986 | |
| 3987 | return new (NumOperands, DescriptorBytes) |
| 3988 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
| 3989 | NumOperands, NameStr, InsertBefore); |
| 3990 | } |
| 3991 | |
| 3992 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
| 3993 | BasicBlock *DefaultDest, |
| 3994 | ArrayRef<BasicBlock *> IndirectDests, |
| 3995 | ArrayRef<Value *> Args, const Twine &NameStr, |
| 3996 | BasicBlock *InsertAtEnd) { |
| 3997 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
| 3998 | return new (NumOperands) |
| 3999 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
| 4000 | NumOperands, NameStr, InsertAtEnd); |
| 4001 | } |
| 4002 | |
| 4003 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
| 4004 | BasicBlock *DefaultDest, |
| 4005 | ArrayRef<BasicBlock *> IndirectDests, |
| 4006 | ArrayRef<Value *> Args, |
| 4007 | ArrayRef<OperandBundleDef> Bundles, |
| 4008 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 4009 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
| 4010 | CountBundleInputs(Bundles)); |
| 4011 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
| 4012 | |
| 4013 | return new (NumOperands, DescriptorBytes) |
| 4014 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
| 4015 | NumOperands, NameStr, InsertAtEnd); |
| 4016 | } |
| 4017 | |
| 4018 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
| 4019 | ArrayRef<BasicBlock *> IndirectDests, |
| 4020 | ArrayRef<Value *> Args, const Twine &NameStr, |
| 4021 | Instruction *InsertBefore = nullptr) { |
| 4022 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
| 4023 | IndirectDests, Args, NameStr, InsertBefore); |
| 4024 | } |
| 4025 | |
| 4026 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
| 4027 | ArrayRef<BasicBlock *> IndirectDests, |
| 4028 | ArrayRef<Value *> Args, |
| 4029 | ArrayRef<OperandBundleDef> Bundles = None, |
| 4030 | const Twine &NameStr = "", |
| 4031 | Instruction *InsertBefore = nullptr) { |
| 4032 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
| 4033 | IndirectDests, Args, Bundles, NameStr, InsertBefore); |
| 4034 | } |
| 4035 | |
| 4036 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
| 4037 | ArrayRef<BasicBlock *> IndirectDests, |
| 4038 | ArrayRef<Value *> Args, const Twine &NameStr, |
| 4039 | BasicBlock *InsertAtEnd) { |
| 4040 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
| 4041 | IndirectDests, Args, NameStr, InsertAtEnd); |
| 4042 | } |
| 4043 | |
| 4044 | static CallBrInst *Create(FunctionCallee Func, |
| 4045 | BasicBlock *DefaultDest, |
| 4046 | ArrayRef<BasicBlock *> IndirectDests, |
| 4047 | ArrayRef<Value *> Args, |
| 4048 | ArrayRef<OperandBundleDef> Bundles, |
| 4049 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 4050 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
| 4051 | IndirectDests, Args, Bundles, NameStr, InsertAtEnd); |
| 4052 | } |
| 4053 | |
| 4054 | /// Create a clone of \p CBI with a different set of operand bundles and |
| 4055 | /// insert it before \p InsertPt. |
| 4056 | /// |
| 4057 | /// The returned callbr instruction is identical to \p CBI in every way |
| 4058 | /// except that the operand bundles for the new instruction are set to the |
| 4059 | /// operand bundles in \p Bundles. |
| 4060 | static CallBrInst *Create(CallBrInst *CBI, |
| 4061 | ArrayRef<OperandBundleDef> Bundles, |
| 4062 | Instruction *InsertPt = nullptr); |
| 4063 | |
| 4064 | /// Return the number of callbr indirect dest labels. |
| 4065 | /// |
| 4066 | unsigned getNumIndirectDests() const { return NumIndirectDests; } |
| 4067 | |
| 4068 | /// getIndirectDestLabel - Return the i-th indirect dest label. |
| 4069 | /// |
| 4070 | Value *getIndirectDestLabel(unsigned i) const { |
| 4071 | assert(i < getNumIndirectDests() && "Out of bounds!")((void)0); |
| 4072 | return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() + |
| 4073 | 1); |
| 4074 | } |
| 4075 | |
| 4076 | Value *getIndirectDestLabelUse(unsigned i) const { |
| 4077 | assert(i < getNumIndirectDests() && "Out of bounds!")((void)0); |
| 4078 | return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() + |
| 4079 | 1); |
| 4080 | } |
| 4081 | |
| 4082 | // Return the destination basic blocks... |
| 4083 | BasicBlock *getDefaultDest() const { |
| 4084 | return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1)); |
| 4085 | } |
| 4086 | BasicBlock *getIndirectDest(unsigned i) const { |
| 4087 | return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i)); |
| 4088 | } |
| 4089 | SmallVector<BasicBlock *, 16> getIndirectDests() const { |
| 4090 | SmallVector<BasicBlock *, 16> IndirectDests; |
| 4091 | for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i) |
| 4092 | IndirectDests.push_back(getIndirectDest(i)); |
| 4093 | return IndirectDests; |
| 4094 | } |
| 4095 | void setDefaultDest(BasicBlock *B) { |
| 4096 | *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B); |
| 4097 | } |
| 4098 | void setIndirectDest(unsigned i, BasicBlock *B) { |
| 4099 | updateArgBlockAddresses(i, B); |
| 4100 | *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B); |
| 4101 | } |
| 4102 | |
| 4103 | BasicBlock *getSuccessor(unsigned i) const { |
| 4104 | assert(i < getNumSuccessors() + 1 &&((void)0) |
| 4105 | "Successor # out of range for callbr!")((void)0); |
| 4106 | return i == 0 ? getDefaultDest() : getIndirectDest(i - 1); |
| 4107 | } |
| 4108 | |
| 4109 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
| 4110 | assert(i < getNumIndirectDests() + 1 &&((void)0) |
| 4111 | "Successor # out of range for callbr!")((void)0); |
| 4112 | return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc); |
| 4113 | } |
| 4114 | |
| 4115 | unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; } |
| 4116 | |
| 4117 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4118 | static bool classof(const Instruction *I) { |
| 4119 | return (I->getOpcode() == Instruction::CallBr); |
| 4120 | } |
| 4121 | static bool classof(const Value *V) { |
| 4122 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4123 | } |
| 4124 | |
| 4125 | private: |
| 4126 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 4127 | // method so that subclasses cannot accidentally use it. |
| 4128 | template <typename Bitfield> |
| 4129 | void setSubclassData(typename Bitfield::Type Value) { |
| 4130 | Instruction::setSubclassData<Bitfield>(Value); |
| 4131 | } |
| 4132 | }; |
| 4133 | |
| 4134 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
| 4135 | ArrayRef<BasicBlock *> IndirectDests, |
| 4136 | ArrayRef<Value *> Args, |
| 4137 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 4138 | const Twine &NameStr, Instruction *InsertBefore) |
| 4139 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
| 4140 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
| 4141 | InsertBefore) { |
| 4142 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
| 4143 | } |
| 4144 | |
| 4145 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
| 4146 | ArrayRef<BasicBlock *> IndirectDests, |
| 4147 | ArrayRef<Value *> Args, |
| 4148 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
| 4149 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
| 4150 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
| 4151 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
| 4152 | InsertAtEnd) { |
| 4153 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
| 4154 | } |
| 4155 | |
| 4156 | //===----------------------------------------------------------------------===// |
| 4157 | // ResumeInst Class |
| 4158 | //===----------------------------------------------------------------------===// |
| 4159 | |
| 4160 | //===--------------------------------------------------------------------------- |
| 4161 | /// Resume the propagation of an exception. |
| 4162 | /// |
| 4163 | class ResumeInst : public Instruction { |
| 4164 | ResumeInst(const ResumeInst &RI); |
| 4165 | |
| 4166 | explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr); |
| 4167 | ResumeInst(Value *Exn, BasicBlock *InsertAtEnd); |
| 4168 | |
| 4169 | protected: |
| 4170 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4171 | friend class Instruction; |
| 4172 | |
| 4173 | ResumeInst *cloneImpl() const; |
| 4174 | |
| 4175 | public: |
| 4176 | static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) { |
| 4177 | return new(1) ResumeInst(Exn, InsertBefore); |
| 4178 | } |
| 4179 | |
| 4180 | static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) { |
| 4181 | return new(1) ResumeInst(Exn, InsertAtEnd); |
| 4182 | } |
| 4183 | |
| 4184 | /// Provide fast operand accessors |
| 4185 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 4186 | |
| 4187 | /// Convenience accessor. |
| 4188 | Value *getValue() const { return Op<0>(); } |
| 4189 | |
| 4190 | unsigned getNumSuccessors() const { return 0; } |
| 4191 | |
| 4192 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4193 | static bool classof(const Instruction *I) { |
| 4194 | return I->getOpcode() == Instruction::Resume; |
| 4195 | } |
| 4196 | static bool classof(const Value *V) { |
| 4197 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4198 | } |
| 4199 | |
| 4200 | private: |
| 4201 | BasicBlock *getSuccessor(unsigned idx) const { |
| 4202 | llvm_unreachable("ResumeInst has no successors!")__builtin_unreachable(); |
| 4203 | } |
| 4204 | |
| 4205 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
| 4206 | llvm_unreachable("ResumeInst has no successors!")__builtin_unreachable(); |
| 4207 | } |
| 4208 | }; |
| 4209 | |
| 4210 | template <> |
| 4211 | struct OperandTraits<ResumeInst> : |
| 4212 | public FixedNumOperandTraits<ResumeInst, 1> { |
| 4213 | }; |
| 4214 | |
| 4215 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits <ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator ResumeInst::op_begin() const { return OperandTraits<ResumeInst >::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst ::op_iterator ResumeInst::op_end() { return OperandTraits< ResumeInst>::op_end(this); } ResumeInst::const_op_iterator ResumeInst::op_end() const { return OperandTraits<ResumeInst >::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<ResumeInst>::op_begin(const_cast <ResumeInst*>(this))[i_nocapture].get()); } void ResumeInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( void)0); OperandTraits<ResumeInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned ResumeInst::getNumOperands() const { return OperandTraits<ResumeInst>::operands(this); } template <int Idx_nocapture> Use &ResumeInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ResumeInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
| 4216 | |
| 4217 | //===----------------------------------------------------------------------===// |
| 4218 | // CatchSwitchInst Class |
| 4219 | //===----------------------------------------------------------------------===// |
| 4220 | class CatchSwitchInst : public Instruction { |
| 4221 | using UnwindDestField = BoolBitfieldElementT<0>; |
| 4222 | |
| 4223 | /// The number of operands actually allocated. NumOperands is |
| 4224 | /// the number actually in use. |
| 4225 | unsigned ReservedSpace; |
| 4226 | |
| 4227 | // Operand[0] = Outer scope |
| 4228 | // Operand[1] = Unwind block destination |
| 4229 | // Operand[n] = BasicBlock to go to on match |
| 4230 | CatchSwitchInst(const CatchSwitchInst &CSI); |
| 4231 | |
| 4232 | /// Create a new switch instruction, specifying a |
| 4233 | /// default destination. The number of additional handlers can be specified |
| 4234 | /// here to make memory allocation more efficient. |
| 4235 | /// This constructor can also autoinsert before another instruction. |
| 4236 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
| 4237 | unsigned NumHandlers, const Twine &NameStr, |
| 4238 | Instruction *InsertBefore); |
| 4239 | |
| 4240 | /// Create a new switch instruction, specifying a |
| 4241 | /// default destination. The number of additional handlers can be specified |
| 4242 | /// here to make memory allocation more efficient. |
| 4243 | /// This constructor also autoinserts at the end of the specified BasicBlock. |
| 4244 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
| 4245 | unsigned NumHandlers, const Twine &NameStr, |
| 4246 | BasicBlock *InsertAtEnd); |
| 4247 | |
| 4248 | // allocate space for exactly zero operands |
| 4249 | void *operator new(size_t S) { return User::operator new(S); } |
| 4250 | |
| 4251 | void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved); |
| 4252 | void growOperands(unsigned Size); |
| 4253 | |
| 4254 | protected: |
| 4255 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4256 | friend class Instruction; |
| 4257 | |
| 4258 | CatchSwitchInst *cloneImpl() const; |
| 4259 | |
| 4260 | public: |
| 4261 | void operator delete(void *Ptr) { return User::operator delete(Ptr); } |
| 4262 | |
| 4263 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
| 4264 | unsigned NumHandlers, |
| 4265 | const Twine &NameStr = "", |
| 4266 | Instruction *InsertBefore = nullptr) { |
| 4267 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
| 4268 | InsertBefore); |
| 4269 | } |
| 4270 | |
| 4271 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
| 4272 | unsigned NumHandlers, const Twine &NameStr, |
| 4273 | BasicBlock *InsertAtEnd) { |
| 4274 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
| 4275 | InsertAtEnd); |
| 4276 | } |
| 4277 | |
| 4278 | /// Provide fast operand accessors |
| 4279 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 4280 | |
| 4281 | // Accessor Methods for CatchSwitch stmt |
| 4282 | Value *getParentPad() const { return getOperand(0); } |
| 4283 | void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); } |
| 4284 | |
| 4285 | // Accessor Methods for CatchSwitch stmt |
| 4286 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
| 4287 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
| 4288 | BasicBlock *getUnwindDest() const { |
| 4289 | if (hasUnwindDest()) |
| 4290 | return cast<BasicBlock>(getOperand(1)); |
| 4291 | return nullptr; |
| 4292 | } |
| 4293 | void setUnwindDest(BasicBlock *UnwindDest) { |
| 4294 | assert(UnwindDest)((void)0); |
| 4295 | assert(hasUnwindDest())((void)0); |
| 4296 | setOperand(1, UnwindDest); |
| 4297 | } |
| 4298 | |
| 4299 | /// return the number of 'handlers' in this catchswitch |
| 4300 | /// instruction, except the default handler |
| 4301 | unsigned getNumHandlers() const { |
| 4302 | if (hasUnwindDest()) |
| 4303 | return getNumOperands() - 2; |
| 4304 | return getNumOperands() - 1; |
| 4305 | } |
| 4306 | |
| 4307 | private: |
| 4308 | static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); } |
| 4309 | static const BasicBlock *handler_helper(const Value *V) { |
| 4310 | return cast<BasicBlock>(V); |
| 4311 | } |
| 4312 | |
| 4313 | public: |
| 4314 | using DerefFnTy = BasicBlock *(*)(Value *); |
| 4315 | using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>; |
| 4316 | using handler_range = iterator_range<handler_iterator>; |
| 4317 | using ConstDerefFnTy = const BasicBlock *(*)(const Value *); |
| 4318 | using const_handler_iterator = |
| 4319 | mapped_iterator<const_op_iterator, ConstDerefFnTy>; |
| 4320 | using const_handler_range = iterator_range<const_handler_iterator>; |
| 4321 | |
| 4322 | /// Returns an iterator that points to the first handler in CatchSwitchInst. |
| 4323 | handler_iterator handler_begin() { |
| 4324 | op_iterator It = op_begin() + 1; |
| 4325 | if (hasUnwindDest()) |
| 4326 | ++It; |
| 4327 | return handler_iterator(It, DerefFnTy(handler_helper)); |
| 4328 | } |
| 4329 | |
| 4330 | /// Returns an iterator that points to the first handler in the |
| 4331 | /// CatchSwitchInst. |
| 4332 | const_handler_iterator handler_begin() const { |
| 4333 | const_op_iterator It = op_begin() + 1; |
| 4334 | if (hasUnwindDest()) |
| 4335 | ++It; |
| 4336 | return const_handler_iterator(It, ConstDerefFnTy(handler_helper)); |
| 4337 | } |
| 4338 | |
| 4339 | /// Returns a read-only iterator that points one past the last |
| 4340 | /// handler in the CatchSwitchInst. |
| 4341 | handler_iterator handler_end() { |
| 4342 | return handler_iterator(op_end(), DerefFnTy(handler_helper)); |
| 4343 | } |
| 4344 | |
| 4345 | /// Returns an iterator that points one past the last handler in the |
| 4346 | /// CatchSwitchInst. |
| 4347 | const_handler_iterator handler_end() const { |
| 4348 | return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper)); |
| 4349 | } |
| 4350 | |
| 4351 | /// iteration adapter for range-for loops. |
| 4352 | handler_range handlers() { |
| 4353 | return make_range(handler_begin(), handler_end()); |
| 4354 | } |
| 4355 | |
| 4356 | /// iteration adapter for range-for loops. |
| 4357 | const_handler_range handlers() const { |
| 4358 | return make_range(handler_begin(), handler_end()); |
| 4359 | } |
| 4360 | |
| 4361 | /// Add an entry to the switch instruction... |
| 4362 | /// Note: |
| 4363 | /// This action invalidates handler_end(). Old handler_end() iterator will |
| 4364 | /// point to the added handler. |
| 4365 | void addHandler(BasicBlock *Dest); |
| 4366 | |
| 4367 | void removeHandler(handler_iterator HI); |
| 4368 | |
| 4369 | unsigned getNumSuccessors() const { return getNumOperands() - 1; } |
| 4370 | BasicBlock *getSuccessor(unsigned Idx) const { |
| 4371 | assert(Idx < getNumSuccessors() &&((void)0) |
| 4372 | "Successor # out of range for catchswitch!")((void)0); |
| 4373 | return cast<BasicBlock>(getOperand(Idx + 1)); |
| 4374 | } |
| 4375 | void setSuccessor(unsigned Idx, BasicBlock *NewSucc) { |
| 4376 | assert(Idx < getNumSuccessors() &&((void)0) |
| 4377 | "Successor # out of range for catchswitch!")((void)0); |
| 4378 | setOperand(Idx + 1, NewSucc); |
| 4379 | } |
| 4380 | |
| 4381 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4382 | static bool classof(const Instruction *I) { |
| 4383 | return I->getOpcode() == Instruction::CatchSwitch; |
| 4384 | } |
| 4385 | static bool classof(const Value *V) { |
| 4386 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4387 | } |
| 4388 | }; |
| 4389 | |
| 4390 | template <> |
| 4391 | struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {}; |
| 4392 | |
| 4393 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)CatchSwitchInst::op_iterator CatchSwitchInst::op_begin() { return OperandTraits<CatchSwitchInst>::op_begin(this); } CatchSwitchInst ::const_op_iterator CatchSwitchInst::op_begin() const { return OperandTraits<CatchSwitchInst>::op_begin(const_cast< CatchSwitchInst*>(this)); } CatchSwitchInst::op_iterator CatchSwitchInst ::op_end() { return OperandTraits<CatchSwitchInst>::op_end (this); } CatchSwitchInst::const_op_iterator CatchSwitchInst:: op_end() const { return OperandTraits<CatchSwitchInst>:: op_end(const_cast<CatchSwitchInst*>(this)); } Value *CatchSwitchInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<CatchSwitchInst>::op_begin (const_cast<CatchSwitchInst*>(this))[i_nocapture].get() ); } void CatchSwitchInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((void)0); OperandTraits<CatchSwitchInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CatchSwitchInst::getNumOperands() const { return OperandTraits <CatchSwitchInst>::operands(this); } template <int Idx_nocapture > Use &CatchSwitchInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchSwitchInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
| 4394 | |
| 4395 | //===----------------------------------------------------------------------===// |
| 4396 | // CleanupPadInst Class |
| 4397 | //===----------------------------------------------------------------------===// |
| 4398 | class CleanupPadInst : public FuncletPadInst { |
| 4399 | private: |
| 4400 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
| 4401 | unsigned Values, const Twine &NameStr, |
| 4402 | Instruction *InsertBefore) |
| 4403 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
| 4404 | NameStr, InsertBefore) {} |
| 4405 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
| 4406 | unsigned Values, const Twine &NameStr, |
| 4407 | BasicBlock *InsertAtEnd) |
| 4408 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
| 4409 | NameStr, InsertAtEnd) {} |
| 4410 | |
| 4411 | public: |
| 4412 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None, |
| 4413 | const Twine &NameStr = "", |
| 4414 | Instruction *InsertBefore = nullptr) { |
| 4415 | unsigned Values = 1 + Args.size(); |
| 4416 | return new (Values) |
| 4417 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore); |
| 4418 | } |
| 4419 | |
| 4420 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args, |
| 4421 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 4422 | unsigned Values = 1 + Args.size(); |
| 4423 | return new (Values) |
| 4424 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd); |
| 4425 | } |
| 4426 | |
| 4427 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4428 | static bool classof(const Instruction *I) { |
| 4429 | return I->getOpcode() == Instruction::CleanupPad; |
| 4430 | } |
| 4431 | static bool classof(const Value *V) { |
| 4432 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4433 | } |
| 4434 | }; |
| 4435 | |
| 4436 | //===----------------------------------------------------------------------===// |
| 4437 | // CatchPadInst Class |
| 4438 | //===----------------------------------------------------------------------===// |
| 4439 | class CatchPadInst : public FuncletPadInst { |
| 4440 | private: |
| 4441 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
| 4442 | unsigned Values, const Twine &NameStr, |
| 4443 | Instruction *InsertBefore) |
| 4444 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
| 4445 | NameStr, InsertBefore) {} |
| 4446 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
| 4447 | unsigned Values, const Twine &NameStr, |
| 4448 | BasicBlock *InsertAtEnd) |
| 4449 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
| 4450 | NameStr, InsertAtEnd) {} |
| 4451 | |
| 4452 | public: |
| 4453 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
| 4454 | const Twine &NameStr = "", |
| 4455 | Instruction *InsertBefore = nullptr) { |
| 4456 | unsigned Values = 1 + Args.size(); |
| 4457 | return new (Values) |
| 4458 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore); |
| 4459 | } |
| 4460 | |
| 4461 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
| 4462 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
| 4463 | unsigned Values = 1 + Args.size(); |
| 4464 | return new (Values) |
| 4465 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd); |
| 4466 | } |
| 4467 | |
| 4468 | /// Convenience accessors |
| 4469 | CatchSwitchInst *getCatchSwitch() const { |
| 4470 | return cast<CatchSwitchInst>(Op<-1>()); |
| 4471 | } |
| 4472 | void setCatchSwitch(Value *CatchSwitch) { |
| 4473 | assert(CatchSwitch)((void)0); |
| 4474 | Op<-1>() = CatchSwitch; |
| 4475 | } |
| 4476 | |
| 4477 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4478 | static bool classof(const Instruction *I) { |
| 4479 | return I->getOpcode() == Instruction::CatchPad; |
| 4480 | } |
| 4481 | static bool classof(const Value *V) { |
| 4482 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4483 | } |
| 4484 | }; |
| 4485 | |
| 4486 | //===----------------------------------------------------------------------===// |
| 4487 | // CatchReturnInst Class |
| 4488 | //===----------------------------------------------------------------------===// |
| 4489 | |
| 4490 | class CatchReturnInst : public Instruction { |
| 4491 | CatchReturnInst(const CatchReturnInst &RI); |
| 4492 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore); |
| 4493 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd); |
| 4494 | |
| 4495 | void init(Value *CatchPad, BasicBlock *BB); |
| 4496 | |
| 4497 | protected: |
| 4498 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4499 | friend class Instruction; |
| 4500 | |
| 4501 | CatchReturnInst *cloneImpl() const; |
| 4502 | |
| 4503 | public: |
| 4504 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
| 4505 | Instruction *InsertBefore = nullptr) { |
| 4506 | assert(CatchPad)((void)0); |
| 4507 | assert(BB)((void)0); |
| 4508 | return new (2) CatchReturnInst(CatchPad, BB, InsertBefore); |
| 4509 | } |
| 4510 | |
| 4511 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
| 4512 | BasicBlock *InsertAtEnd) { |
| 4513 | assert(CatchPad)((void)0); |
| 4514 | assert(BB)((void)0); |
| 4515 | return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd); |
| 4516 | } |
| 4517 | |
| 4518 | /// Provide fast operand accessors |
| 4519 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 4520 | |
| 4521 | /// Convenience accessors. |
| 4522 | CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); } |
| 4523 | void setCatchPad(CatchPadInst *CatchPad) { |
| 4524 | assert(CatchPad)((void)0); |
| 4525 | Op<0>() = CatchPad; |
| 4526 | } |
| 4527 | |
| 4528 | BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); } |
| 4529 | void setSuccessor(BasicBlock *NewSucc) { |
| 4530 | assert(NewSucc)((void)0); |
| 4531 | Op<1>() = NewSucc; |
| 4532 | } |
| 4533 | unsigned getNumSuccessors() const { return 1; } |
| 4534 | |
| 4535 | /// Get the parentPad of this catchret's catchpad's catchswitch. |
| 4536 | /// The successor block is implicitly a member of this funclet. |
| 4537 | Value *getCatchSwitchParentPad() const { |
| 4538 | return getCatchPad()->getCatchSwitch()->getParentPad(); |
| 4539 | } |
| 4540 | |
| 4541 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4542 | static bool classof(const Instruction *I) { |
| 4543 | return (I->getOpcode() == Instruction::CatchRet); |
| 4544 | } |
| 4545 | static bool classof(const Value *V) { |
| 4546 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4547 | } |
| 4548 | |
| 4549 | private: |
| 4550 | BasicBlock *getSuccessor(unsigned Idx) const { |
| 4551 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((void)0); |
| 4552 | return getSuccessor(); |
| 4553 | } |
| 4554 | |
| 4555 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
| 4556 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((void)0); |
| 4557 | setSuccessor(B); |
| 4558 | } |
| 4559 | }; |
| 4560 | |
| 4561 | template <> |
| 4562 | struct OperandTraits<CatchReturnInst> |
| 4563 | : public FixedNumOperandTraits<CatchReturnInst, 2> {}; |
| 4564 | |
| 4565 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)CatchReturnInst::op_iterator CatchReturnInst::op_begin() { return OperandTraits<CatchReturnInst>::op_begin(this); } CatchReturnInst ::const_op_iterator CatchReturnInst::op_begin() const { return OperandTraits<CatchReturnInst>::op_begin(const_cast< CatchReturnInst*>(this)); } CatchReturnInst::op_iterator CatchReturnInst ::op_end() { return OperandTraits<CatchReturnInst>::op_end (this); } CatchReturnInst::const_op_iterator CatchReturnInst:: op_end() const { return OperandTraits<CatchReturnInst>:: op_end(const_cast<CatchReturnInst*>(this)); } Value *CatchReturnInst ::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null <Value>( OperandTraits<CatchReturnInst>::op_begin (const_cast<CatchReturnInst*>(this))[i_nocapture].get() ); } void CatchReturnInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((void)0); OperandTraits<CatchReturnInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CatchReturnInst::getNumOperands() const { return OperandTraits <CatchReturnInst>::operands(this); } template <int Idx_nocapture > Use &CatchReturnInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchReturnInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
| 4566 | |
| 4567 | //===----------------------------------------------------------------------===// |
| 4568 | // CleanupReturnInst Class |
| 4569 | //===----------------------------------------------------------------------===// |
| 4570 | |
| 4571 | class CleanupReturnInst : public Instruction { |
| 4572 | using UnwindDestField = BoolBitfieldElementT<0>; |
| 4573 | |
| 4574 | private: |
| 4575 | CleanupReturnInst(const CleanupReturnInst &RI); |
| 4576 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
| 4577 | Instruction *InsertBefore = nullptr); |
| 4578 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
| 4579 | BasicBlock *InsertAtEnd); |
| 4580 | |
| 4581 | void init(Value *CleanupPad, BasicBlock *UnwindBB); |
| 4582 | |
| 4583 | protected: |
| 4584 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4585 | friend class Instruction; |
| 4586 | |
| 4587 | CleanupReturnInst *cloneImpl() const; |
| 4588 | |
| 4589 | public: |
| 4590 | static CleanupReturnInst *Create(Value *CleanupPad, |
| 4591 | BasicBlock *UnwindBB = nullptr, |
| 4592 | Instruction *InsertBefore = nullptr) { |
| 4593 | assert(CleanupPad)((void)0); |
| 4594 | unsigned Values = 1; |
| 4595 | if (UnwindBB) |
| 4596 | ++Values; |
| 4597 | return new (Values) |
| 4598 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore); |
| 4599 | } |
| 4600 | |
| 4601 | static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB, |
| 4602 | BasicBlock *InsertAtEnd) { |
| 4603 | assert(CleanupPad)((void)0); |
| 4604 | unsigned Values = 1; |
| 4605 | if (UnwindBB) |
| 4606 | ++Values; |
| 4607 | return new (Values) |
| 4608 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd); |
| 4609 | } |
| 4610 | |
| 4611 | /// Provide fast operand accessors |
| 4612 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
| 4613 | |
| 4614 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
| 4615 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
| 4616 | |
| 4617 | /// Convenience accessor. |
| 4618 | CleanupPadInst *getCleanupPad() const { |
| 4619 | return cast<CleanupPadInst>(Op<0>()); |
| 4620 | } |
| 4621 | void setCleanupPad(CleanupPadInst *CleanupPad) { |
| 4622 | assert(CleanupPad)((void)0); |
| 4623 | Op<0>() = CleanupPad; |
| 4624 | } |
| 4625 | |
| 4626 | unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; } |
| 4627 | |
| 4628 | BasicBlock *getUnwindDest() const { |
| 4629 | return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr; |
| 4630 | } |
| 4631 | void setUnwindDest(BasicBlock *NewDest) { |
| 4632 | assert(NewDest)((void)0); |
| 4633 | assert(hasUnwindDest())((void)0); |
| 4634 | Op<1>() = NewDest; |
| 4635 | } |
| 4636 | |
| 4637 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4638 | static bool classof(const Instruction *I) { |
| 4639 | return (I->getOpcode() == Instruction::CleanupRet); |
| 4640 | } |
| 4641 | static bool classof(const Value *V) { |
| 4642 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4643 | } |
| 4644 | |
| 4645 | private: |
| 4646 | BasicBlock *getSuccessor(unsigned Idx) const { |
| 4647 | assert(Idx == 0)((void)0); |
| 4648 | return getUnwindDest(); |
| 4649 | } |
| 4650 | |
| 4651 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
| 4652 | assert(Idx == 0)((void)0); |
| 4653 | setUnwindDest(B); |
| 4654 | } |
| 4655 | |
| 4656 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
| 4657 | // method so that subclasses cannot accidentally use it. |
| 4658 | template <typename Bitfield> |
| 4659 | void setSubclassData(typename Bitfield::Type Value) { |
| 4660 | Instruction::setSubclassData<Bitfield>(Value); |
| 4661 | } |
| 4662 | }; |
| 4663 | |
| 4664 | template <> |
| 4665 | struct OperandTraits<CleanupReturnInst> |
| 4666 | : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {}; |
| 4667 | |
| 4668 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)CleanupReturnInst::op_iterator CleanupReturnInst::op_begin() { return OperandTraits<CleanupReturnInst>::op_begin(this ); } CleanupReturnInst::const_op_iterator CleanupReturnInst:: op_begin() const { return OperandTraits<CleanupReturnInst> ::op_begin(const_cast<CleanupReturnInst*>(this)); } CleanupReturnInst ::op_iterator CleanupReturnInst::op_end() { return OperandTraits <CleanupReturnInst>::op_end(this); } CleanupReturnInst:: const_op_iterator CleanupReturnInst::op_end() const { return OperandTraits <CleanupReturnInst>::op_end(const_cast<CleanupReturnInst *>(this)); } Value *CleanupReturnInst::getOperand(unsigned i_nocapture) const { ((void)0); return cast_or_null<Value >( OperandTraits<CleanupReturnInst>::op_begin(const_cast <CleanupReturnInst*>(this))[i_nocapture].get()); } void CleanupReturnInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((void)0); OperandTraits<CleanupReturnInst>::op_begin (this)[i_nocapture] = Val_nocapture; } unsigned CleanupReturnInst ::getNumOperands() const { return OperandTraits<CleanupReturnInst >::operands(this); } template <int Idx_nocapture> Use &CleanupReturnInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & CleanupReturnInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
| 4669 | |
| 4670 | //===----------------------------------------------------------------------===// |
| 4671 | // UnreachableInst Class |
| 4672 | //===----------------------------------------------------------------------===// |
| 4673 | |
| 4674 | //===--------------------------------------------------------------------------- |
| 4675 | /// This function has undefined behavior. In particular, the |
| 4676 | /// presence of this instruction indicates some higher level knowledge that the |
| 4677 | /// end of the block cannot be reached. |
| 4678 | /// |
| 4679 | class UnreachableInst : public Instruction { |
| 4680 | protected: |
| 4681 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4682 | friend class Instruction; |
| 4683 | |
| 4684 | UnreachableInst *cloneImpl() const; |
| 4685 | |
| 4686 | public: |
| 4687 | explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr); |
| 4688 | explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
| 4689 | |
| 4690 | // allocate space for exactly zero operands |
| 4691 | void *operator new(size_t S) { return User::operator new(S, 0); } |
| 4692 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
| 4693 | |
| 4694 | unsigned getNumSuccessors() const { return 0; } |
| 4695 | |
| 4696 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4697 | static bool classof(const Instruction *I) { |
| 4698 | return I->getOpcode() == Instruction::Unreachable; |
| 4699 | } |
| 4700 | static bool classof(const Value *V) { |
| 4701 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4702 | } |
| 4703 | |
| 4704 | private: |
| 4705 | BasicBlock *getSuccessor(unsigned idx) const { |
| 4706 | llvm_unreachable("UnreachableInst has no successors!")__builtin_unreachable(); |
| 4707 | } |
| 4708 | |
| 4709 | void setSuccessor(unsigned idx, BasicBlock *B) { |
| 4710 | llvm_unreachable("UnreachableInst has no successors!")__builtin_unreachable(); |
| 4711 | } |
| 4712 | }; |
| 4713 | |
| 4714 | //===----------------------------------------------------------------------===// |
| 4715 | // TruncInst Class |
| 4716 | //===----------------------------------------------------------------------===// |
| 4717 | |
| 4718 | /// This class represents a truncation of integer types. |
| 4719 | class TruncInst : public CastInst { |
| 4720 | protected: |
| 4721 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4722 | friend class Instruction; |
| 4723 | |
| 4724 | /// Clone an identical TruncInst |
| 4725 | TruncInst *cloneImpl() const; |
| 4726 | |
| 4727 | public: |
| 4728 | /// Constructor with insert-before-instruction semantics |
| 4729 | TruncInst( |
| 4730 | Value *S, ///< The value to be truncated |
| 4731 | Type *Ty, ///< The (smaller) type to truncate to |
| 4732 | const Twine &NameStr = "", ///< A name for the new instruction |
| 4733 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 4734 | ); |
| 4735 | |
| 4736 | /// Constructor with insert-at-end-of-block semantics |
| 4737 | TruncInst( |
| 4738 | Value *S, ///< The value to be truncated |
| 4739 | Type *Ty, ///< The (smaller) type to truncate to |
| 4740 | const Twine &NameStr, ///< A name for the new instruction |
| 4741 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 4742 | ); |
| 4743 | |
| 4744 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4745 | static bool classof(const Instruction *I) { |
| 4746 | return I->getOpcode() == Trunc; |
| 4747 | } |
| 4748 | static bool classof(const Value *V) { |
| 4749 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4750 | } |
| 4751 | }; |
| 4752 | |
| 4753 | //===----------------------------------------------------------------------===// |
| 4754 | // ZExtInst Class |
| 4755 | //===----------------------------------------------------------------------===// |
| 4756 | |
| 4757 | /// This class represents zero extension of integer types. |
| 4758 | class ZExtInst : public CastInst { |
| 4759 | protected: |
| 4760 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4761 | friend class Instruction; |
| 4762 | |
| 4763 | /// Clone an identical ZExtInst |
| 4764 | ZExtInst *cloneImpl() const; |
| 4765 | |
| 4766 | public: |
| 4767 | /// Constructor with insert-before-instruction semantics |
| 4768 | ZExtInst( |
| 4769 | Value *S, ///< The value to be zero extended |
| 4770 | Type *Ty, ///< The type to zero extend to |
| 4771 | const Twine &NameStr = "", ///< A name for the new instruction |
| 4772 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 4773 | ); |
| 4774 | |
| 4775 | /// Constructor with insert-at-end semantics. |
| 4776 | ZExtInst( |
| 4777 | Value *S, ///< The value to be zero extended |
| 4778 | Type *Ty, ///< The type to zero extend to |
| 4779 | const Twine &NameStr, ///< A name for the new instruction |
| 4780 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 4781 | ); |
| 4782 | |
| 4783 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4784 | static bool classof(const Instruction *I) { |
| 4785 | return I->getOpcode() == ZExt; |
| 4786 | } |
| 4787 | static bool classof(const Value *V) { |
| 4788 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4789 | } |
| 4790 | }; |
| 4791 | |
| 4792 | //===----------------------------------------------------------------------===// |
| 4793 | // SExtInst Class |
| 4794 | //===----------------------------------------------------------------------===// |
| 4795 | |
| 4796 | /// This class represents a sign extension of integer types. |
| 4797 | class SExtInst : public CastInst { |
| 4798 | protected: |
| 4799 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4800 | friend class Instruction; |
| 4801 | |
| 4802 | /// Clone an identical SExtInst |
| 4803 | SExtInst *cloneImpl() const; |
| 4804 | |
| 4805 | public: |
| 4806 | /// Constructor with insert-before-instruction semantics |
| 4807 | SExtInst( |
| 4808 | Value *S, ///< The value to be sign extended |
| 4809 | Type *Ty, ///< The type to sign extend to |
| 4810 | const Twine &NameStr = "", ///< A name for the new instruction |
| 4811 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 4812 | ); |
| 4813 | |
| 4814 | /// Constructor with insert-at-end-of-block semantics |
| 4815 | SExtInst( |
| 4816 | Value *S, ///< The value to be sign extended |
| 4817 | Type *Ty, ///< The type to sign extend to |
| 4818 | const Twine &NameStr, ///< A name for the new instruction |
| 4819 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 4820 | ); |
| 4821 | |
| 4822 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4823 | static bool classof(const Instruction *I) { |
| 4824 | return I->getOpcode() == SExt; |
| 4825 | } |
| 4826 | static bool classof(const Value *V) { |
| 4827 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4828 | } |
| 4829 | }; |
| 4830 | |
| 4831 | //===----------------------------------------------------------------------===// |
| 4832 | // FPTruncInst Class |
| 4833 | //===----------------------------------------------------------------------===// |
| 4834 | |
| 4835 | /// This class represents a truncation of floating point types. |
| 4836 | class FPTruncInst : public CastInst { |
| 4837 | protected: |
| 4838 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4839 | friend class Instruction; |
| 4840 | |
| 4841 | /// Clone an identical FPTruncInst |
| 4842 | FPTruncInst *cloneImpl() const; |
| 4843 | |
| 4844 | public: |
| 4845 | /// Constructor with insert-before-instruction semantics |
| 4846 | FPTruncInst( |
| 4847 | Value *S, ///< The value to be truncated |
| 4848 | Type *Ty, ///< The type to truncate to |
| 4849 | const Twine &NameStr = "", ///< A name for the new instruction |
| 4850 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 4851 | ); |
| 4852 | |
| 4853 | /// Constructor with insert-before-instruction semantics |
| 4854 | FPTruncInst( |
| 4855 | Value *S, ///< The value to be truncated |
| 4856 | Type *Ty, ///< The type to truncate to |
| 4857 | const Twine &NameStr, ///< A name for the new instruction |
| 4858 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 4859 | ); |
| 4860 | |
| 4861 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4862 | static bool classof(const Instruction *I) { |
| 4863 | return I->getOpcode() == FPTrunc; |
| 4864 | } |
| 4865 | static bool classof(const Value *V) { |
| 4866 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4867 | } |
| 4868 | }; |
| 4869 | |
| 4870 | //===----------------------------------------------------------------------===// |
| 4871 | // FPExtInst Class |
| 4872 | //===----------------------------------------------------------------------===// |
| 4873 | |
| 4874 | /// This class represents an extension of floating point types. |
| 4875 | class FPExtInst : public CastInst { |
| 4876 | protected: |
| 4877 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4878 | friend class Instruction; |
| 4879 | |
| 4880 | /// Clone an identical FPExtInst |
| 4881 | FPExtInst *cloneImpl() const; |
| 4882 | |
| 4883 | public: |
| 4884 | /// Constructor with insert-before-instruction semantics |
| 4885 | FPExtInst( |
| 4886 | Value *S, ///< The value to be extended |
| 4887 | Type *Ty, ///< The type to extend to |
| 4888 | const Twine &NameStr = "", ///< A name for the new instruction |
| 4889 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 4890 | ); |
| 4891 | |
| 4892 | /// Constructor with insert-at-end-of-block semantics |
| 4893 | FPExtInst( |
| 4894 | Value *S, ///< The value to be extended |
| 4895 | Type *Ty, ///< The type to extend to |
| 4896 | const Twine &NameStr, ///< A name for the new instruction |
| 4897 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 4898 | ); |
| 4899 | |
| 4900 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4901 | static bool classof(const Instruction *I) { |
| 4902 | return I->getOpcode() == FPExt; |
| 4903 | } |
| 4904 | static bool classof(const Value *V) { |
| 4905 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4906 | } |
| 4907 | }; |
| 4908 | |
| 4909 | //===----------------------------------------------------------------------===// |
| 4910 | // UIToFPInst Class |
| 4911 | //===----------------------------------------------------------------------===// |
| 4912 | |
| 4913 | /// This class represents a cast unsigned integer to floating point. |
| 4914 | class UIToFPInst : public CastInst { |
| 4915 | protected: |
| 4916 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4917 | friend class Instruction; |
| 4918 | |
| 4919 | /// Clone an identical UIToFPInst |
| 4920 | UIToFPInst *cloneImpl() const; |
| 4921 | |
| 4922 | public: |
| 4923 | /// Constructor with insert-before-instruction semantics |
| 4924 | UIToFPInst( |
| 4925 | Value *S, ///< The value to be converted |
| 4926 | Type *Ty, ///< The type to convert to |
| 4927 | const Twine &NameStr = "", ///< A name for the new instruction |
| 4928 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 4929 | ); |
| 4930 | |
| 4931 | /// Constructor with insert-at-end-of-block semantics |
| 4932 | UIToFPInst( |
| 4933 | Value *S, ///< The value to be converted |
| 4934 | Type *Ty, ///< The type to convert to |
| 4935 | const Twine &NameStr, ///< A name for the new instruction |
| 4936 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 4937 | ); |
| 4938 | |
| 4939 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4940 | static bool classof(const Instruction *I) { |
| 4941 | return I->getOpcode() == UIToFP; |
| 4942 | } |
| 4943 | static bool classof(const Value *V) { |
| 4944 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4945 | } |
| 4946 | }; |
| 4947 | |
| 4948 | //===----------------------------------------------------------------------===// |
| 4949 | // SIToFPInst Class |
| 4950 | //===----------------------------------------------------------------------===// |
| 4951 | |
| 4952 | /// This class represents a cast from signed integer to floating point. |
| 4953 | class SIToFPInst : public CastInst { |
| 4954 | protected: |
| 4955 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4956 | friend class Instruction; |
| 4957 | |
| 4958 | /// Clone an identical SIToFPInst |
| 4959 | SIToFPInst *cloneImpl() const; |
| 4960 | |
| 4961 | public: |
| 4962 | /// Constructor with insert-before-instruction semantics |
| 4963 | SIToFPInst( |
| 4964 | Value *S, ///< The value to be converted |
| 4965 | Type *Ty, ///< The type to convert to |
| 4966 | const Twine &NameStr = "", ///< A name for the new instruction |
| 4967 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 4968 | ); |
| 4969 | |
| 4970 | /// Constructor with insert-at-end-of-block semantics |
| 4971 | SIToFPInst( |
| 4972 | Value *S, ///< The value to be converted |
| 4973 | Type *Ty, ///< The type to convert to |
| 4974 | const Twine &NameStr, ///< A name for the new instruction |
| 4975 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 4976 | ); |
| 4977 | |
| 4978 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 4979 | static bool classof(const Instruction *I) { |
| 4980 | return I->getOpcode() == SIToFP; |
| 4981 | } |
| 4982 | static bool classof(const Value *V) { |
| 4983 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 4984 | } |
| 4985 | }; |
| 4986 | |
| 4987 | //===----------------------------------------------------------------------===// |
| 4988 | // FPToUIInst Class |
| 4989 | //===----------------------------------------------------------------------===// |
| 4990 | |
| 4991 | /// This class represents a cast from floating point to unsigned integer |
| 4992 | class FPToUIInst : public CastInst { |
| 4993 | protected: |
| 4994 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 4995 | friend class Instruction; |
| 4996 | |
| 4997 | /// Clone an identical FPToUIInst |
| 4998 | FPToUIInst *cloneImpl() const; |
| 4999 | |
| 5000 | public: |
| 5001 | /// Constructor with insert-before-instruction semantics |
| 5002 | FPToUIInst( |
| 5003 | Value *S, ///< The value to be converted |
| 5004 | Type *Ty, ///< The type to convert to |
| 5005 | const Twine &NameStr = "", ///< A name for the new instruction |
| 5006 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 5007 | ); |
| 5008 | |
| 5009 | /// Constructor with insert-at-end-of-block semantics |
| 5010 | FPToUIInst( |
| 5011 | Value *S, ///< The value to be converted |
| 5012 | Type *Ty, ///< The type to convert to |
| 5013 | const Twine &NameStr, ///< A name for the new instruction |
| 5014 | BasicBlock *InsertAtEnd ///< Where to insert the new instruction |
| 5015 | ); |
| 5016 | |
| 5017 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 5018 | static bool classof(const Instruction *I) { |
| 5019 | return I->getOpcode() == FPToUI; |
| 5020 | } |
| 5021 | static bool classof(const Value *V) { |
| 5022 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 5023 | } |
| 5024 | }; |
| 5025 | |
| 5026 | //===----------------------------------------------------------------------===// |
| 5027 | // FPToSIInst Class |
| 5028 | //===----------------------------------------------------------------------===// |
| 5029 | |
| 5030 | /// This class represents a cast from floating point to signed integer. |
| 5031 | class FPToSIInst : public CastInst { |
| 5032 | protected: |
| 5033 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 5034 | friend class Instruction; |
| 5035 | |
| 5036 | /// Clone an identical FPToSIInst |
| 5037 | FPToSIInst *cloneImpl() const; |
| 5038 | |
| 5039 | public: |
| 5040 | /// Constructor with insert-before-instruction semantics |
| 5041 | FPToSIInst( |
| 5042 | Value *S, ///< The value to be converted |
| 5043 | Type *Ty, ///< The type to convert to |
| 5044 | const Twine &NameStr = "", ///< A name for the new instruction |
| 5045 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 5046 | ); |
| 5047 | |
| 5048 | /// Constructor with insert-at-end-of-block semantics |
| 5049 | FPToSIInst( |
| 5050 | Value *S, ///< The value to be converted |
| 5051 | Type *Ty, ///< The type to convert to |
| 5052 | const Twine &NameStr, ///< A name for the new instruction |
| 5053 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 5054 | ); |
| 5055 | |
| 5056 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
| 5057 | static bool classof(const Instruction *I) { |
| 5058 | return I->getOpcode() == FPToSI; |
| 5059 | } |
| 5060 | static bool classof(const Value *V) { |
| 5061 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 5062 | } |
| 5063 | }; |
| 5064 | |
| 5065 | //===----------------------------------------------------------------------===// |
| 5066 | // IntToPtrInst Class |
| 5067 | //===----------------------------------------------------------------------===// |
| 5068 | |
| 5069 | /// This class represents a cast from an integer to a pointer. |
| 5070 | class IntToPtrInst : public CastInst { |
| 5071 | public: |
| 5072 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 5073 | friend class Instruction; |
| 5074 | |
| 5075 | /// Constructor with insert-before-instruction semantics |
| 5076 | IntToPtrInst( |
| 5077 | Value *S, ///< The value to be converted |
| 5078 | Type *Ty, ///< The type to convert to |
| 5079 | const Twine &NameStr = "", ///< A name for the new instruction |
| 5080 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 5081 | ); |
| 5082 | |
| 5083 | /// Constructor with insert-at-end-of-block semantics |
| 5084 | IntToPtrInst( |
| 5085 | Value *S, ///< The value to be converted |
| 5086 | Type *Ty, ///< The type to convert to |
| 5087 | const Twine &NameStr, ///< A name for the new instruction |
| 5088 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 5089 | ); |
| 5090 | |
| 5091 | /// Clone an identical IntToPtrInst. |
| 5092 | IntToPtrInst *cloneImpl() const; |
| 5093 | |
| 5094 | /// Returns the address space of this instruction's pointer type. |
| 5095 | unsigned getAddressSpace() const { |
| 5096 | return getType()->getPointerAddressSpace(); |
| 5097 | } |
| 5098 | |
| 5099 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 5100 | static bool classof(const Instruction *I) { |
| 5101 | return I->getOpcode() == IntToPtr; |
| 5102 | } |
| 5103 | static bool classof(const Value *V) { |
| 5104 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 5105 | } |
| 5106 | }; |
| 5107 | |
| 5108 | //===----------------------------------------------------------------------===// |
| 5109 | // PtrToIntInst Class |
| 5110 | //===----------------------------------------------------------------------===// |
| 5111 | |
| 5112 | /// This class represents a cast from a pointer to an integer. |
| 5113 | class PtrToIntInst : public CastInst { |
| 5114 | protected: |
| 5115 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 5116 | friend class Instruction; |
| 5117 | |
| 5118 | /// Clone an identical PtrToIntInst. |
| 5119 | PtrToIntInst *cloneImpl() const; |
| 5120 | |
| 5121 | public: |
| 5122 | /// Constructor with insert-before-instruction semantics |
| 5123 | PtrToIntInst( |
| 5124 | Value *S, ///< The value to be converted |
| 5125 | Type *Ty, ///< The type to convert to |
| 5126 | const Twine &NameStr = "", ///< A name for the new instruction |
| 5127 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 5128 | ); |
| 5129 | |
| 5130 | /// Constructor with insert-at-end-of-block semantics |
| 5131 | PtrToIntInst( |
| 5132 | Value *S, ///< The value to be converted |
| 5133 | Type *Ty, ///< The type to convert to |
| 5134 | const Twine &NameStr, ///< A name for the new instruction |
| 5135 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 5136 | ); |
| 5137 | |
| 5138 | /// Gets the pointer operand. |
| 5139 | Value *getPointerOperand() { return getOperand(0); } |
| 5140 | /// Gets the pointer operand. |
| 5141 | const Value *getPointerOperand() const { return getOperand(0); } |
| 5142 | /// Gets the operand index of the pointer operand. |
| 5143 | static unsigned getPointerOperandIndex() { return 0U; } |
| 5144 | |
| 5145 | /// Returns the address space of the pointer operand. |
| 5146 | unsigned getPointerAddressSpace() const { |
| 5147 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
| 5148 | } |
| 5149 | |
| 5150 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 5151 | static bool classof(const Instruction *I) { |
| 5152 | return I->getOpcode() == PtrToInt; |
| 5153 | } |
| 5154 | static bool classof(const Value *V) { |
| 5155 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 5156 | } |
| 5157 | }; |
| 5158 | |
| 5159 | //===----------------------------------------------------------------------===// |
| 5160 | // BitCastInst Class |
| 5161 | //===----------------------------------------------------------------------===// |
| 5162 | |
| 5163 | /// This class represents a no-op cast from one type to another. |
| 5164 | class BitCastInst : public CastInst { |
| 5165 | protected: |
| 5166 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 5167 | friend class Instruction; |
| 5168 | |
| 5169 | /// Clone an identical BitCastInst. |
| 5170 | BitCastInst *cloneImpl() const; |
| 5171 | |
| 5172 | public: |
| 5173 | /// Constructor with insert-before-instruction semantics |
| 5174 | BitCastInst( |
| 5175 | Value *S, ///< The value to be casted |
| 5176 | Type *Ty, ///< The type to casted to |
| 5177 | const Twine &NameStr = "", ///< A name for the new instruction |
| 5178 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 5179 | ); |
| 5180 | |
| 5181 | /// Constructor with insert-at-end-of-block semantics |
| 5182 | BitCastInst( |
| 5183 | Value *S, ///< The value to be casted |
| 5184 | Type *Ty, ///< The type to casted to |
| 5185 | const Twine &NameStr, ///< A name for the new instruction |
| 5186 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 5187 | ); |
| 5188 | |
| 5189 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 5190 | static bool classof(const Instruction *I) { |
| 5191 | return I->getOpcode() == BitCast; |
| 5192 | } |
| 5193 | static bool classof(const Value *V) { |
| 5194 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 5195 | } |
| 5196 | }; |
| 5197 | |
| 5198 | //===----------------------------------------------------------------------===// |
| 5199 | // AddrSpaceCastInst Class |
| 5200 | //===----------------------------------------------------------------------===// |
| 5201 | |
| 5202 | /// This class represents a conversion between pointers from one address space |
| 5203 | /// to another. |
| 5204 | class AddrSpaceCastInst : public CastInst { |
| 5205 | protected: |
| 5206 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 5207 | friend class Instruction; |
| 5208 | |
| 5209 | /// Clone an identical AddrSpaceCastInst. |
| 5210 | AddrSpaceCastInst *cloneImpl() const; |
| 5211 | |
| 5212 | public: |
| 5213 | /// Constructor with insert-before-instruction semantics |
| 5214 | AddrSpaceCastInst( |
| 5215 | Value *S, ///< The value to be casted |
| 5216 | Type *Ty, ///< The type to casted to |
| 5217 | const Twine &NameStr = "", ///< A name for the new instruction |
| 5218 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
| 5219 | ); |
| 5220 | |
| 5221 | /// Constructor with insert-at-end-of-block semantics |
| 5222 | AddrSpaceCastInst( |
| 5223 | Value *S, ///< The value to be casted |
| 5224 | Type *Ty, ///< The type to casted to |
| 5225 | const Twine &NameStr, ///< A name for the new instruction |
| 5226 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
| 5227 | ); |
| 5228 | |
| 5229 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 5230 | static bool classof(const Instruction *I) { |
| 5231 | return I->getOpcode() == AddrSpaceCast; |
| 5232 | } |
| 5233 | static bool classof(const Value *V) { |
| 5234 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 5235 | } |
| 5236 | |
| 5237 | /// Gets the pointer operand. |
| 5238 | Value *getPointerOperand() { |
| 5239 | return getOperand(0); |
| 5240 | } |
| 5241 | |
| 5242 | /// Gets the pointer operand. |
| 5243 | const Value *getPointerOperand() const { |
| 5244 | return getOperand(0); |
| 5245 | } |
| 5246 | |
| 5247 | /// Gets the operand index of the pointer operand. |
| 5248 | static unsigned getPointerOperandIndex() { |
| 5249 | return 0U; |
| 5250 | } |
| 5251 | |
| 5252 | /// Returns the address space of the pointer operand. |
| 5253 | unsigned getSrcAddressSpace() const { |
| 5254 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
| 5255 | } |
| 5256 | |
| 5257 | /// Returns the address space of the result. |
| 5258 | unsigned getDestAddressSpace() const { |
| 5259 | return getType()->getPointerAddressSpace(); |
| 5260 | } |
| 5261 | }; |
| 5262 | |
| 5263 | /// A helper function that returns the pointer operand of a load or store |
| 5264 | /// instruction. Returns nullptr if not load or store. |
| 5265 | inline const Value *getLoadStorePointerOperand(const Value *V) { |
| 5266 | if (auto *Load = dyn_cast<LoadInst>(V)) |
| 5267 | return Load->getPointerOperand(); |
| 5268 | if (auto *Store = dyn_cast<StoreInst>(V)) |
| 5269 | return Store->getPointerOperand(); |
| 5270 | return nullptr; |
| 5271 | } |
| 5272 | inline Value *getLoadStorePointerOperand(Value *V) { |
| 5273 | return const_cast<Value *>( |
| 5274 | getLoadStorePointerOperand(static_cast<const Value *>(V))); |
| 5275 | } |
| 5276 | |
| 5277 | /// A helper function that returns the pointer operand of a load, store |
| 5278 | /// or GEP instruction. Returns nullptr if not load, store, or GEP. |
| 5279 | inline const Value *getPointerOperand(const Value *V) { |
| 5280 | if (auto *Ptr = getLoadStorePointerOperand(V)) |
| 5281 | return Ptr; |
| 5282 | if (auto *Gep = dyn_cast<GetElementPtrInst>(V)) |
| 5283 | return Gep->getPointerOperand(); |
| 5284 | return nullptr; |
| 5285 | } |
| 5286 | inline Value *getPointerOperand(Value *V) { |
| 5287 | return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V))); |
| 5288 | } |
| 5289 | |
| 5290 | /// A helper function that returns the alignment of load or store instruction. |
| 5291 | inline Align getLoadStoreAlignment(Value *I) { |
| 5292 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&((void)0) |
| 5293 | "Expected Load or Store instruction")((void)0); |
| 5294 | if (auto *LI = dyn_cast<LoadInst>(I)) |
| 5295 | return LI->getAlign(); |
| 5296 | return cast<StoreInst>(I)->getAlign(); |
| 5297 | } |
| 5298 | |
| 5299 | /// A helper function that returns the address space of the pointer operand of |
| 5300 | /// load or store instruction. |
| 5301 | inline unsigned getLoadStoreAddressSpace(Value *I) { |
| 5302 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&((void)0) |
| 5303 | "Expected Load or Store instruction")((void)0); |
| 5304 | if (auto *LI = dyn_cast<LoadInst>(I)) |
| 5305 | return LI->getPointerAddressSpace(); |
| 5306 | return cast<StoreInst>(I)->getPointerAddressSpace(); |
| 5307 | } |
| 5308 | |
| 5309 | /// A helper function that returns the type of a load or store instruction. |
| 5310 | inline Type *getLoadStoreType(Value *I) { |
| 5311 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&((void)0) |
| 5312 | "Expected Load or Store instruction")((void)0); |
| 5313 | if (auto *LI = dyn_cast<LoadInst>(I)) |
| 5314 | return LI->getType(); |
| 5315 | return cast<StoreInst>(I)->getValueOperand()->getType(); |
| 5316 | } |
| 5317 | |
| 5318 | //===----------------------------------------------------------------------===// |
| 5319 | // FreezeInst Class |
| 5320 | //===----------------------------------------------------------------------===// |
| 5321 | |
| 5322 | /// This class represents a freeze function that returns random concrete |
| 5323 | /// value if an operand is either a poison value or an undef value |
| 5324 | class FreezeInst : public UnaryInstruction { |
| 5325 | protected: |
| 5326 | // Note: Instruction needs to be a friend here to call cloneImpl. |
| 5327 | friend class Instruction; |
| 5328 | |
| 5329 | /// Clone an identical FreezeInst |
| 5330 | FreezeInst *cloneImpl() const; |
| 5331 | |
| 5332 | public: |
| 5333 | explicit FreezeInst(Value *S, |
| 5334 | const Twine &NameStr = "", |
| 5335 | Instruction *InsertBefore = nullptr); |
| 5336 | FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd); |
| 5337 | |
| 5338 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
| 5339 | static inline bool classof(const Instruction *I) { |
| 5340 | return I->getOpcode() == Freeze; |
| 5341 | } |
| 5342 | static inline bool classof(const Value *V) { |
| 5343 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
| 5344 | } |
| 5345 | }; |
| 5346 | |
| 5347 | } // end namespace llvm |
| 5348 | |
| 5349 | #endif // LLVM_IR_INSTRUCTIONS_H |