1 //===--- SelectOptimize.cpp - Convert select to branches if profitable ---===// 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 converts selects to conditional jumps when profitable. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/SelectOptimize.h" 14 #include "llvm/ADT/SmallVector.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/Analysis/BlockFrequencyInfo.h" 17 #include "llvm/Analysis/BranchProbabilityInfo.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 20 #include "llvm/Analysis/ProfileSummaryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/CodeGen/Passes.h" 23 #include "llvm/CodeGen/TargetLowering.h" 24 #include "llvm/CodeGen/TargetPassConfig.h" 25 #include "llvm/CodeGen/TargetSchedule.h" 26 #include "llvm/CodeGen/TargetSubtargetInfo.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/IRBuilder.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/PatternMatch.h" 33 #include "llvm/IR/ProfDataUtils.h" 34 #include "llvm/InitializePasses.h" 35 #include "llvm/Pass.h" 36 #include "llvm/Support/ScaledNumber.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Transforms/Utils/SizeOpts.h" 39 #include <algorithm> 40 #include <memory> 41 #include <queue> 42 #include <stack> 43 44 using namespace llvm; 45 using namespace llvm::PatternMatch; 46 47 #define DEBUG_TYPE "select-optimize" 48 49 STATISTIC(NumSelectOptAnalyzed, 50 "Number of select groups considered for conversion to branch"); 51 STATISTIC(NumSelectConvertedExpColdOperand, 52 "Number of select groups converted due to expensive cold operand"); 53 STATISTIC(NumSelectConvertedHighPred, 54 "Number of select groups converted due to high-predictability"); 55 STATISTIC(NumSelectUnPred, 56 "Number of select groups not converted due to unpredictability"); 57 STATISTIC(NumSelectColdBB, 58 "Number of select groups not converted due to cold basic block"); 59 STATISTIC(NumSelectConvertedLoop, 60 "Number of select groups converted due to loop-level analysis"); 61 STATISTIC(NumSelectsConverted, "Number of selects converted"); 62 63 static cl::opt<unsigned> ColdOperandThreshold( 64 "cold-operand-threshold", 65 cl::desc("Maximum frequency of path for an operand to be considered cold."), 66 cl::init(20), cl::Hidden); 67 68 static cl::opt<unsigned> ColdOperandMaxCostMultiplier( 69 "cold-operand-max-cost-multiplier", 70 cl::desc("Maximum cost multiplier of TCC_expensive for the dependence " 71 "slice of a cold operand to be considered inexpensive."), 72 cl::init(1), cl::Hidden); 73 74 static cl::opt<unsigned> 75 GainGradientThreshold("select-opti-loop-gradient-gain-threshold", 76 cl::desc("Gradient gain threshold (%)."), 77 cl::init(25), cl::Hidden); 78 79 static cl::opt<unsigned> 80 GainCycleThreshold("select-opti-loop-cycle-gain-threshold", 81 cl::desc("Minimum gain per loop (in cycles) threshold."), 82 cl::init(4), cl::Hidden); 83 84 static cl::opt<unsigned> GainRelativeThreshold( 85 "select-opti-loop-relative-gain-threshold", 86 cl::desc( 87 "Minimum relative gain per loop threshold (1/X). Defaults to 12.5%"), 88 cl::init(8), cl::Hidden); 89 90 static cl::opt<unsigned> MispredictDefaultRate( 91 "mispredict-default-rate", cl::Hidden, cl::init(25), 92 cl::desc("Default mispredict rate (initialized to 25%).")); 93 94 static cl::opt<bool> 95 DisableLoopLevelHeuristics("disable-loop-level-heuristics", cl::Hidden, 96 cl::init(false), 97 cl::desc("Disable loop-level heuristics.")); 98 99 namespace { 100 101 class SelectOptimizeImpl { 102 const TargetMachine *TM = nullptr; 103 const TargetSubtargetInfo *TSI = nullptr; 104 const TargetLowering *TLI = nullptr; 105 const TargetTransformInfo *TTI = nullptr; 106 const LoopInfo *LI = nullptr; 107 BlockFrequencyInfo *BFI; 108 ProfileSummaryInfo *PSI = nullptr; 109 OptimizationRemarkEmitter *ORE = nullptr; 110 TargetSchedModel TSchedModel; 111 112 public: 113 SelectOptimizeImpl() = default; 114 SelectOptimizeImpl(const TargetMachine *TM) : TM(TM){}; 115 PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM); 116 bool runOnFunction(Function &F, Pass &P); 117 118 using Scaled64 = ScaledNumber<uint64_t>; 119 120 struct CostInfo { 121 /// Predicated cost (with selects as conditional moves). 122 Scaled64 PredCost; 123 /// Non-predicated cost (with selects converted to branches). 124 Scaled64 NonPredCost; 125 }; 126 127 /// SelectLike is an abstraction over SelectInst and other operations that can 128 /// act like selects. For example Or(Zext(icmp), X) can be treated like 129 /// select(icmp, X|1, X). 130 class SelectLike { 131 SelectLike(Instruction *I) : I(I) {} 132 133 /// The select (/or) instruction. 134 Instruction *I; 135 /// Whether this select is inverted, "not(cond), FalseVal, TrueVal", as 136 /// opposed to the original condition. 137 bool Inverted = false; 138 139 public: 140 /// Match a select or select-like instruction, returning a SelectLike. 141 static SelectLike match(Instruction *I) { 142 // Select instruction are what we are usually looking for. 143 if (isa<SelectInst>(I)) 144 return SelectLike(I); 145 146 // An Or(zext(i1 X), Y) can also be treated like a select, with condition 147 // C and values Y|1 and Y. 148 Value *X; 149 if (PatternMatch::match( 150 I, m_c_Or(m_OneUse(m_ZExt(m_Value(X))), m_Value())) && 151 X->getType()->isIntegerTy(1)) 152 return SelectLike(I); 153 154 return SelectLike(nullptr); 155 } 156 157 bool isValid() { return I; } 158 operator bool() { return isValid(); } 159 160 /// Invert the select by inverting the condition and switching the operands. 161 void setInverted() { 162 assert(!Inverted && "Trying to invert an inverted SelectLike"); 163 assert(isa<Instruction>(getCondition()) && 164 cast<Instruction>(getCondition())->getOpcode() == 165 Instruction::Xor); 166 Inverted = true; 167 } 168 bool isInverted() const { return Inverted; } 169 170 Instruction *getI() { return I; } 171 const Instruction *getI() const { return I; } 172 173 Type *getType() const { return I->getType(); } 174 175 Value *getNonInvertedCondition() const { 176 if (auto *Sel = dyn_cast<SelectInst>(I)) 177 return Sel->getCondition(); 178 // Or(zext) case 179 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 180 Value *X; 181 if (PatternMatch::match(BO->getOperand(0), 182 m_OneUse(m_ZExt(m_Value(X))))) 183 return X; 184 if (PatternMatch::match(BO->getOperand(1), 185 m_OneUse(m_ZExt(m_Value(X))))) 186 return X; 187 } 188 189 llvm_unreachable("Unhandled case in getCondition"); 190 } 191 192 /// Return the condition for the SelectLike instruction. For example the 193 /// condition of a select or c in `or(zext(c), x)` 194 Value *getCondition() const { 195 Value *CC = getNonInvertedCondition(); 196 // For inverted conditions the CC is checked when created to be a not 197 // (xor) instruction. 198 if (Inverted) 199 return cast<Instruction>(CC)->getOperand(0); 200 return CC; 201 } 202 203 /// Return the true value for the SelectLike instruction. Note this may not 204 /// exist for all SelectLike instructions. For example, for `or(zext(c), x)` 205 /// the true value would be `or(x,1)`. As this value does not exist, nullptr 206 /// is returned. 207 Value *getTrueValue(bool HonorInverts = true) const { 208 if (Inverted && HonorInverts) 209 return getFalseValue(/*HonorInverts=*/false); 210 if (auto *Sel = dyn_cast<SelectInst>(I)) 211 return Sel->getTrueValue(); 212 // Or(zext) case - The true value is Or(X), so return nullptr as the value 213 // does not yet exist. 214 if (isa<BinaryOperator>(I)) 215 return nullptr; 216 217 llvm_unreachable("Unhandled case in getTrueValue"); 218 } 219 220 /// Return the false value for the SelectLike instruction. For example the 221 /// getFalseValue of a select or `x` in `or(zext(c), x)` (which is 222 /// `select(c, x|1, x)`) 223 Value *getFalseValue(bool HonorInverts = true) const { 224 if (Inverted && HonorInverts) 225 return getTrueValue(/*HonorInverts=*/false); 226 if (auto *Sel = dyn_cast<SelectInst>(I)) 227 return Sel->getFalseValue(); 228 // Or(zext) case - return the operand which is not the zext. 229 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 230 Value *X; 231 if (PatternMatch::match(BO->getOperand(0), 232 m_OneUse(m_ZExt(m_Value(X))))) 233 return BO->getOperand(1); 234 if (PatternMatch::match(BO->getOperand(1), 235 m_OneUse(m_ZExt(m_Value(X))))) 236 return BO->getOperand(0); 237 } 238 239 llvm_unreachable("Unhandled case in getFalseValue"); 240 } 241 242 /// Return the NonPredCost cost of the true op, given the costs in 243 /// InstCostMap. This may need to be generated for select-like instructions. 244 Scaled64 getTrueOpCost(DenseMap<const Instruction *, CostInfo> &InstCostMap, 245 const TargetTransformInfo *TTI) { 246 if (isa<SelectInst>(I)) 247 if (auto *I = dyn_cast<Instruction>(getTrueValue())) { 248 auto It = InstCostMap.find(I); 249 return It != InstCostMap.end() ? It->second.NonPredCost 250 : Scaled64::getZero(); 251 } 252 253 // Or case - add the cost of an extra Or to the cost of the False case. 254 if (isa<BinaryOperator>(I)) 255 if (auto I = dyn_cast<Instruction>(getFalseValue())) { 256 auto It = InstCostMap.find(I); 257 if (It != InstCostMap.end()) { 258 InstructionCost OrCost = TTI->getArithmeticInstrCost( 259 Instruction::Or, I->getType(), TargetTransformInfo::TCK_Latency, 260 {TargetTransformInfo::OK_AnyValue, 261 TargetTransformInfo::OP_None}, 262 {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2}); 263 return It->second.NonPredCost + Scaled64::get(*OrCost.getValue()); 264 } 265 } 266 267 return Scaled64::getZero(); 268 } 269 270 /// Return the NonPredCost cost of the false op, given the costs in 271 /// InstCostMap. This may need to be generated for select-like instructions. 272 Scaled64 273 getFalseOpCost(DenseMap<const Instruction *, CostInfo> &InstCostMap, 274 const TargetTransformInfo *TTI) { 275 if (isa<SelectInst>(I)) 276 if (auto *I = dyn_cast<Instruction>(getFalseValue())) { 277 auto It = InstCostMap.find(I); 278 return It != InstCostMap.end() ? It->second.NonPredCost 279 : Scaled64::getZero(); 280 } 281 282 // Or case - return the cost of the false case 283 if (isa<BinaryOperator>(I)) 284 if (auto I = dyn_cast<Instruction>(getFalseValue())) 285 if (auto It = InstCostMap.find(I); It != InstCostMap.end()) 286 return It->second.NonPredCost; 287 288 return Scaled64::getZero(); 289 } 290 }; 291 292 private: 293 // Select groups consist of consecutive select instructions with the same 294 // condition. 295 using SelectGroup = SmallVector<SelectLike, 2>; 296 using SelectGroups = SmallVector<SelectGroup, 2>; 297 298 // Converts select instructions of a function to conditional jumps when deemed 299 // profitable. Returns true if at least one select was converted. 300 bool optimizeSelects(Function &F); 301 302 // Heuristics for determining which select instructions can be profitably 303 // conveted to branches. Separate heuristics for selects in inner-most loops 304 // and the rest of code regions (base heuristics for non-inner-most loop 305 // regions). 306 void optimizeSelectsBase(Function &F, SelectGroups &ProfSIGroups); 307 void optimizeSelectsInnerLoops(Function &F, SelectGroups &ProfSIGroups); 308 309 // Converts to branches the select groups that were deemed 310 // profitable-to-convert. 311 void convertProfitableSIGroups(SelectGroups &ProfSIGroups); 312 313 // Splits selects of a given basic block into select groups. 314 void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups); 315 316 // Determines for which select groups it is profitable converting to branches 317 // (base and inner-most-loop heuristics). 318 void findProfitableSIGroupsBase(SelectGroups &SIGroups, 319 SelectGroups &ProfSIGroups); 320 void findProfitableSIGroupsInnerLoops(const Loop *L, SelectGroups &SIGroups, 321 SelectGroups &ProfSIGroups); 322 323 // Determines if a select group should be converted to a branch (base 324 // heuristics). 325 bool isConvertToBranchProfitableBase(const SelectGroup &ASI); 326 327 // Returns true if there are expensive instructions in the cold value 328 // operand's (if any) dependence slice of any of the selects of the given 329 // group. 330 bool hasExpensiveColdOperand(const SelectGroup &ASI); 331 332 // For a given source instruction, collect its backwards dependence slice 333 // consisting of instructions exclusively computed for producing the operands 334 // of the source instruction. 335 void getExclBackwardsSlice(Instruction *I, std::stack<Instruction *> &Slice, 336 Instruction *SI, bool ForSinking = false); 337 338 // Returns true if the condition of the select is highly predictable. 339 bool isSelectHighlyPredictable(const SelectLike SI); 340 341 // Loop-level checks to determine if a non-predicated version (with branches) 342 // of the given loop is more profitable than its predicated version. 343 bool checkLoopHeuristics(const Loop *L, const CostInfo LoopDepth[2]); 344 345 // Computes instruction and loop-critical-path costs for both the predicated 346 // and non-predicated version of the given loop. 347 bool computeLoopCosts(const Loop *L, const SelectGroups &SIGroups, 348 DenseMap<const Instruction *, CostInfo> &InstCostMap, 349 CostInfo *LoopCost); 350 351 // Returns a set of all the select instructions in the given select groups. 352 SmallDenseMap<const Instruction *, SelectLike, 2> 353 getSImap(const SelectGroups &SIGroups); 354 355 // Returns the latency cost of a given instruction. 356 std::optional<uint64_t> computeInstCost(const Instruction *I); 357 358 // Returns the misprediction cost of a given select when converted to branch. 359 Scaled64 getMispredictionCost(const SelectLike SI, const Scaled64 CondCost); 360 361 // Returns the cost of a branch when the prediction is correct. 362 Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost, 363 const SelectLike SI); 364 365 // Returns true if the target architecture supports lowering a given select. 366 bool isSelectKindSupported(const SelectLike SI); 367 }; 368 369 class SelectOptimize : public FunctionPass { 370 SelectOptimizeImpl Impl; 371 372 public: 373 static char ID; 374 375 SelectOptimize() : FunctionPass(ID) { 376 initializeSelectOptimizePass(*PassRegistry::getPassRegistry()); 377 } 378 379 bool runOnFunction(Function &F) override { 380 return Impl.runOnFunction(F, *this); 381 } 382 383 void getAnalysisUsage(AnalysisUsage &AU) const override { 384 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 385 AU.addRequired<TargetPassConfig>(); 386 AU.addRequired<TargetTransformInfoWrapperPass>(); 387 AU.addRequired<LoopInfoWrapperPass>(); 388 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 389 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 390 } 391 }; 392 393 } // namespace 394 395 PreservedAnalyses SelectOptimizePass::run(Function &F, 396 FunctionAnalysisManager &FAM) { 397 SelectOptimizeImpl Impl(TM); 398 return Impl.run(F, FAM); 399 } 400 401 char SelectOptimize::ID = 0; 402 403 INITIALIZE_PASS_BEGIN(SelectOptimize, DEBUG_TYPE, "Optimize selects", false, 404 false) 405 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 406 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 407 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 408 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 409 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 410 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 411 INITIALIZE_PASS_END(SelectOptimize, DEBUG_TYPE, "Optimize selects", false, 412 false) 413 414 FunctionPass *llvm::createSelectOptimizePass() { return new SelectOptimize(); } 415 416 PreservedAnalyses SelectOptimizeImpl::run(Function &F, 417 FunctionAnalysisManager &FAM) { 418 TSI = TM->getSubtargetImpl(F); 419 TLI = TSI->getTargetLowering(); 420 421 // If none of the select types are supported then skip this pass. 422 // This is an optimization pass. Legality issues will be handled by 423 // instruction selection. 424 if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) && 425 !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) && 426 !TLI->isSelectSupported(TargetLowering::VectorMaskSelect)) 427 return PreservedAnalyses::all(); 428 429 TTI = &FAM.getResult<TargetIRAnalysis>(F); 430 if (!TTI->enableSelectOptimize()) 431 return PreservedAnalyses::all(); 432 433 PSI = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F) 434 .getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 435 assert(PSI && "This pass requires module analysis pass `profile-summary`!"); 436 BFI = &FAM.getResult<BlockFrequencyAnalysis>(F); 437 438 // When optimizing for size, selects are preferable over branches. 439 if (llvm::shouldOptimizeForSize(&F, PSI, BFI)) 440 return PreservedAnalyses::all(); 441 442 LI = &FAM.getResult<LoopAnalysis>(F); 443 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 444 TSchedModel.init(TSI); 445 446 bool Changed = optimizeSelects(F); 447 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all(); 448 } 449 450 bool SelectOptimizeImpl::runOnFunction(Function &F, Pass &P) { 451 TM = &P.getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); 452 TSI = TM->getSubtargetImpl(F); 453 TLI = TSI->getTargetLowering(); 454 455 // If none of the select types are supported then skip this pass. 456 // This is an optimization pass. Legality issues will be handled by 457 // instruction selection. 458 if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) && 459 !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) && 460 !TLI->isSelectSupported(TargetLowering::VectorMaskSelect)) 461 return false; 462 463 TTI = &P.getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 464 465 if (!TTI->enableSelectOptimize()) 466 return false; 467 468 LI = &P.getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 469 BFI = &P.getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(); 470 PSI = &P.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 471 ORE = &P.getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 472 TSchedModel.init(TSI); 473 474 // When optimizing for size, selects are preferable over branches. 475 if (llvm::shouldOptimizeForSize(&F, PSI, BFI)) 476 return false; 477 478 return optimizeSelects(F); 479 } 480 481 bool SelectOptimizeImpl::optimizeSelects(Function &F) { 482 // Determine for which select groups it is profitable converting to branches. 483 SelectGroups ProfSIGroups; 484 // Base heuristics apply only to non-loops and outer loops. 485 optimizeSelectsBase(F, ProfSIGroups); 486 // Separate heuristics for inner-most loops. 487 optimizeSelectsInnerLoops(F, ProfSIGroups); 488 489 // Convert to branches the select groups that were deemed 490 // profitable-to-convert. 491 convertProfitableSIGroups(ProfSIGroups); 492 493 // Code modified if at least one select group was converted. 494 return !ProfSIGroups.empty(); 495 } 496 497 void SelectOptimizeImpl::optimizeSelectsBase(Function &F, 498 SelectGroups &ProfSIGroups) { 499 // Collect all the select groups. 500 SelectGroups SIGroups; 501 for (BasicBlock &BB : F) { 502 // Base heuristics apply only to non-loops and outer loops. 503 Loop *L = LI->getLoopFor(&BB); 504 if (L && L->isInnermost()) 505 continue; 506 collectSelectGroups(BB, SIGroups); 507 } 508 509 // Determine for which select groups it is profitable converting to branches. 510 findProfitableSIGroupsBase(SIGroups, ProfSIGroups); 511 } 512 513 void SelectOptimizeImpl::optimizeSelectsInnerLoops(Function &F, 514 SelectGroups &ProfSIGroups) { 515 SmallVector<Loop *, 4> Loops(LI->begin(), LI->end()); 516 // Need to check size on each iteration as we accumulate child loops. 517 for (unsigned long i = 0; i < Loops.size(); ++i) 518 for (Loop *ChildL : Loops[i]->getSubLoops()) 519 Loops.push_back(ChildL); 520 521 for (Loop *L : Loops) { 522 if (!L->isInnermost()) 523 continue; 524 525 SelectGroups SIGroups; 526 for (BasicBlock *BB : L->getBlocks()) 527 collectSelectGroups(*BB, SIGroups); 528 529 findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups); 530 } 531 } 532 533 /// If \p isTrue is true, return the true value of \p SI, otherwise return 534 /// false value of \p SI. If the true/false value of \p SI is defined by any 535 /// select instructions in \p Selects, look through the defining select 536 /// instruction until the true/false value is not defined in \p Selects. 537 static Value * 538 getTrueOrFalseValue(SelectOptimizeImpl::SelectLike SI, bool isTrue, 539 const SmallPtrSet<const Instruction *, 2> &Selects, 540 IRBuilder<> &IB) { 541 Value *V = nullptr; 542 for (SelectInst *DefSI = dyn_cast<SelectInst>(SI.getI()); 543 DefSI != nullptr && Selects.count(DefSI); 544 DefSI = dyn_cast<SelectInst>(V)) { 545 if (DefSI->getCondition() == SI.getCondition()) 546 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); 547 else // Handle inverted SI 548 V = (!isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); 549 } 550 551 if (isa<BinaryOperator>(SI.getI())) { 552 assert(SI.getI()->getOpcode() == Instruction::Or && 553 "Only currently handling Or instructions."); 554 V = SI.getFalseValue(); 555 if (isTrue) 556 V = IB.CreateOr(V, ConstantInt::get(V->getType(), 1)); 557 } 558 559 assert(V && "Failed to get select true/false value"); 560 return V; 561 } 562 563 void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) { 564 for (SelectGroup &ASI : ProfSIGroups) { 565 // The code transformation here is a modified version of the sinking 566 // transformation in CodeGenPrepare::optimizeSelectInst with a more 567 // aggressive strategy of which instructions to sink. 568 // 569 // TODO: eliminate the redundancy of logic transforming selects to branches 570 // by removing CodeGenPrepare::optimizeSelectInst and optimizing here 571 // selects for all cases (with and without profile information). 572 573 // Transform a sequence like this: 574 // start: 575 // %cmp = cmp uge i32 %a, %b 576 // %sel = select i1 %cmp, i32 %c, i32 %d 577 // 578 // Into: 579 // start: 580 // %cmp = cmp uge i32 %a, %b 581 // %cmp.frozen = freeze %cmp 582 // br i1 %cmp.frozen, label %select.true, label %select.false 583 // select.true: 584 // br label %select.end 585 // select.false: 586 // br label %select.end 587 // select.end: 588 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] 589 // 590 // %cmp should be frozen, otherwise it may introduce undefined behavior. 591 // In addition, we may sink instructions that produce %c or %d into the 592 // destination(s) of the new branch. 593 // If the true or false blocks do not contain a sunken instruction, that 594 // block and its branch may be optimized away. In that case, one side of the 595 // first branch will point directly to select.end, and the corresponding PHI 596 // predecessor block will be the start block. 597 598 // Find all the instructions that can be soundly sunk to the true/false 599 // blocks. These are instructions that are computed solely for producing the 600 // operands of the select instructions in the group and can be sunk without 601 // breaking the semantics of the LLVM IR (e.g., cannot sink instructions 602 // with side effects). 603 SmallVector<std::stack<Instruction *>, 2> TrueSlices, FalseSlices; 604 typedef std::stack<Instruction *>::size_type StackSizeType; 605 StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0; 606 for (SelectLike SI : ASI) { 607 // For each select, compute the sinkable dependence chains of the true and 608 // false operands. 609 if (auto *TI = dyn_cast_or_null<Instruction>(SI.getTrueValue())) { 610 std::stack<Instruction *> TrueSlice; 611 getExclBackwardsSlice(TI, TrueSlice, SI.getI(), true); 612 maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size()); 613 TrueSlices.push_back(TrueSlice); 614 } 615 if (auto *FI = dyn_cast_or_null<Instruction>(SI.getFalseValue())) { 616 if (isa<SelectInst>(SI.getI()) || !FI->hasOneUse()) { 617 std::stack<Instruction *> FalseSlice; 618 getExclBackwardsSlice(FI, FalseSlice, SI.getI(), true); 619 maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size()); 620 FalseSlices.push_back(FalseSlice); 621 } 622 } 623 } 624 // In the case of multiple select instructions in the same group, the order 625 // of non-dependent instructions (instructions of different dependence 626 // slices) in the true/false blocks appears to affect performance. 627 // Interleaving the slices seems to experimentally be the optimal approach. 628 // This interleaving scheduling allows for more ILP (with a natural downside 629 // of increasing a bit register pressure) compared to a simple ordering of 630 // one whole chain after another. One would expect that this ordering would 631 // not matter since the scheduling in the backend of the compiler would 632 // take care of it, but apparently the scheduler fails to deliver optimal 633 // ILP with a naive ordering here. 634 SmallVector<Instruction *, 2> TrueSlicesInterleaved, FalseSlicesInterleaved; 635 for (StackSizeType IS = 0; IS < maxTrueSliceLen; ++IS) { 636 for (auto &S : TrueSlices) { 637 if (!S.empty()) { 638 TrueSlicesInterleaved.push_back(S.top()); 639 S.pop(); 640 } 641 } 642 } 643 for (StackSizeType IS = 0; IS < maxFalseSliceLen; ++IS) { 644 for (auto &S : FalseSlices) { 645 if (!S.empty()) { 646 FalseSlicesInterleaved.push_back(S.top()); 647 S.pop(); 648 } 649 } 650 } 651 652 // We split the block containing the select(s) into two blocks. 653 SelectLike SI = ASI.front(); 654 SelectLike LastSI = ASI.back(); 655 BasicBlock *StartBlock = SI.getI()->getParent(); 656 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI.getI())); 657 // With RemoveDIs turned off, SplitPt can be a dbg.* intrinsic. With 658 // RemoveDIs turned on, SplitPt would instead point to the next 659 // instruction. To match existing dbg.* intrinsic behaviour with RemoveDIs, 660 // tell splitBasicBlock that we want to include any DbgVariableRecords 661 // attached to SplitPt in the splice. 662 SplitPt.setHeadBit(true); 663 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); 664 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock)); 665 // Delete the unconditional branch that was just created by the split. 666 StartBlock->getTerminator()->eraseFromParent(); 667 668 // Move any debug/pseudo instructions and not's that were in-between the 669 // select group to the newly-created end block. 670 SmallVector<Instruction *, 2> SinkInstrs; 671 auto DIt = SI.getI()->getIterator(); 672 while (&*DIt != LastSI.getI()) { 673 if (DIt->isDebugOrPseudoInst()) 674 SinkInstrs.push_back(&*DIt); 675 if (match(&*DIt, m_Not(m_Specific(SI.getCondition())))) 676 SinkInstrs.push_back(&*DIt); 677 DIt++; 678 } 679 for (auto *DI : SinkInstrs) 680 DI->moveBeforePreserving(&*EndBlock->getFirstInsertionPt()); 681 682 // Duplicate implementation for DbgRecords, the non-instruction debug-info 683 // format. Helper lambda for moving DbgRecords to the end block. 684 auto TransferDbgRecords = [&](Instruction &I) { 685 for (auto &DbgRecord : 686 llvm::make_early_inc_range(I.getDbgRecordRange())) { 687 DbgRecord.removeFromParent(); 688 EndBlock->insertDbgRecordBefore(&DbgRecord, 689 EndBlock->getFirstInsertionPt()); 690 } 691 }; 692 693 // Iterate over all instructions in between SI and LastSI, not including 694 // SI itself. These are all the variable assignments that happen "in the 695 // middle" of the select group. 696 auto R = make_range(std::next(SI.getI()->getIterator()), 697 std::next(LastSI.getI()->getIterator())); 698 llvm::for_each(R, TransferDbgRecords); 699 700 // These are the new basic blocks for the conditional branch. 701 // At least one will become an actual new basic block. 702 BasicBlock *TrueBlock = nullptr, *FalseBlock = nullptr; 703 BranchInst *TrueBranch = nullptr, *FalseBranch = nullptr; 704 if (!TrueSlicesInterleaved.empty()) { 705 TrueBlock = BasicBlock::Create(EndBlock->getContext(), "select.true.sink", 706 EndBlock->getParent(), EndBlock); 707 TrueBranch = BranchInst::Create(EndBlock, TrueBlock); 708 TrueBranch->setDebugLoc(LastSI.getI()->getDebugLoc()); 709 for (Instruction *TrueInst : TrueSlicesInterleaved) 710 TrueInst->moveBefore(TrueBranch); 711 } 712 if (!FalseSlicesInterleaved.empty()) { 713 FalseBlock = 714 BasicBlock::Create(EndBlock->getContext(), "select.false.sink", 715 EndBlock->getParent(), EndBlock); 716 FalseBranch = BranchInst::Create(EndBlock, FalseBlock); 717 FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc()); 718 for (Instruction *FalseInst : FalseSlicesInterleaved) 719 FalseInst->moveBefore(FalseBranch); 720 } 721 // If there was nothing to sink, then arbitrarily choose the 'false' side 722 // for a new input value to the PHI. 723 if (TrueBlock == FalseBlock) { 724 assert(TrueBlock == nullptr && 725 "Unexpected basic block transform while optimizing select"); 726 727 FalseBlock = BasicBlock::Create(StartBlock->getContext(), "select.false", 728 EndBlock->getParent(), EndBlock); 729 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); 730 FalseBranch->setDebugLoc(SI.getI()->getDebugLoc()); 731 } 732 733 // Insert the real conditional branch based on the original condition. 734 // If we did not create a new block for one of the 'true' or 'false' paths 735 // of the condition, it means that side of the branch goes to the end block 736 // directly and the path originates from the start block from the point of 737 // view of the new PHI. 738 BasicBlock *TT, *FT; 739 if (TrueBlock == nullptr) { 740 TT = EndBlock; 741 FT = FalseBlock; 742 TrueBlock = StartBlock; 743 } else if (FalseBlock == nullptr) { 744 TT = TrueBlock; 745 FT = EndBlock; 746 FalseBlock = StartBlock; 747 } else { 748 TT = TrueBlock; 749 FT = FalseBlock; 750 } 751 IRBuilder<> IB(SI.getI()); 752 auto *CondFr = IB.CreateFreeze(SI.getCondition(), 753 SI.getCondition()->getName() + ".frozen"); 754 755 SmallPtrSet<const Instruction *, 2> INS; 756 for (auto SI : ASI) 757 INS.insert(SI.getI()); 758 759 // Use reverse iterator because later select may use the value of the 760 // earlier select, and we need to propagate value through earlier select 761 // to get the PHI operand. 762 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { 763 SelectLike SI = *It; 764 // The select itself is replaced with a PHI Node. 765 PHINode *PN = PHINode::Create(SI.getType(), 2, ""); 766 PN->insertBefore(EndBlock->begin()); 767 PN->takeName(SI.getI()); 768 PN->addIncoming(getTrueOrFalseValue(SI, true, INS, IB), TrueBlock); 769 PN->addIncoming(getTrueOrFalseValue(SI, false, INS, IB), FalseBlock); 770 PN->setDebugLoc(SI.getI()->getDebugLoc()); 771 SI.getI()->replaceAllUsesWith(PN); 772 INS.erase(SI.getI()); 773 ++NumSelectsConverted; 774 } 775 IB.CreateCondBr(CondFr, TT, FT, SI.getI()); 776 777 // Remove the old select instructions, now that they are not longer used. 778 for (auto SI : ASI) 779 SI.getI()->eraseFromParent(); 780 } 781 } 782 783 void SelectOptimizeImpl::collectSelectGroups(BasicBlock &BB, 784 SelectGroups &SIGroups) { 785 BasicBlock::iterator BBIt = BB.begin(); 786 while (BBIt != BB.end()) { 787 Instruction *I = &*BBIt++; 788 if (SelectLike SI = SelectLike::match(I)) { 789 if (!TTI->shouldTreatInstructionLikeSelect(I)) 790 continue; 791 792 SelectGroup SIGroup; 793 SIGroup.push_back(SI); 794 while (BBIt != BB.end()) { 795 Instruction *NI = &*BBIt; 796 // Debug/pseudo instructions should be skipped and not prevent the 797 // formation of a select group. 798 if (NI->isDebugOrPseudoInst()) { 799 ++BBIt; 800 continue; 801 } 802 803 // Skip not(select(..)), if the not is part of the same select group 804 if (match(NI, m_Not(m_Specific(SI.getCondition())))) { 805 ++BBIt; 806 continue; 807 } 808 809 // We only allow selects in the same group, not other select-like 810 // instructions. 811 if (!isa<SelectInst>(NI)) 812 break; 813 814 SelectLike NSI = SelectLike::match(NI); 815 if (NSI && SI.getCondition() == NSI.getCondition()) { 816 SIGroup.push_back(NSI); 817 } else if (NSI && match(NSI.getCondition(), 818 m_Not(m_Specific(SI.getCondition())))) { 819 NSI.setInverted(); 820 SIGroup.push_back(NSI); 821 } else 822 break; 823 ++BBIt; 824 } 825 826 // If the select type is not supported, no point optimizing it. 827 // Instruction selection will take care of it. 828 if (!isSelectKindSupported(SI)) 829 continue; 830 831 LLVM_DEBUG({ 832 dbgs() << "New Select group with\n"; 833 for (auto SI : SIGroup) 834 dbgs() << " " << *SI.getI() << "\n"; 835 }); 836 837 SIGroups.push_back(SIGroup); 838 } 839 } 840 } 841 842 void SelectOptimizeImpl::findProfitableSIGroupsBase( 843 SelectGroups &SIGroups, SelectGroups &ProfSIGroups) { 844 for (SelectGroup &ASI : SIGroups) { 845 ++NumSelectOptAnalyzed; 846 if (isConvertToBranchProfitableBase(ASI)) 847 ProfSIGroups.push_back(ASI); 848 } 849 } 850 851 static void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE, 852 DiagnosticInfoOptimizationBase &Rem) { 853 LLVM_DEBUG(dbgs() << Rem.getMsg() << "\n"); 854 ORE->emit(Rem); 855 } 856 857 void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops( 858 const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) { 859 NumSelectOptAnalyzed += SIGroups.size(); 860 // For each select group in an inner-most loop, 861 // a branch is more preferable than a select/conditional-move if: 862 // i) conversion to branches for all the select groups of the loop satisfies 863 // loop-level heuristics including reducing the loop's critical path by 864 // some threshold (see SelectOptimizeImpl::checkLoopHeuristics); and 865 // ii) the total cost of the select group is cheaper with a branch compared 866 // to its predicated version. The cost is in terms of latency and the cost 867 // of a select group is the cost of its most expensive select instruction 868 // (assuming infinite resources and thus fully leveraging available ILP). 869 870 DenseMap<const Instruction *, CostInfo> InstCostMap; 871 CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()}, 872 {Scaled64::getZero(), Scaled64::getZero()}}; 873 if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) || 874 !checkLoopHeuristics(L, LoopCost)) { 875 return; 876 } 877 878 for (SelectGroup &ASI : SIGroups) { 879 // Assuming infinite resources, the cost of a group of instructions is the 880 // cost of the most expensive instruction of the group. 881 Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero(); 882 for (SelectLike SI : ASI) { 883 SelectCost = std::max(SelectCost, InstCostMap[SI.getI()].PredCost); 884 BranchCost = std::max(BranchCost, InstCostMap[SI.getI()].NonPredCost); 885 } 886 if (BranchCost < SelectCost) { 887 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", ASI.front().getI()); 888 OR << "Profitable to convert to branch (loop analysis). BranchCost=" 889 << BranchCost.toString() << ", SelectCost=" << SelectCost.toString() 890 << ". "; 891 EmitAndPrintRemark(ORE, OR); 892 ++NumSelectConvertedLoop; 893 ProfSIGroups.push_back(ASI); 894 } else { 895 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", 896 ASI.front().getI()); 897 ORmiss << "Select is more profitable (loop analysis). BranchCost=" 898 << BranchCost.toString() 899 << ", SelectCost=" << SelectCost.toString() << ". "; 900 EmitAndPrintRemark(ORE, ORmiss); 901 } 902 } 903 } 904 905 bool SelectOptimizeImpl::isConvertToBranchProfitableBase( 906 const SelectGroup &ASI) { 907 SelectLike SI = ASI.front(); 908 LLVM_DEBUG(dbgs() << "Analyzing select group containing " << *SI.getI() 909 << "\n"); 910 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", SI.getI()); 911 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", SI.getI()); 912 913 // Skip cold basic blocks. Better to optimize for size for cold blocks. 914 if (PSI->isColdBlock(SI.getI()->getParent(), BFI)) { 915 ++NumSelectColdBB; 916 ORmiss << "Not converted to branch because of cold basic block. "; 917 EmitAndPrintRemark(ORE, ORmiss); 918 return false; 919 } 920 921 // If unpredictable, branch form is less profitable. 922 if (SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) { 923 ++NumSelectUnPred; 924 ORmiss << "Not converted to branch because of unpredictable branch. "; 925 EmitAndPrintRemark(ORE, ORmiss); 926 return false; 927 } 928 929 // If highly predictable, branch form is more profitable, unless a 930 // predictable select is inexpensive in the target architecture. 931 if (isSelectHighlyPredictable(SI) && TLI->isPredictableSelectExpensive()) { 932 ++NumSelectConvertedHighPred; 933 OR << "Converted to branch because of highly predictable branch. "; 934 EmitAndPrintRemark(ORE, OR); 935 return true; 936 } 937 938 // Look for expensive instructions in the cold operand's (if any) dependence 939 // slice of any of the selects in the group. 940 if (hasExpensiveColdOperand(ASI)) { 941 ++NumSelectConvertedExpColdOperand; 942 OR << "Converted to branch because of expensive cold operand."; 943 EmitAndPrintRemark(ORE, OR); 944 return true; 945 } 946 947 ORmiss << "Not profitable to convert to branch (base heuristic)."; 948 EmitAndPrintRemark(ORE, ORmiss); 949 return false; 950 } 951 952 static InstructionCost divideNearest(InstructionCost Numerator, 953 uint64_t Denominator) { 954 return (Numerator + (Denominator / 2)) / Denominator; 955 } 956 957 static bool extractBranchWeights(const SelectOptimizeImpl::SelectLike SI, 958 uint64_t &TrueVal, uint64_t &FalseVal) { 959 if (isa<SelectInst>(SI.getI())) 960 return extractBranchWeights(*SI.getI(), TrueVal, FalseVal); 961 return false; 962 } 963 964 bool SelectOptimizeImpl::hasExpensiveColdOperand(const SelectGroup &ASI) { 965 bool ColdOperand = false; 966 uint64_t TrueWeight, FalseWeight, TotalWeight; 967 if (extractBranchWeights(ASI.front(), TrueWeight, FalseWeight)) { 968 uint64_t MinWeight = std::min(TrueWeight, FalseWeight); 969 TotalWeight = TrueWeight + FalseWeight; 970 // Is there a path with frequency <ColdOperandThreshold% (default:20%) ? 971 ColdOperand = TotalWeight * ColdOperandThreshold > 100 * MinWeight; 972 } else if (PSI->hasProfileSummary()) { 973 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", 974 ASI.front().getI()); 975 ORmiss << "Profile data available but missing branch-weights metadata for " 976 "select instruction. "; 977 EmitAndPrintRemark(ORE, ORmiss); 978 } 979 if (!ColdOperand) 980 return false; 981 // Check if the cold path's dependence slice is expensive for any of the 982 // selects of the group. 983 for (SelectLike SI : ASI) { 984 Instruction *ColdI = nullptr; 985 uint64_t HotWeight; 986 if (TrueWeight < FalseWeight) { 987 ColdI = dyn_cast_or_null<Instruction>(SI.getTrueValue()); 988 HotWeight = FalseWeight; 989 } else { 990 ColdI = dyn_cast_or_null<Instruction>(SI.getFalseValue()); 991 HotWeight = TrueWeight; 992 } 993 if (ColdI) { 994 std::stack<Instruction *> ColdSlice; 995 getExclBackwardsSlice(ColdI, ColdSlice, SI.getI()); 996 InstructionCost SliceCost = 0; 997 while (!ColdSlice.empty()) { 998 SliceCost += TTI->getInstructionCost(ColdSlice.top(), 999 TargetTransformInfo::TCK_Latency); 1000 ColdSlice.pop(); 1001 } 1002 // The colder the cold value operand of the select is the more expensive 1003 // the cmov becomes for computing the cold value operand every time. Thus, 1004 // the colder the cold operand is the more its cost counts. 1005 // Get nearest integer cost adjusted for coldness. 1006 InstructionCost AdjSliceCost = 1007 divideNearest(SliceCost * HotWeight, TotalWeight); 1008 if (AdjSliceCost >= 1009 ColdOperandMaxCostMultiplier * TargetTransformInfo::TCC_Expensive) 1010 return true; 1011 } 1012 } 1013 return false; 1014 } 1015 1016 // Check if it is safe to move LoadI next to the SI. 1017 // Conservatively assume it is safe only if there is no instruction 1018 // modifying memory in-between the load and the select instruction. 1019 static bool isSafeToSinkLoad(Instruction *LoadI, Instruction *SI) { 1020 // Assume loads from different basic blocks are unsafe to move. 1021 if (LoadI->getParent() != SI->getParent()) 1022 return false; 1023 auto It = LoadI->getIterator(); 1024 while (&*It != SI) { 1025 if (It->mayWriteToMemory()) 1026 return false; 1027 It++; 1028 } 1029 return true; 1030 } 1031 1032 // For a given source instruction, collect its backwards dependence slice 1033 // consisting of instructions exclusively computed for the purpose of producing 1034 // the operands of the source instruction. As an approximation 1035 // (sufficiently-accurate in practice), we populate this set with the 1036 // instructions of the backwards dependence slice that only have one-use and 1037 // form an one-use chain that leads to the source instruction. 1038 void SelectOptimizeImpl::getExclBackwardsSlice(Instruction *I, 1039 std::stack<Instruction *> &Slice, 1040 Instruction *SI, 1041 bool ForSinking) { 1042 SmallPtrSet<Instruction *, 2> Visited; 1043 std::queue<Instruction *> Worklist; 1044 Worklist.push(I); 1045 while (!Worklist.empty()) { 1046 Instruction *II = Worklist.front(); 1047 Worklist.pop(); 1048 1049 // Avoid cycles. 1050 if (!Visited.insert(II).second) 1051 continue; 1052 1053 if (!II->hasOneUse()) 1054 continue; 1055 1056 // Cannot soundly sink instructions with side-effects. 1057 // Terminator or phi instructions cannot be sunk. 1058 // Avoid sinking other select instructions (should be handled separetely). 1059 if (ForSinking && (II->isTerminator() || II->mayHaveSideEffects() || 1060 isa<SelectInst>(II) || isa<PHINode>(II))) 1061 continue; 1062 1063 // Avoid sinking loads in order not to skip state-modifying instructions, 1064 // that may alias with the loaded address. 1065 // Only allow sinking of loads within the same basic block that are 1066 // conservatively proven to be safe. 1067 if (ForSinking && II->mayReadFromMemory() && !isSafeToSinkLoad(II, SI)) 1068 continue; 1069 1070 // Avoid considering instructions with less frequency than the source 1071 // instruction (i.e., avoid colder code regions of the dependence slice). 1072 if (BFI->getBlockFreq(II->getParent()) < BFI->getBlockFreq(I->getParent())) 1073 continue; 1074 1075 // Eligible one-use instruction added to the dependence slice. 1076 Slice.push(II); 1077 1078 // Explore all the operands of the current instruction to expand the slice. 1079 for (Value *Op : II->operand_values()) 1080 if (auto *OpI = dyn_cast<Instruction>(Op)) 1081 Worklist.push(OpI); 1082 } 1083 } 1084 1085 bool SelectOptimizeImpl::isSelectHighlyPredictable(const SelectLike SI) { 1086 uint64_t TrueWeight, FalseWeight; 1087 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) { 1088 uint64_t Max = std::max(TrueWeight, FalseWeight); 1089 uint64_t Sum = TrueWeight + FalseWeight; 1090 if (Sum != 0) { 1091 auto Probability = BranchProbability::getBranchProbability(Max, Sum); 1092 if (Probability > TTI->getPredictableBranchThreshold()) 1093 return true; 1094 } 1095 } 1096 return false; 1097 } 1098 1099 bool SelectOptimizeImpl::checkLoopHeuristics(const Loop *L, 1100 const CostInfo LoopCost[2]) { 1101 // Loop-level checks to determine if a non-predicated version (with branches) 1102 // of the loop is more profitable than its predicated version. 1103 1104 if (DisableLoopLevelHeuristics) 1105 return true; 1106 1107 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", 1108 L->getHeader()->getFirstNonPHI()); 1109 1110 if (LoopCost[0].NonPredCost > LoopCost[0].PredCost || 1111 LoopCost[1].NonPredCost >= LoopCost[1].PredCost) { 1112 ORmissL << "No select conversion in the loop due to no reduction of loop's " 1113 "critical path. "; 1114 EmitAndPrintRemark(ORE, ORmissL); 1115 return false; 1116 } 1117 1118 Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost, 1119 LoopCost[1].PredCost - LoopCost[1].NonPredCost}; 1120 1121 // Profitably converting to branches need to reduce the loop's critical path 1122 // by at least some threshold (absolute gain of GainCycleThreshold cycles and 1123 // relative gain of 12.5%). 1124 if (Gain[1] < Scaled64::get(GainCycleThreshold) || 1125 Gain[1] * Scaled64::get(GainRelativeThreshold) < LoopCost[1].PredCost) { 1126 Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost; 1127 ORmissL << "No select conversion in the loop due to small reduction of " 1128 "loop's critical path. Gain=" 1129 << Gain[1].toString() 1130 << ", RelativeGain=" << RelativeGain.toString() << "%. "; 1131 EmitAndPrintRemark(ORE, ORmissL); 1132 return false; 1133 } 1134 1135 // If the loop's critical path involves loop-carried dependences, the gradient 1136 // of the gain needs to be at least GainGradientThreshold% (defaults to 25%). 1137 // This check ensures that the latency reduction for the loop's critical path 1138 // keeps decreasing with sufficient rate beyond the two analyzed loop 1139 // iterations. 1140 if (Gain[1] > Gain[0]) { 1141 Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) / 1142 (LoopCost[1].PredCost - LoopCost[0].PredCost); 1143 if (GradientGain < Scaled64::get(GainGradientThreshold)) { 1144 ORmissL << "No select conversion in the loop due to small gradient gain. " 1145 "GradientGain=" 1146 << GradientGain.toString() << "%. "; 1147 EmitAndPrintRemark(ORE, ORmissL); 1148 return false; 1149 } 1150 } 1151 // If the gain decreases it is not profitable to convert. 1152 else if (Gain[1] < Gain[0]) { 1153 ORmissL 1154 << "No select conversion in the loop due to negative gradient gain. "; 1155 EmitAndPrintRemark(ORE, ORmissL); 1156 return false; 1157 } 1158 1159 // Non-predicated version of the loop is more profitable than its 1160 // predicated version. 1161 return true; 1162 } 1163 1164 // Computes instruction and loop-critical-path costs for both the predicated 1165 // and non-predicated version of the given loop. 1166 // Returns false if unable to compute these costs due to invalid cost of loop 1167 // instruction(s). 1168 bool SelectOptimizeImpl::computeLoopCosts( 1169 const Loop *L, const SelectGroups &SIGroups, 1170 DenseMap<const Instruction *, CostInfo> &InstCostMap, CostInfo *LoopCost) { 1171 LLVM_DEBUG(dbgs() << "Calculating Latency / IPredCost / INonPredCost of loop " 1172 << L->getHeader()->getName() << "\n"); 1173 const auto &SImap = getSImap(SIGroups); 1174 // Compute instruction and loop-critical-path costs across two iterations for 1175 // both predicated and non-predicated version. 1176 const unsigned Iterations = 2; 1177 for (unsigned Iter = 0; Iter < Iterations; ++Iter) { 1178 // Cost of the loop's critical path. 1179 CostInfo &MaxCost = LoopCost[Iter]; 1180 for (BasicBlock *BB : L->getBlocks()) { 1181 for (const Instruction &I : *BB) { 1182 if (I.isDebugOrPseudoInst()) 1183 continue; 1184 // Compute the predicated and non-predicated cost of the instruction. 1185 Scaled64 IPredCost = Scaled64::getZero(), 1186 INonPredCost = Scaled64::getZero(); 1187 1188 // Assume infinite resources that allow to fully exploit the available 1189 // instruction-level parallelism. 1190 // InstCost = InstLatency + max(Op1Cost, Op2Cost, … OpNCost) 1191 for (const Use &U : I.operands()) { 1192 auto UI = dyn_cast<Instruction>(U.get()); 1193 if (!UI) 1194 continue; 1195 if (InstCostMap.count(UI)) { 1196 IPredCost = std::max(IPredCost, InstCostMap[UI].PredCost); 1197 INonPredCost = std::max(INonPredCost, InstCostMap[UI].NonPredCost); 1198 } 1199 } 1200 auto ILatency = computeInstCost(&I); 1201 if (!ILatency) { 1202 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", &I); 1203 ORmissL << "Invalid instruction cost preventing analysis and " 1204 "optimization of the inner-most loop containing this " 1205 "instruction. "; 1206 EmitAndPrintRemark(ORE, ORmissL); 1207 return false; 1208 } 1209 IPredCost += Scaled64::get(*ILatency); 1210 INonPredCost += Scaled64::get(*ILatency); 1211 1212 // For a select that can be converted to branch, 1213 // compute its cost as a branch (non-predicated cost). 1214 // 1215 // BranchCost = PredictedPathCost + MispredictCost 1216 // PredictedPathCost = TrueOpCost * TrueProb + FalseOpCost * FalseProb 1217 // MispredictCost = max(MispredictPenalty, CondCost) * MispredictRate 1218 if (SImap.contains(&I)) { 1219 auto SI = SImap.at(&I); 1220 Scaled64 TrueOpCost = SI.getTrueOpCost(InstCostMap, TTI); 1221 Scaled64 FalseOpCost = SI.getFalseOpCost(InstCostMap, TTI); 1222 Scaled64 PredictedPathCost = 1223 getPredictedPathCost(TrueOpCost, FalseOpCost, SI); 1224 1225 Scaled64 CondCost = Scaled64::getZero(); 1226 if (auto *CI = dyn_cast<Instruction>(SI.getCondition())) 1227 if (InstCostMap.count(CI)) 1228 CondCost = InstCostMap[CI].NonPredCost; 1229 Scaled64 MispredictCost = getMispredictionCost(SI, CondCost); 1230 1231 INonPredCost = PredictedPathCost + MispredictCost; 1232 } 1233 LLVM_DEBUG(dbgs() << " " << ILatency << "/" << IPredCost << "/" 1234 << INonPredCost << " for " << I << "\n"); 1235 1236 InstCostMap[&I] = {IPredCost, INonPredCost}; 1237 MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost); 1238 MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost); 1239 } 1240 } 1241 LLVM_DEBUG(dbgs() << "Iteration " << Iter + 1 1242 << " MaxCost = " << MaxCost.PredCost << " " 1243 << MaxCost.NonPredCost << "\n"); 1244 } 1245 return true; 1246 } 1247 1248 SmallDenseMap<const Instruction *, SelectOptimizeImpl::SelectLike, 2> 1249 SelectOptimizeImpl::getSImap(const SelectGroups &SIGroups) { 1250 SmallDenseMap<const Instruction *, SelectLike, 2> SImap; 1251 for (const SelectGroup &ASI : SIGroups) 1252 for (SelectLike SI : ASI) 1253 SImap.try_emplace(SI.getI(), SI); 1254 return SImap; 1255 } 1256 1257 std::optional<uint64_t> 1258 SelectOptimizeImpl::computeInstCost(const Instruction *I) { 1259 InstructionCost ICost = 1260 TTI->getInstructionCost(I, TargetTransformInfo::TCK_Latency); 1261 if (auto OC = ICost.getValue()) 1262 return std::optional<uint64_t>(*OC); 1263 return std::nullopt; 1264 } 1265 1266 ScaledNumber<uint64_t> 1267 SelectOptimizeImpl::getMispredictionCost(const SelectLike SI, 1268 const Scaled64 CondCost) { 1269 uint64_t MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty; 1270 1271 // Account for the default misprediction rate when using a branch 1272 // (conservatively set to 25% by default). 1273 uint64_t MispredictRate = MispredictDefaultRate; 1274 // If the select condition is obviously predictable, then the misprediction 1275 // rate is zero. 1276 if (isSelectHighlyPredictable(SI)) 1277 MispredictRate = 0; 1278 1279 // CondCost is included to account for cases where the computation of the 1280 // condition is part of a long dependence chain (potentially loop-carried) 1281 // that would delay detection of a misprediction and increase its cost. 1282 Scaled64 MispredictCost = 1283 std::max(Scaled64::get(MispredictPenalty), CondCost) * 1284 Scaled64::get(MispredictRate); 1285 MispredictCost /= Scaled64::get(100); 1286 1287 return MispredictCost; 1288 } 1289 1290 // Returns the cost of a branch when the prediction is correct. 1291 // TrueCost * TrueProbability + FalseCost * FalseProbability. 1292 ScaledNumber<uint64_t> 1293 SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost, 1294 const SelectLike SI) { 1295 Scaled64 PredPathCost; 1296 uint64_t TrueWeight, FalseWeight; 1297 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) { 1298 uint64_t SumWeight = TrueWeight + FalseWeight; 1299 if (SumWeight != 0) { 1300 PredPathCost = TrueCost * Scaled64::get(TrueWeight) + 1301 FalseCost * Scaled64::get(FalseWeight); 1302 PredPathCost /= Scaled64::get(SumWeight); 1303 return PredPathCost; 1304 } 1305 } 1306 // Without branch weight metadata, we assume 75% for the one path and 25% for 1307 // the other, and pick the result with the biggest cost. 1308 PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost, 1309 FalseCost * Scaled64::get(3) + TrueCost); 1310 PredPathCost /= Scaled64::get(4); 1311 return PredPathCost; 1312 } 1313 1314 bool SelectOptimizeImpl::isSelectKindSupported(const SelectLike SI) { 1315 bool VectorCond = !SI.getCondition()->getType()->isIntegerTy(1); 1316 if (VectorCond) 1317 return false; 1318 TargetLowering::SelectSupportKind SelectKind; 1319 if (SI.getType()->isVectorTy()) 1320 SelectKind = TargetLowering::ScalarCondVectorVal; 1321 else 1322 SelectKind = TargetLowering::ScalarValSelect; 1323 return TLI->isSelectSupported(SelectKind); 1324 } 1325