LLVM 24.0.0git
SimplifyCFG.cpp
Go to the documentation of this file.
1//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
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// Peephole optimize the CFG.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
31#include "llvm/Analysis/Loads.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/NoFolder.h"
59#include "llvm/IR/Operator.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
66#include "llvm/IR/ValueHandle.h"
70#include "llvm/Support/Debug.h"
80#include <algorithm>
81#include <cassert>
82#include <climits>
83#include <cstddef>
84#include <cstdint>
85#include <iterator>
86#include <map>
87#include <optional>
88#include <set>
89#include <tuple>
90#include <utility>
91#include <vector>
92
93using namespace llvm;
94using namespace PatternMatch;
95
96#define DEBUG_TYPE "simplifycfg"
97
98namespace llvm {
99
101 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
102
103 cl::desc(
104 "Temporary development switch used to gradually uplift SimplifyCFG "
105 "into preserving DomTree,"));
106
107// Chosen as 2 so as to be cheap, but still to have enough power to fold
108// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
109// To catch this, we need to fold a compare and a select, hence '2' being the
110// minimum reasonable default.
112 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
113 cl::desc(
114 "Control the amount of phi node folding to perform (default = 2)"));
115
117 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
118 cl::desc("Control the maximal total instruction cost that we are willing "
119 "to speculatively execute to fold a 2-entry PHI node into a "
120 "select (default = 4)"));
121
122static cl::opt<bool>
123 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
124 cl::desc("Hoist common instructions up to the parent block"));
125
127 "simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true),
128 cl::desc("Hoist loads if the target supports conditional faulting"));
129
131 "simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true),
132 cl::desc("Hoist stores if the target supports conditional faulting"));
133
135 "hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6),
136 cl::desc("Control the maximal conditional load/store that we are willing "
137 "to speculatively execute to eliminate conditional branch "
138 "(default = 6)"));
139
141 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
142 cl::init(20),
143 cl::desc("Allow reordering across at most this many "
144 "instructions when hoisting"));
145
146static cl::opt<bool>
147 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
148 cl::desc("Sink common instructions down to the end block"));
149
151 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
152 cl::desc("Hoist conditional stores if an unconditional store precedes"));
153
155 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
156 cl::desc("Hoist conditional stores even if an unconditional store does not "
157 "precede - hoist multiple conditional stores into a single "
158 "predicated store"));
159
161 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
162 cl::desc("When merging conditional stores, do so even if the resultant "
163 "basic blocks are unlikely to be if-converted as a result"));
164
166 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
167 cl::desc("Allow exactly one expensive instruction to be speculatively "
168 "executed"));
169
171 "max-speculation-depth", cl::Hidden, cl::init(10),
172 cl::desc("Limit maximum recursion depth when calculating costs of "
173 "speculatively executed instructions"));
174
175static cl::opt<int>
176 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
177 cl::init(10),
178 cl::desc("Max size of a block which is still considered "
179 "small enough to thread through"));
180
181// Two is chosen to allow one negation and a logical combine.
183 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
184 cl::init(2),
185 cl::desc("Maximum cost of combining conditions when "
186 "folding branches"));
187
189 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
190 cl::init(2),
191 cl::desc("Multiplier to apply to threshold when determining whether or not "
192 "to fold branch to common destination when vector operations are "
193 "present"));
194
196 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
197 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
198
200 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
201 cl::desc("Limit cases to analyze when converting a switch to select"));
202
204 "simplifycfg-max-loop-header-threading-search", cl::Hidden, cl::init(1024),
205 cl::desc("Limit number of blocks searched to prove that threading through "
206 "a loop header keeps the loop canonical"));
207
209 "max-jump-threading-live-blocks", cl::Hidden, cl::init(24),
210 cl::desc("Limit number of blocks a define in a threaded block is allowed "
211 "to be live in"));
212
214
215} // end namespace llvm
216
217STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
218STATISTIC(NumLinearMaps,
219 "Number of switch instructions turned into linear mapping");
220STATISTIC(NumLookupTables,
221 "Number of switch instructions turned into lookup tables");
223 NumLookupTablesHoles,
224 "Number of switch instructions turned into lookup tables (holes checked)");
225STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
226STATISTIC(NumFoldValueComparisonIntoPredecessors,
227 "Number of value comparisons folded into predecessor basic blocks");
228STATISTIC(NumFoldBranchToCommonDest,
229 "Number of branches folded into predecessor basic block");
231 NumHoistCommonCode,
232 "Number of common instruction 'blocks' hoisted up to the begin block");
233STATISTIC(NumHoistCommonInstrs,
234 "Number of common instructions hoisted up to the begin block");
235STATISTIC(NumSinkCommonCode,
236 "Number of common instruction 'blocks' sunk down to the end block");
237STATISTIC(NumSinkCommonInstrs,
238 "Number of common instructions sunk down to the end block");
239STATISTIC(NumSpeculations, "Number of speculative executed instructions");
240STATISTIC(NumInvokes,
241 "Number of invokes with empty resume blocks simplified into calls");
242STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
243STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
244
245namespace {
246
247// The first field contains the value that the switch produces when a certain
248// case group is selected, and the second field is a vector containing the
249// cases composing the case group.
250using SwitchCaseResultVectorTy =
252
253// The first field contains the phi node that generates a result of the switch
254// and the second field contains the value generated for a certain case in the
255// switch for that PHI.
256using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
257
258/// ValueEqualityComparisonCase - Represents a case of a switch.
259struct ValueEqualityComparisonCase {
261 BasicBlock *Dest;
262
263 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
264 : Value(Value), Dest(Dest) {}
265
266 bool operator<(ValueEqualityComparisonCase RHS) const {
267 // Comparing pointers is ok as we only rely on the order for uniquing.
268 return Value < RHS.Value;
269 }
270
271 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
272};
273
274class SimplifyCFGOpt {
275 const TargetTransformInfo &TTI;
276 DomTreeUpdater *DTU;
277 const DataLayout &DL;
278 ArrayRef<WeakVH> LoopHeaders;
279 const SimplifyCFGOptions &Options;
280 bool Resimplify;
281
282 Value *isValueEqualityComparison(Instruction *TI);
283 BasicBlock *getValueEqualityComparisonCases(
284 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
285 bool simplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
286 BasicBlock *Pred,
287 IRBuilder<> &Builder);
288 bool performValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
289 Instruction *PTI,
290 IRBuilder<> &Builder);
291 bool foldValueComparisonIntoPredecessors(Instruction *TI,
292 IRBuilder<> &Builder);
293
294 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
295 bool simplifySingleResume(ResumeInst *RI);
296 bool simplifyCommonResume(ResumeInst *RI);
297 bool simplifyCleanupReturn(CleanupReturnInst *RI);
298 bool simplifyUnreachable(UnreachableInst *UI);
299 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
300 bool simplifyDuplicateSwitchArms(SwitchInst *SI, DomTreeUpdater *DTU);
301 bool simplifyIndirectBr(IndirectBrInst *IBI);
302 bool simplifyUncondBranch(UncondBrInst *BI, IRBuilder<> &Builder);
303 bool simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder);
304 bool foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI);
305
306 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
307 IRBuilder<> &Builder);
308 bool tryToSimplifyUncondBranchWithICmpSelectInIt(ICmpInst *ICI,
309 SelectInst *Select,
310 IRBuilder<> &Builder);
311 bool hoistCommonCodeFromSuccessors(Instruction *TI, bool AllInstsEqOnly);
312 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
313 Instruction *TI, Instruction *I1,
314 SmallVectorImpl<Instruction *> &OtherSuccTIs,
315 ArrayRef<BasicBlock *> UniqueSuccessors);
316 bool speculativelyExecuteBB(CondBrInst *BI, BasicBlock *ThenBB);
317 bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
318 BasicBlock *TrueBB, BasicBlock *FalseBB,
319 uint32_t TrueWeight, uint32_t FalseWeight);
320 bool simplifyBranchOnICmpChain(CondBrInst *BI, IRBuilder<> &Builder,
321 const DataLayout &DL);
322 bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
323 bool simplifySwitchOnSelectRemap(SwitchInst *SI, SelectInst *Select, Value *X,
324 ConstantInt *C, bool Negate);
325 bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
326 bool turnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
327 bool simplifyDuplicatePredecessors(BasicBlock *Succ, DomTreeUpdater *DTU);
328
329public:
330 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
331 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
332 const SimplifyCFGOptions &Opts)
333 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
334 assert((!DTU || !DTU->hasPostDomTree()) &&
335 "SimplifyCFG is not yet capable of maintaining validity of a "
336 "PostDomTree, so don't ask for it.");
337 }
338
339 bool simplifyOnce(BasicBlock *BB);
340 bool run(BasicBlock *BB);
341
342 // Helper to set Resimplify and return change indication.
343 bool requestResimplify() {
344 Resimplify = true;
345 return true;
346 }
347};
348
349// we synthesize a || b as select a, true, b
350// we synthesize a && b as select a, b, false
351// this function determines if SI is playing one of those roles.
352[[maybe_unused]] bool
353isSelectInRoleOfConjunctionOrDisjunction(const SelectInst *SI) {
354 return ((isa<ConstantInt>(SI->getTrueValue()) &&
355 (dyn_cast<ConstantInt>(SI->getTrueValue())->isOne())) ||
356 (isa<ConstantInt>(SI->getFalseValue()) &&
357 (dyn_cast<ConstantInt>(SI->getFalseValue())->isNullValue())));
358}
359
360} // end anonymous namespace
361
362/// Return true if all the PHI nodes in the basic block \p BB
363/// receive compatible (identical) incoming values when coming from
364/// all of the predecessor blocks that are specified in \p IncomingBlocks.
365///
366/// Note that if the values aren't exactly identical, but \p EquivalenceSet
367/// is provided, and *both* of the values are present in the set,
368/// then they are considered equal.
370 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
371 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
372 assert(IncomingBlocks.size() == 2 &&
373 "Only for a pair of incoming blocks at the time!");
374
375 // FIXME: it is okay if one of the incoming values is an `undef` value,
376 // iff the other incoming value is guaranteed to be a non-poison value.
377 // FIXME: it is okay if one of the incoming values is a `poison` value.
378 return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
379 Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
380 Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
381 if (IV0 == IV1)
382 return true;
383 if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
384 EquivalenceSet->contains(IV1))
385 return true;
386 return false;
387 });
388}
389
390/// Return true if it is safe to merge these two
391/// terminator instructions together.
392static bool
394 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
395 if (SI1 == SI2)
396 return false; // Can't merge with self!
397
398 // It is not safe to merge these two switch instructions if they have a common
399 // successor, and if that successor has a PHI node, and if *that* PHI node has
400 // conflicting incoming values from the two switch blocks.
401 BasicBlock *SI1BB = SI1->getParent();
402 BasicBlock *SI2BB = SI2->getParent();
403
405 bool Fail = false;
406 for (BasicBlock *Succ : successors(SI2BB)) {
407 if (!SI1Succs.count(Succ))
408 continue;
409 if (incomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
410 continue;
411 Fail = true;
412 if (FailBlocks)
413 FailBlocks->insert(Succ);
414 else
415 break;
416 }
417
418 return !Fail;
419}
420
421/// Update PHI nodes in Succ to indicate that there will now be entries in it
422/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
423/// will be the same as those coming in from ExistPred, an existing predecessor
424/// of Succ.
425static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
426 BasicBlock *ExistPred,
427 MemorySSAUpdater *MSSAU = nullptr) {
428 for (PHINode &PN : Succ->phis())
429 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
430 if (MSSAU)
431 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
432 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
433}
434
435/// Compute an abstract "cost" of speculating the given instruction,
436/// which is assumed to be safe to speculate. TCC_Free means cheap,
437/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
438/// expensive.
440 const TargetTransformInfo &TTI) {
441 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
442}
443
444/// If we have a merge point of an "if condition" as accepted above,
445/// return true if the specified value dominates the block. We don't handle
446/// the true generality of domination here, just a special case which works
447/// well enough for us.
448///
449/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
450/// see if V (which must be an instruction) and its recursive operands
451/// that do not dominate BB have a combined cost lower than Budget and
452/// are non-trapping. If both are true, the instruction is inserted into the
453/// set and true is returned.
454///
455/// The cost for most non-trapping instructions is defined as 1 except for
456/// Select whose cost is 2.
457///
458/// After this function returns, Cost is increased by the cost of
459/// V plus its non-dominating operands. If that cost is greater than
460/// Budget, false is returned and Cost is undefined.
462 Value *V, BasicBlock *BB, Instruction *InsertPt,
463 SmallPtrSetImpl<Instruction *> &AggressiveInsts, InstructionCost &Cost,
465 SmallPtrSetImpl<Instruction *> &ZeroCostInstructions, unsigned Depth = 0) {
466 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
467 // so limit the recursion depth.
468 // TODO: While this recursion limit does prevent pathological behavior, it
469 // would be better to track visited instructions to avoid cycles.
471 return false;
472
474 if (!I) {
475 // Non-instructions dominate all instructions and can be executed
476 // unconditionally.
477 return true;
478 }
479 BasicBlock *PBB = I->getParent();
480
481 // We don't want to allow weird loops that might have the "if condition" in
482 // the bottom of this block.
483 if (PBB == BB)
484 return false;
485
486 // If this instruction is defined in a block that contains an unconditional
487 // branch to BB, then it must be in the 'conditional' part of the "if
488 // statement". If not, it definitely dominates the region.
490 if (!BI || BI->getSuccessor() != BB)
491 return true;
492
493 // If we have seen this instruction before, don't count it again.
494 if (AggressiveInsts.count(I))
495 return true;
496
497 // Okay, it looks like the instruction IS in the "condition". Check to
498 // see if it's a cheap instruction to unconditionally compute, and if it
499 // only uses stuff defined outside of the condition. If so, hoist it out.
500 if (!isSafeToSpeculativelyExecute(I, InsertPt, AC))
501 return false;
502
503 // Overflow arithmetic instruction plus extract value are usually generated
504 // when a division is being replaced. But, in this case, the zero check may
505 // still be kept in the code. In that case it would be worth to hoist these
506 // two instruction out of the basic block. Let's treat this pattern as one
507 // single cheap instruction here!
508 WithOverflowInst *OverflowInst;
509 if (match(I, m_ExtractValue<1>(m_OneUse(m_WithOverflowInst(OverflowInst))))) {
510 ZeroCostInstructions.insert(OverflowInst);
511 Cost += 1;
512 } else if (!ZeroCostInstructions.contains(I))
513 Cost += computeSpeculationCost(I, TTI);
514
515 // Allow exactly one instruction to be speculated regardless of its cost
516 // (as long as it is safe to do so).
517 // This is intended to flatten the CFG even if the instruction is a division
518 // or other expensive operation. The speculation of an expensive instruction
519 // is expected to be undone in CodeGenPrepare if the speculation has not
520 // enabled further IR optimizations.
521 if (Cost > Budget &&
522 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
523 !Cost.isValid()))
524 return false;
525
526 // Okay, we can only really hoist these out if their operands do
527 // not take us over the cost threshold.
528 for (Use &Op : I->operands())
529 if (!dominatesMergePoint(Op, BB, InsertPt, AggressiveInsts, Cost, Budget,
530 TTI, AC, ZeroCostInstructions, Depth + 1))
531 return false;
532 // Okay, it's safe to do this! Remember this instruction.
533 AggressiveInsts.insert(I);
534 return true;
535}
536
537/// Extract ConstantInt from value, looking through IntToPtr
538/// and PointerNullValue. Return NULL if value is not a constant int.
540 // Normal constant int.
542 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
543 return CI;
544
545 // It is not safe to look through inttoptr or ptrtoint when using unstable
546 // pointer types.
547 if (DL.hasUnstableRepresentation(V->getType()))
548 return nullptr;
549
550 // This is some kind of pointer constant. Turn it into a pointer-sized
551 // ConstantInt if possible.
552 IntegerType *IntPtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
553
554 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
556 return ConstantInt::get(IntPtrTy, 0);
557
558 // IntToPtr const int, we can look through this if the semantics of
559 // inttoptr for this address space are a simple (truncating) bitcast.
561 if (CE->getOpcode() == Instruction::IntToPtr)
562 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
563 // The constant is very likely to have the right type already.
564 if (CI->getType() == IntPtrTy)
565 return CI;
566 else
567 return cast<ConstantInt>(
568 ConstantFoldIntegerCast(CI, IntPtrTy, /*isSigned=*/false, DL));
569 }
570 return nullptr;
571}
572
573namespace {
574
575/// Given a chain of or (||) or and (&&) comparison of a value against a
576/// constant, this will try to recover the information required for a switch
577/// structure.
578/// It will depth-first traverse the chain of comparison, seeking for patterns
579/// like %a == 12 or %a < 4 and combine them to produce a set of integer
580/// representing the different cases for the switch.
581/// Note that if the chain is composed of '||' it will build the set of elements
582/// that matches the comparisons (i.e. any of this value validate the chain)
583/// while for a chain of '&&' it will build the set elements that make the test
584/// fail.
585struct ConstantComparesGatherer {
586 const DataLayout &DL;
587
588 /// Value found for the switch comparison
589 Value *CompValue = nullptr;
590
591 /// Extra clause to be checked before the switch
592 Value *Extra = nullptr;
593
594 /// Set of integers to match in switch
596
597 /// Number of comparisons matched in the and/or chain
598 unsigned UsedICmps = 0;
599
600 /// If the elements in Vals matches the comparisons
601 bool IsEq = false;
602
603 // Used to check if the first matched CompValue shall be the Extra check.
604 bool IgnoreFirstMatch = false;
605 bool MultipleMatches = false;
606
607 /// Construct and compute the result for the comparison instruction Cond
608 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
609 gather(Cond);
610 if (CompValue || !MultipleMatches)
611 return;
612 Extra = nullptr;
613 Vals.clear();
614 UsedICmps = 0;
615 IgnoreFirstMatch = true;
616 gather(Cond);
617 }
618
619 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
620 ConstantComparesGatherer &
621 operator=(const ConstantComparesGatherer &) = delete;
622
623private:
624 /// Try to set the current value used for the comparison, it succeeds only if
625 /// it wasn't set before or if the new value is the same as the old one
626 bool setValueOnce(Value *NewVal) {
627 if (IgnoreFirstMatch) {
628 IgnoreFirstMatch = false;
629 return false;
630 }
631 if (CompValue && CompValue != NewVal) {
632 MultipleMatches = true;
633 return false;
634 }
635 CompValue = NewVal;
636 return true;
637 }
638
639 /// Try to match Instruction "I" as a comparison against a constant and
640 /// populates the array Vals with the set of values that match (or do not
641 /// match depending on isEQ).
642 /// Return false on failure. On success, the Value the comparison matched
643 /// against is placed in CompValue.
644 /// If CompValue is already set, the function is expected to fail if a match
645 /// is found but the value compared to is different.
646 bool matchInstruction(Instruction *I, bool isEQ) {
647 if (match(I, m_Not(m_Instruction(I))))
648 isEQ = !isEQ;
649
650 Value *Val;
651 if (match(I, m_NUWTrunc(m_Value(Val)))) {
652 // If we already have a value for the switch, it has to match!
653 if (!setValueOnce(Val))
654 return false;
655 UsedICmps++;
656 Vals.push_back(ConstantInt::get(cast<IntegerType>(Val->getType()), isEQ));
657 return true;
658 }
659 // If this is an icmp against a constant, handle this as one of the cases.
660 ICmpInst *ICI;
661 ConstantInt *C;
662 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
663 (C = getConstantInt(I->getOperand(1), DL)))) {
664 return false;
665 }
666
667 Value *RHSVal;
668 const APInt *RHSC;
669
670 // Pattern match a special case
671 // (x & ~2^z) == y --> x == y || x == y|2^z
672 // This undoes a transformation done by instcombine to fuse 2 compares.
673 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
674 // It's a little bit hard to see why the following transformations are
675 // correct. Here is a CVC3 program to verify them for 64-bit values:
676
677 /*
678 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
679 x : BITVECTOR(64);
680 y : BITVECTOR(64);
681 z : BITVECTOR(64);
682 mask : BITVECTOR(64) = BVSHL(ONE, z);
683 QUERY( (y & ~mask = y) =>
684 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
685 );
686 QUERY( (y | mask = y) =>
687 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
688 );
689 */
690
691 // Please note that each pattern must be a dual implication (<--> or
692 // iff). One directional implication can create spurious matches. If the
693 // implication is only one-way, an unsatisfiable condition on the left
694 // side can imply a satisfiable condition on the right side. Dual
695 // implication ensures that satisfiable conditions are transformed to
696 // other satisfiable conditions and unsatisfiable conditions are
697 // transformed to other unsatisfiable conditions.
698
699 // Here is a concrete example of a unsatisfiable condition on the left
700 // implying a satisfiable condition on the right:
701 //
702 // mask = (1 << z)
703 // (x & ~mask) == y --> (x == y || x == (y | mask))
704 //
705 // Substituting y = 3, z = 0 yields:
706 // (x & -2) == 3 --> (x == 3 || x == 2)
707
708 // Pattern match a special case:
709 /*
710 QUERY( (y & ~mask = y) =>
711 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
712 );
713 */
714 if (match(ICI->getOperand(0),
715 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
716 APInt Mask = ~*RHSC;
717 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
718 // If we already have a value for the switch, it has to match!
719 if (!setValueOnce(RHSVal))
720 return false;
721
722 Vals.push_back(C);
723 Vals.push_back(
724 ConstantInt::get(C->getContext(),
725 C->getValue() | Mask));
726 UsedICmps++;
727 return true;
728 }
729 }
730
731 // Pattern match a special case:
732 /*
733 QUERY( (y | mask = y) =>
734 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
735 );
736 */
737 if (match(ICI->getOperand(0),
738 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
739 APInt Mask = *RHSC;
740 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
741 // If we already have a value for the switch, it has to match!
742 if (!setValueOnce(RHSVal))
743 return false;
744
745 Vals.push_back(C);
746 Vals.push_back(ConstantInt::get(C->getContext(),
747 C->getValue() & ~Mask));
748 UsedICmps++;
749 return true;
750 }
751 }
752
753 // If we already have a value for the switch, it has to match!
754 if (!setValueOnce(ICI->getOperand(0)))
755 return false;
756
757 UsedICmps++;
758 Vals.push_back(C);
759 return true;
760 }
761
762 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
763 ConstantRange Span =
765
766 // Shift the range if the compare is fed by an add. This is the range
767 // compare idiom as emitted by instcombine.
768 Value *CandidateVal = I->getOperand(0);
769 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
770 Span = Span.subtract(*RHSC);
771 CandidateVal = RHSVal;
772 }
773
774 // If this is an and/!= check, then we are looking to build the set of
775 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
776 // x != 0 && x != 1.
777 if (!isEQ)
778 Span = Span.inverse();
779
780 // If there are a ton of values, we don't want to make a ginormous switch.
781 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
782 return false;
783 }
784
785 // If we already have a value for the switch, it has to match!
786 if (!setValueOnce(CandidateVal))
787 return false;
788
789 // Add all values from the range to the set
790 APInt Tmp = Span.getLower();
791 do
792 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
793 while (++Tmp != Span.getUpper());
794
795 UsedICmps++;
796 return true;
797 }
798
799 /// Given a potentially 'or'd or 'and'd together collection of icmp
800 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
801 /// the value being compared, and stick the list constants into the Vals
802 /// vector.
803 /// One "Extra" case is allowed to differ from the other.
804 void gather(Value *V) {
805 Value *Op0, *Op1;
806 if (match(V, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
807 IsEq = true;
808 else if (match(V, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
809 IsEq = false;
810 else
811 return;
812 // Keep a stack (SmallVector for efficiency) for depth-first traversal
813 SmallVector<Value *, 8> DFT{Op0, Op1};
814 SmallPtrSet<Value *, 8> Visited{V, Op0, Op1};
815
816 while (!DFT.empty()) {
817 V = DFT.pop_back_val();
818
819 if (Instruction *I = dyn_cast<Instruction>(V)) {
820 // If it is a || (or && depending on isEQ), process the operands.
821 if (IsEq ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
822 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
823 if (Visited.insert(Op1).second)
824 DFT.push_back(Op1);
825 if (Visited.insert(Op0).second)
826 DFT.push_back(Op0);
827
828 continue;
829 }
830
831 // Try to match the current instruction
832 if (matchInstruction(I, IsEq))
833 // Match succeed, continue the loop
834 continue;
835 }
836
837 // One element of the sequence of || (or &&) could not be match as a
838 // comparison against the same value as the others.
839 // We allow only one "Extra" case to be checked before the switch
840 if (!Extra) {
841 Extra = V;
842 continue;
843 }
844 // Failed to parse a proper sequence, abort now
845 CompValue = nullptr;
846 break;
847 }
848 }
849};
850
851} // end anonymous namespace
852
854 MemorySSAUpdater *MSSAU = nullptr) {
855 Instruction *Cond = nullptr;
857 Cond = dyn_cast<Instruction>(SI->getCondition());
858 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
859 Cond = dyn_cast<Instruction>(BI->getCondition());
860 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
861 Cond = dyn_cast<Instruction>(IBI->getAddress());
862 }
863
864 TI->eraseFromParent();
865 if (Cond)
867}
868
869/// Return true if the specified terminator checks
870/// to see if a value is equal to constant integer value.
871Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
872 Value *CV = nullptr;
873 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
874 // Do not permit merging of large switch instructions into their
875 // predecessors unless there is only one predecessor.
876 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
877 CV = SI->getCondition();
878 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI))
879 if (BI->getCondition()->hasOneUse()) {
880 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
881 if (ICI->isEquality() && getConstantInt(ICI->getOperand(1), DL))
882 CV = ICI->getOperand(0);
883 } else if (auto *Trunc = dyn_cast<TruncInst>(BI->getCondition())) {
884 if (Trunc->hasNoUnsignedWrap())
885 CV = Trunc->getOperand(0);
886 }
887 }
888
889 // Unwrap any lossless ptrtoint cast (except for unstable pointers).
890 if (CV) {
891 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
892 Value *Ptr = PTII->getPointerOperand();
893 if (DL.hasUnstableRepresentation(Ptr->getType()))
894 return CV;
895 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
896 CV = Ptr;
897 }
898 }
899 return CV;
900}
901
902/// Given a value comparison instruction,
903/// decode all of the 'cases' that it represents and return the 'default' block.
904BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
905 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
906 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
907 Cases.reserve(SI->getNumCases());
908 for (auto Case : SI->cases())
909 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
910 Case.getCaseSuccessor()));
911 return SI->getDefaultDest();
912 }
913
914 CondBrInst *BI = cast<CondBrInst>(TI);
915 Value *Cond = BI->getCondition();
916 ICmpInst::Predicate Pred;
917 ConstantInt *C;
918 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
919 Pred = ICI->getPredicate();
920 C = getConstantInt(ICI->getOperand(1), DL);
921 } else {
922 Pred = ICmpInst::ICMP_NE;
923 auto *Trunc = cast<TruncInst>(Cond);
924 C = ConstantInt::get(cast<IntegerType>(Trunc->getOperand(0)->getType()), 0);
925 }
926 BasicBlock *Succ = BI->getSuccessor(Pred == ICmpInst::ICMP_NE);
927 Cases.push_back(ValueEqualityComparisonCase(C, Succ));
928 return BI->getSuccessor(Pred == ICmpInst::ICMP_EQ);
929}
930
931/// Given a vector of bb/value pairs, remove any entries
932/// in the list that match the specified block.
933static void
935 std::vector<ValueEqualityComparisonCase> &Cases) {
936 llvm::erase(Cases, BB);
937}
938
939/// Return true if there are any keys in C1 that exist in C2 as well.
940static bool valuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
941 std::vector<ValueEqualityComparisonCase> &C2) {
942 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
943
944 // Make V1 be smaller than V2.
945 if (V1->size() > V2->size())
946 std::swap(V1, V2);
947
948 if (V1->empty())
949 return false;
950 if (V1->size() == 1) {
951 // Just scan V2.
952 ConstantInt *TheVal = (*V1)[0].Value;
953 for (const ValueEqualityComparisonCase &VECC : *V2)
954 if (TheVal == VECC.Value)
955 return true;
956 }
957
958 // Otherwise, just sort both lists and compare element by element.
959 array_pod_sort(V1->begin(), V1->end());
960 array_pod_sort(V2->begin(), V2->end());
961 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
962 while (i1 != e1 && i2 != e2) {
963 if ((*V1)[i1].Value == (*V2)[i2].Value)
964 return true;
965 if ((*V1)[i1].Value < (*V2)[i2].Value)
966 ++i1;
967 else
968 ++i2;
969 }
970 return false;
971}
972
973/// If TI is known to be a terminator instruction and its block is known to
974/// only have a single predecessor block, check to see if that predecessor is
975/// also a value comparison with the same value, and if that comparison
976/// determines the outcome of this comparison. If so, simplify TI. This does a
977/// very limited form of jump threading.
978bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
979 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
980 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
981 if (!PredVal)
982 return false; // Not a value comparison in predecessor.
983
984 Value *ThisVal = isValueEqualityComparison(TI);
985 assert(ThisVal && "This isn't a value comparison!!");
986 if (ThisVal != PredVal)
987 return false; // Different predicates.
988
989 // TODO: Preserve branch weight metadata, similarly to how
990 // foldValueComparisonIntoPredecessors preserves it.
991
992 // Find out information about when control will move from Pred to TI's block.
993 std::vector<ValueEqualityComparisonCase> PredCases;
994 BasicBlock *PredDef =
995 getValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
996 eliminateBlockCases(PredDef, PredCases); // Remove default from cases.
997
998 // Find information about how control leaves this block.
999 std::vector<ValueEqualityComparisonCase> ThisCases;
1000 BasicBlock *ThisDef = getValueEqualityComparisonCases(TI, ThisCases);
1001 eliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
1002
1003 // If TI's block is the default block from Pred's comparison, potentially
1004 // simplify TI based on this knowledge.
1005 if (PredDef == TI->getParent()) {
1006 // If we are here, we know that the value is none of those cases listed in
1007 // PredCases. If there are any cases in ThisCases that are in PredCases, we
1008 // can simplify TI.
1009 if (!valuesOverlap(PredCases, ThisCases))
1010 return false;
1011
1012 if (isa<CondBrInst>(TI)) {
1013 // Okay, one of the successors of this condbr is dead. Convert it to a
1014 // uncond br.
1015 assert(ThisCases.size() == 1 && "Branch can only have one case!");
1016 // Insert the new branch.
1017 Instruction *NI = Builder.CreateBr(ThisDef);
1018 (void)NI;
1019
1020 // Remove PHI node entries for the dead edge.
1021 ThisCases[0].Dest->removePredecessor(PredDef);
1022
1023 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1024 << "Through successor TI: " << *TI << "Leaving: " << *NI
1025 << "\n");
1026
1028
1029 if (DTU)
1030 DTU->applyUpdates(
1031 {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
1032
1033 return true;
1034 }
1035
1036 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
1037 // Okay, TI has cases that are statically dead, prune them away.
1038 SmallPtrSet<Constant *, 16> DeadCases;
1039 for (const ValueEqualityComparisonCase &Case : PredCases)
1040 DeadCases.insert(Case.Value);
1041
1042 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1043 << "Through successor TI: " << *TI);
1044
1045 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
1046 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
1047 --i;
1048 auto *Successor = i->getCaseSuccessor();
1049 if (DTU)
1050 ++NumPerSuccessorCases[Successor];
1051 if (DeadCases.count(i->getCaseValue())) {
1052 Successor->removePredecessor(PredDef);
1053 SI.removeCase(i);
1054 if (DTU)
1055 --NumPerSuccessorCases[Successor];
1056 }
1057 }
1058
1059 if (DTU) {
1060 std::vector<DominatorTree::UpdateType> Updates;
1061 for (const auto &I : NumPerSuccessorCases)
1062 if (I.second == 0)
1063 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
1064 DTU->applyUpdates(Updates);
1065 }
1066
1067 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
1068 return true;
1069 }
1070
1071 // Otherwise, TI's block must correspond to some matched value. Find out
1072 // which value (or set of values) this is.
1073 ConstantInt *TIV = nullptr;
1074 BasicBlock *TIBB = TI->getParent();
1075 for (const auto &[Value, Dest] : PredCases)
1076 if (Dest == TIBB) {
1077 if (TIV)
1078 return false; // Cannot handle multiple values coming to this block.
1079 TIV = Value;
1080 }
1081 assert(TIV && "No edge from pred to succ?");
1082
1083 // Okay, we found the one constant that our value can be if we get into TI's
1084 // BB. Find out which successor will unconditionally be branched to.
1085 BasicBlock *TheRealDest = nullptr;
1086 for (const auto &[Value, Dest] : ThisCases)
1087 if (Value == TIV) {
1088 TheRealDest = Dest;
1089 break;
1090 }
1091
1092 // If not handled by any explicit cases, it is handled by the default case.
1093 if (!TheRealDest)
1094 TheRealDest = ThisDef;
1095
1096 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1097
1098 // Remove PHI node entries for dead edges.
1099 BasicBlock *CheckEdge = TheRealDest;
1100 for (BasicBlock *Succ : successors(TIBB))
1101 if (Succ != CheckEdge) {
1102 if (Succ != TheRealDest)
1103 RemovedSuccs.insert(Succ);
1104 Succ->removePredecessor(TIBB);
1105 } else
1106 CheckEdge = nullptr;
1107
1108 // Insert the new branch.
1109 Instruction *NI = Builder.CreateBr(TheRealDest);
1110 (void)NI;
1111
1112 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1113 << "Through successor TI: " << *TI << "Leaving: " << *NI
1114 << "\n");
1115
1117 if (DTU) {
1118 SmallVector<DominatorTree::UpdateType, 2> Updates;
1119 Updates.reserve(RemovedSuccs.size());
1120 for (auto *RemovedSucc : RemovedSuccs)
1121 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1122 DTU->applyUpdates(Updates);
1123 }
1124 return true;
1125}
1126
1127namespace {
1128
1129/// This class implements a stable ordering of constant
1130/// integers that does not depend on their address. This is important for
1131/// applications that sort ConstantInt's to ensure uniqueness.
1132struct ConstantIntOrdering {
1133 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1134 return LHS->getValue().ult(RHS->getValue());
1135 }
1136};
1137
1138} // end anonymous namespace
1139
1141 ConstantInt *const *P2) {
1142 const ConstantInt *LHS = *P1;
1143 const ConstantInt *RHS = *P2;
1144 if (LHS == RHS)
1145 return 0;
1146 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1147}
1148
1149/// Get Weights of a given terminator, the default weight is at the front
1150/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1151/// metadata.
1153 SmallVectorImpl<uint64_t> &Weights) {
1154 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1155 assert(MD && "Invalid branch-weight metadata");
1156 extractFromBranchWeightMD64(MD, Weights);
1157
1158 // If TI is a conditional eq, the default case is the false case,
1159 // and the corresponding branch-weight data is at index 2. We swap the
1160 // default weight to be the first entry.
1161 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
1162 assert(Weights.size() == 2);
1163 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
1164 if (!ICI)
1165 return;
1166
1167 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1168 std::swap(Weights.front(), Weights.back());
1169 }
1170}
1171
1173 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1174 Instruction *PTI = PredBlock->getTerminator();
1175
1176 // If we have bonus instructions, clone them into the predecessor block.
1177 // Note that there may be multiple predecessor blocks, so we cannot move
1178 // bonus instructions to a predecessor block.
1179 for (Instruction &BonusInst : *BB) {
1180 if (BonusInst.isTerminator())
1181 continue;
1182
1183 // Skip cloning pseudo probes into the predecessor, as it would overcount
1184 // otherwise.
1185 if (isa<PseudoProbeInst>(BonusInst))
1186 continue;
1187
1188 Instruction *NewBonusInst = BonusInst.clone();
1189 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1190
1191 if (!NewBonusInst->getDebugLoc().isSameSourceLocation(PTI->getDebugLoc())) {
1192 // Unless the instruction has the same !dbg location as the original
1193 // branch, drop it. When we fold the bonus instructions we want to make
1194 // sure we reset their debug locations in order to avoid stepping on
1195 // dead code caused by folding dead branches.
1196 NewBonusInst->dropLocation();
1197 } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
1198 mapAtomInstance(DL, VMap);
1199 }
1200
1201 RemapInstruction(NewBonusInst, VMap,
1203
1204 // If we speculated an instruction, we need to drop any metadata that may
1205 // result in undefined behavior, as the metadata might have been valid
1206 // only given the branch precondition.
1207 // Similarly strip attributes on call parameters that may cause UB in
1208 // location the call is moved to.
1209 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1210
1211 auto Range = NewBonusInst->cloneDebugInfoFrom(&BonusInst);
1212 RemapDbgRecordRange(NewBonusInst->getModule(), Range, VMap,
1214
1215 NewBonusInst->takeName(&BonusInst);
1216 BonusInst.setName(NewBonusInst->getName() + ".old");
1217 VMap[&BonusInst] = NewBonusInst;
1218
1219 // Update (liveout) uses of bonus instructions,
1220 // now that the bonus instruction has been cloned into predecessor.
1221 // Note that we expect to be in a block-closed SSA form for this to work!
1222 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1223 auto *UI = cast<Instruction>(U.getUser());
1224 auto *PN = dyn_cast<PHINode>(UI);
1225 if (!PN) {
1226 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1227 "If the user is not a PHI node, then it should be in the same "
1228 "block as, and come after, the original bonus instruction.");
1229 continue; // Keep using the original bonus instruction.
1230 }
1231 // Is this the block-closed SSA form PHI node?
1232 if (PN->getIncomingBlock(U) == BB)
1233 continue; // Great, keep using the original bonus instruction.
1234 // The only other alternative is an "use" when coming from
1235 // the predecessor block - here we should refer to the cloned bonus instr.
1236 assert(PN->getIncomingBlock(U) == PredBlock &&
1237 "Not in block-closed SSA form?");
1238 U.set(NewBonusInst);
1239 }
1240 }
1241
1242 // Key Instructions: We may have propagated atom info into the pred. If the
1243 // pred's terminator already has atom info do nothing as merging would drop
1244 // one atom group anyway. If it doesn't, propagte the remapped atom group
1245 // from BB's terminator.
1246 if (auto &PredDL = PTI->getDebugLoc()) {
1247 auto &DL = BB->getTerminator()->getDebugLoc();
1248 if (!PredDL->getAtomGroup() && DL && DL->getAtomGroup() &&
1249 PredDL.isSameSourceLocation(DL)) {
1250 PTI->setDebugLoc(DL);
1251 RemapSourceAtom(PTI, VMap);
1252 }
1253 }
1254}
1255
1256bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
1257 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1258 BasicBlock *BB = TI->getParent();
1259 BasicBlock *Pred = PTI->getParent();
1260
1262
1263 // Figure out which 'cases' to copy from SI to PSI.
1264 std::vector<ValueEqualityComparisonCase> BBCases;
1265 BasicBlock *BBDefault = getValueEqualityComparisonCases(TI, BBCases);
1266
1267 std::vector<ValueEqualityComparisonCase> PredCases;
1268 BasicBlock *PredDefault = getValueEqualityComparisonCases(PTI, PredCases);
1269
1270 // Based on whether the default edge from PTI goes to BB or not, fill in
1271 // PredCases and PredDefault with the new switch cases we would like to
1272 // build.
1273 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1274
1275 // Update the branch weight metadata along the way
1276 SmallVector<uint64_t, 8> Weights;
1277 bool PredHasWeights = hasBranchWeightMD(*PTI);
1278 bool SuccHasWeights = hasBranchWeightMD(*TI);
1279
1280 if (PredHasWeights) {
1281 getBranchWeights(PTI, Weights);
1282 // branch-weight metadata is inconsistent here.
1283 if (Weights.size() != 1 + PredCases.size())
1284 PredHasWeights = SuccHasWeights = false;
1285 } else if (SuccHasWeights)
1286 // If there are no predecessor weights but there are successor weights,
1287 // populate Weights with 1, which will later be scaled to the sum of
1288 // successor's weights
1289 Weights.assign(1 + PredCases.size(), 1);
1290
1291 SmallVector<uint64_t, 8> SuccWeights;
1292 if (SuccHasWeights) {
1293 getBranchWeights(TI, SuccWeights);
1294 // branch-weight metadata is inconsistent here.
1295 if (SuccWeights.size() != 1 + BBCases.size())
1296 PredHasWeights = SuccHasWeights = false;
1297 } else if (PredHasWeights)
1298 SuccWeights.assign(1 + BBCases.size(), 1);
1299
1300 if (PredDefault == BB) {
1301 // If this is the default destination from PTI, only the edges in TI
1302 // that don't occur in PTI, or that branch to BB will be activated.
1303 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1304 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1305 if (PredCases[i].Dest != BB)
1306 PTIHandled.insert(PredCases[i].Value);
1307 else {
1308 // The default destination is BB, we don't need explicit targets.
1309 std::swap(PredCases[i], PredCases.back());
1310
1311 if (PredHasWeights || SuccHasWeights) {
1312 // Increase weight for the default case.
1313 Weights[0] += Weights[i + 1];
1314 std::swap(Weights[i + 1], Weights.back());
1315 Weights.pop_back();
1316 }
1317
1318 PredCases.pop_back();
1319 --i;
1320 --e;
1321 }
1322
1323 // Reconstruct the new switch statement we will be building.
1324 if (PredDefault != BBDefault) {
1325 PredDefault->removePredecessor(Pred);
1326 if (DTU && PredDefault != BB)
1327 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1328 PredDefault = BBDefault;
1329 ++NewSuccessors[BBDefault];
1330 }
1331
1332 unsigned CasesFromPred = Weights.size();
1333 uint64_t ValidTotalSuccWeight = 0;
1334 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1335 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1336 PredCases.push_back(BBCases[i]);
1337 ++NewSuccessors[BBCases[i].Dest];
1338 if (SuccHasWeights || PredHasWeights) {
1339 // The default weight is at index 0, so weight for the ith case
1340 // should be at index i+1. Scale the cases from successor by
1341 // PredDefaultWeight (Weights[0]).
1342 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1343 ValidTotalSuccWeight += SuccWeights[i + 1];
1344 }
1345 }
1346
1347 if (SuccHasWeights || PredHasWeights) {
1348 ValidTotalSuccWeight += SuccWeights[0];
1349 // Scale the cases from predecessor by ValidTotalSuccWeight.
1350 for (unsigned i = 1; i < CasesFromPred; ++i)
1351 Weights[i] *= ValidTotalSuccWeight;
1352 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1353 Weights[0] *= SuccWeights[0];
1354 }
1355 } else {
1356 // If this is not the default destination from PSI, only the edges
1357 // in SI that occur in PSI with a destination of BB will be
1358 // activated.
1359 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1360 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1361 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1362 if (PredCases[i].Dest == BB) {
1363 PTIHandled.insert(PredCases[i].Value);
1364
1365 if (PredHasWeights || SuccHasWeights) {
1366 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1367 std::swap(Weights[i + 1], Weights.back());
1368 Weights.pop_back();
1369 }
1370
1371 std::swap(PredCases[i], PredCases.back());
1372 PredCases.pop_back();
1373 --i;
1374 --e;
1375 }
1376
1377 // Okay, now we know which constants were sent to BB from the
1378 // predecessor. Figure out where they will all go now.
1379 for (const ValueEqualityComparisonCase &Case : BBCases)
1380 if (PTIHandled.count(Case.Value)) {
1381 // If this is one we are capable of getting...
1382 if (PredHasWeights || SuccHasWeights)
1383 Weights.push_back(WeightsForHandled[Case.Value]);
1384 PredCases.push_back(Case);
1385 ++NewSuccessors[Case.Dest];
1386 PTIHandled.erase(Case.Value); // This constant is taken care of
1387 }
1388
1389 // If there are any constants vectored to BB that TI doesn't handle,
1390 // they must go to the default destination of TI.
1391 for (ConstantInt *I : PTIHandled) {
1392 if (PredHasWeights || SuccHasWeights)
1393 Weights.push_back(WeightsForHandled[I]);
1394 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1395 ++NewSuccessors[BBDefault];
1396 }
1397 }
1398
1399 // Okay, at this point, we know which new successor Pred will get. Make
1400 // sure we update the number of entries in the PHI nodes for these
1401 // successors.
1402 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1403 if (DTU) {
1404 SuccsOfPred = {llvm::from_range, successors(Pred)};
1405 Updates.reserve(Updates.size() + NewSuccessors.size());
1406 }
1407 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1408 NewSuccessors) {
1409 for (auto I : seq(NewSuccessor.second)) {
1410 (void)I;
1411 addPredecessorToBlock(NewSuccessor.first, Pred, BB);
1412 }
1413 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1414 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1415 }
1416
1417 Builder.SetInsertPoint(PTI);
1418 // Convert pointer to int before we switch.
1419 if (CV->getType()->isPointerTy()) {
1420 assert(!DL.hasUnstableRepresentation(CV->getType()) &&
1421 "Should not end up here with unstable pointers");
1422 CV =
1423 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1424 }
1425
1426 // Now that the successors are updated, create the new Switch instruction.
1427 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1428 NewSI->setDebugLoc(PTI->getDebugLoc());
1429 for (ValueEqualityComparisonCase &V : PredCases)
1430 NewSI->addCase(V.Value, V.Dest);
1431
1432 if (PredHasWeights || SuccHasWeights)
1433 setFittedBranchWeights(*NewSI, Weights, /*IsExpected=*/false,
1434 /*ElideAllZero=*/true);
1435 else
1437
1438 // The new switch is only known to be unpredictable if both of the comparisons
1439 // it was built from were unpredictable.
1440 if (MDNode *Unpredictable = PTI->getMetadata(LLVMContext::MD_unpredictable))
1441 if (TI->hasMetadata(LLVMContext::MD_unpredictable))
1442 NewSI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
1443
1445
1446 // Okay, last check. If BB is still a successor of PSI, then we must
1447 // have an infinite loop case. If so, add an infinitely looping block
1448 // to handle the case to preserve the behavior of the code.
1449 BasicBlock *InfLoopBlock = nullptr;
1450 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1451 if (NewSI->getSuccessor(i) == BB) {
1452 if (!InfLoopBlock) {
1453 // Insert it at the end of the function, because it's either code,
1454 // or it won't matter if it's hot. :)
1455 InfLoopBlock =
1456 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1457 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
1458 if (DTU)
1459 Updates.push_back(
1460 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1461 }
1462 NewSI->setSuccessor(i, InfLoopBlock);
1463 }
1464
1465 if (DTU) {
1466 if (InfLoopBlock)
1467 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1468
1469 Updates.push_back({DominatorTree::Delete, Pred, BB});
1470
1471 DTU->applyUpdates(Updates);
1472 }
1473
1474 ++NumFoldValueComparisonIntoPredecessors;
1475 return true;
1476}
1477
1478/// The specified terminator is a value equality comparison instruction
1479/// (either a switch or a branch on "X == c").
1480/// See if any of the predecessors of the terminator block are value comparisons
1481/// on the same value. If so, and if safe to do so, fold them together.
1482bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1483 IRBuilder<> &Builder) {
1484 BasicBlock *BB = TI->getParent();
1485 Value *CV = isValueEqualityComparison(TI); // CondVal
1486 assert(CV && "Not a comparison?");
1487
1488 bool Changed = false;
1489
1490 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1491 while (!Preds.empty()) {
1492 BasicBlock *Pred = Preds.pop_back_val();
1493 Instruction *PTI = Pred->getTerminator();
1494
1495 // Don't try to fold into itself.
1496 if (Pred == BB)
1497 continue;
1498
1499 // See if the predecessor is a comparison with the same value.
1500 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1501 if (PCV != CV)
1502 continue;
1503
1504 SmallSetVector<BasicBlock *, 4> FailBlocks;
1505 if (!safeToMergeTerminators(TI, PTI, &FailBlocks)) {
1506 for (auto *Succ : FailBlocks) {
1507 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1508 return false;
1509 }
1510 }
1511
1512 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1513 Changed = true;
1514 }
1515 return Changed;
1516}
1517
1518// If we would need to insert a select that uses the value of this invoke
1519// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1520// need to do this), we can't hoist the invoke, as there is nowhere to put the
1521// select in this case.
1523 Instruction *I1, Instruction *I2) {
1524 for (BasicBlock *Succ : successors(BB1)) {
1525 for (const PHINode &PN : Succ->phis()) {
1526 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1527 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1528 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1529 return false;
1530 }
1531 }
1532 }
1533 return true;
1534}
1535
1536// Get interesting characteristics of instructions that
1537// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1538// instructions can be reordered across.
1544
1546 // Pseudo probes don't constrain reordering of other instructions.
1548 return 0;
1549 unsigned Flags = 0;
1550 if (I->mayReadFromMemory())
1551 Flags |= SkipReadMem;
1552 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1553 // inalloca) across stacksave/stackrestore boundaries.
1554 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1555 Flags |= SkipSideEffect;
1557 Flags |= SkipImplicitControlFlow;
1558 return Flags;
1559}
1560
1561// Returns true if it is safe to reorder an instruction across preceding
1562// instructions in a basic block.
1563static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1564 // Don't reorder a store over a load.
1565 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1566 return false;
1567
1568 // If we have seen an instruction with side effects, it's unsafe to reorder an
1569 // instruction which reads memory or itself has side effects.
1570 if ((Flags & SkipSideEffect) &&
1571 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1572 return false;
1573
1574 // Reordering across an instruction which does not necessarily transfer
1575 // control to the next instruction is speculation.
1577 return false;
1578
1579 // Hoisting of llvm.deoptimize is only legal together with the next return
1580 // instruction, which this pass is not always able to do.
1581 if (auto *CB = dyn_cast<CallBase>(I))
1582 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1583 return false;
1584
1585 // It's also unsafe/illegal to hoist an instruction above its instruction
1586 // operands
1587 BasicBlock *BB = I->getParent();
1588 for (Value *Op : I->operands()) {
1589 if (auto *J = dyn_cast<Instruction>(Op))
1590 if (J->getParent() == BB)
1591 return false;
1592 }
1593
1594 return true;
1595}
1596
1597static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1598
1599/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1600/// instructions \p I1 and \p I2 can and should be hoisted.
1602 const TargetTransformInfo &TTI) {
1603 // If we're going to hoist a call, make sure that the two instructions
1604 // we're commoning/hoisting are both marked with musttail, or neither of
1605 // them is marked as such. Otherwise, we might end up in a situation where
1606 // we hoist from a block where the terminator is a `ret` to a block where
1607 // the terminator is a `br`, and `musttail` calls expect to be followed by
1608 // a return.
1609 auto *C1 = dyn_cast<CallInst>(I1);
1610 auto *C2 = dyn_cast<CallInst>(I2);
1611 if (C1 && C2)
1612 if (C1->isMustTailCall() != C2->isMustTailCall())
1613 return false;
1614
1615 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1616 return false;
1617
1618 // If any of the two call sites has nomerge or convergent attribute, stop
1619 // hoisting.
1620 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1621 if (CB1->cannotMerge() || CB1->isConvergent())
1622 return false;
1623 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1624 if (CB2->cannotMerge() || CB2->isConvergent())
1625 return false;
1626
1627 return true;
1628}
1629
1630/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1631/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1632/// hoistCommonCodeFromSuccessors. e.g. The input:
1633/// I1 DVRs: { x, z },
1634/// OtherInsts: { I2 DVRs: { x, y, z } }
1635/// would result in hoisting only DbgVariableRecord x.
1637 Instruction *TI, Instruction *I1,
1638 SmallVectorImpl<Instruction *> &OtherInsts) {
1639 if (!I1->hasDbgRecords())
1640 return;
1641 using CurrentAndEndIt =
1642 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1643 // Vector of {Current, End} iterators.
1645 Itrs.reserve(OtherInsts.size() + 1);
1646 // Helper lambdas for lock-step checks:
1647 // Return true if this Current == End.
1648 auto atEnd = [](const CurrentAndEndIt &Pair) {
1649 return Pair.first == Pair.second;
1650 };
1651 // Return true if all Current are identical.
1652 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1653 return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
1655 return Itrs[0].first->isIdenticalToWhenDefined(*I);
1656 });
1657 };
1658
1659 // Collect the iterators.
1660 Itrs.push_back(
1661 {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1662 for (Instruction *Other : OtherInsts) {
1663 if (!Other->hasDbgRecords())
1664 return;
1665 Itrs.push_back(
1666 {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1667 }
1668
1669 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1670 // the lock-step DbgRecord are identical, hoist all of them to TI.
1671 // This replicates the dbg.* intrinsic behaviour in
1672 // hoistCommonCodeFromSuccessors.
1673 while (none_of(Itrs, atEnd)) {
1674 bool HoistDVRs = allIdentical(Itrs);
1675 for (CurrentAndEndIt &Pair : Itrs) {
1676 // Increment Current iterator now as we may be about to move the
1677 // DbgRecord.
1678 DbgRecord &DR = *Pair.first++;
1679 if (HoistDVRs) {
1680 DR.removeFromParent();
1681 TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
1682 }
1683 }
1684 }
1685}
1686
1688 const Instruction *I2) {
1689 if (I1->isIdenticalToWhenDefined(I2, /*IntersectAttrs=*/true))
1690 return true;
1691
1692 if (auto *Cmp1 = dyn_cast<CmpInst>(I1))
1693 if (auto *Cmp2 = dyn_cast<CmpInst>(I2))
1694 return Cmp1->getPredicate() == Cmp2->getSwappedPredicate() &&
1695 Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
1696 Cmp1->getOperand(1) == Cmp2->getOperand(0);
1697
1698 if (I1->isCommutative() && I1->isSameOperationAs(I2)) {
1699 return I1->getOperand(0) == I2->getOperand(1) &&
1700 I1->getOperand(1) == I2->getOperand(0) &&
1701 equal(drop_begin(I1->operands(), 2), drop_begin(I2->operands(), 2));
1702 }
1703
1704 return false;
1705}
1706
1707/// If the target supports conditional faulting,
1708/// we look for the following pattern:
1709/// \code
1710/// BB:
1711/// ...
1712/// %cond = icmp ult %x, %y
1713/// br i1 %cond, label %TrueBB, label %FalseBB
1714/// FalseBB:
1715/// store i32 1, ptr %q, align 4
1716/// ...
1717/// TrueBB:
1718/// %maskedloadstore = load i32, ptr %b, align 4
1719/// store i32 %maskedloadstore, ptr %p, align 4
1720/// ...
1721/// \endcode
1722///
1723/// and transform it into:
1724///
1725/// \code
1726/// BB:
1727/// ...
1728/// %cond = icmp ult %x, %y
1729/// %maskedloadstore = cload i32, ptr %b, %cond
1730/// cstore i32 %maskedloadstore, ptr %p, %cond
1731/// cstore i32 1, ptr %q, ~%cond
1732/// br i1 %cond, label %TrueBB, label %FalseBB
1733/// FalseBB:
1734/// ...
1735/// TrueBB:
1736/// ...
1737/// \endcode
1738///
1739/// where cload/cstore are represented by llvm.masked.load/store intrinsics,
1740/// e.g.
1741///
1742/// \code
1743/// %vcond = bitcast i1 %cond to <1 x i1>
1744/// %v0 = call <1 x i32> @llvm.masked.load.v1i32.p0
1745/// (ptr %b, i32 4, <1 x i1> %vcond, <1 x i32> poison)
1746/// %maskedloadstore = bitcast <1 x i32> %v0 to i32
1747/// call void @llvm.masked.store.v1i32.p0
1748/// (<1 x i32> %v0, ptr %p, i32 4, <1 x i1> %vcond)
1749/// %cond.not = xor i1 %cond, true
1750/// %vcond.not = bitcast i1 %cond.not to <1 x i>
1751/// call void @llvm.masked.store.v1i32.p0
1752/// (<1 x i32> <i32 1>, ptr %q, i32 4, <1x i1> %vcond.not)
1753/// \endcode
1754///
1755/// So we need to turn hoisted load/store into cload/cstore.
1756///
1757/// \param BI The branch instruction.
1758/// \param SpeculatedConditionalLoadsStores The load/store instructions that
1759/// will be speculated.
1760/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
1762 CondBrInst *BI,
1763 SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
1764 std::optional<bool> Invert, Instruction *Sel) {
1765 auto &Context = BI->getParent()->getContext();
1766 auto *VCondTy = FixedVectorType::get(Type::getInt1Ty(Context), 1);
1767 auto *Cond = BI->getCondition();
1768 // Construct the condition if needed.
1769 BasicBlock *BB = BI->getParent();
1770 Value *Mask = nullptr;
1771 Value *MaskFalse = nullptr;
1772 Value *MaskTrue = nullptr;
1773 if (Invert.has_value()) {
1774 IRBuilder<> Builder(Sel ? Sel : SpeculatedConditionalLoadsStores.back());
1775 Mask = Builder.CreateBitCast(
1776 *Invert ? Builder.CreateXor(Cond, ConstantInt::getTrue(Context)) : Cond,
1777 VCondTy);
1778 } else {
1779 IRBuilder<> Builder(BI);
1780 MaskFalse = Builder.CreateBitCast(
1781 Builder.CreateXor(Cond, ConstantInt::getTrue(Context)), VCondTy);
1782 MaskTrue = Builder.CreateBitCast(Cond, VCondTy);
1783 }
1784 auto PeekThroughBitcasts = [](Value *V) {
1785 while (auto *BitCast = dyn_cast<BitCastInst>(V))
1786 V = BitCast->getOperand(0);
1787 return V;
1788 };
1789 for (auto *I : SpeculatedConditionalLoadsStores) {
1790 IRBuilder<> Builder(Invert.has_value() ? I : BI);
1791 if (!Invert.has_value())
1792 Mask = I->getParent() == BI->getSuccessor(0) ? MaskTrue : MaskFalse;
1793 // We currently assume conditional faulting load/store is supported for
1794 // scalar types only when creating new instructions. This can be easily
1795 // extended for vector types in the future.
1796 assert(!getLoadStoreType(I)->isVectorTy() && "not implemented");
1797 auto *Op0 = I->getOperand(0);
1798 CallInst *MaskedLoadStore = nullptr;
1799 if (auto *LI = dyn_cast<LoadInst>(I)) {
1800 // Handle Load.
1801 auto *Ty = I->getType();
1802 PHINode *PN = nullptr;
1803 Value *PassThru = nullptr;
1804 if (Invert.has_value())
1805 for (User *U : I->users()) {
1806 if ((PN = dyn_cast<PHINode>(U))) {
1807 PassThru = Builder.CreateBitCast(
1808 PeekThroughBitcasts(PN->getIncomingValueForBlock(BB)),
1809 FixedVectorType::get(Ty, 1));
1810 } else if (auto *Ins = cast<Instruction>(U);
1811 Sel && Ins->getParent() == BB) {
1812 // This happens when store or/and a speculative instruction between
1813 // load and store were hoisted to the BB. Make sure the masked load
1814 // inserted before its use.
1815 // We assume there's one of such use.
1816 Builder.SetInsertPoint(Ins);
1817 }
1818 }
1819 MaskedLoadStore = Builder.CreateMaskedLoad(
1820 FixedVectorType::get(Ty, 1), Op0, LI->getAlign(), Mask, PassThru);
1821 if (const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1823 if (PassThru && !isa<PoisonValue>(PassThru)) {
1824 auto *C = dyn_cast<Constant>(PassThru);
1825 CR = C ? CR.unionWith(C->toConstantRange())
1826 : ConstantRange::getFull(CR.getBitWidth());
1827 }
1828 MaskedLoadStore->addRangeRetAttr(CR);
1829 }
1830 Value *NewLoadStore = Builder.CreateBitCast(MaskedLoadStore, Ty);
1831 if (PN)
1832 PN->setIncomingValue(PN->getBasicBlockIndex(BB), NewLoadStore);
1833 I->replaceAllUsesWith(NewLoadStore);
1834 } else {
1835 // Handle Store.
1836 auto *StoredVal = Builder.CreateBitCast(
1837 PeekThroughBitcasts(Op0), FixedVectorType::get(Op0->getType(), 1));
1838 MaskedLoadStore = Builder.CreateMaskedStore(
1839 StoredVal, I->getOperand(1), cast<StoreInst>(I)->getAlign(), Mask);
1840 }
1841 // For non-debug metadata, only !annotation, !range, !nonnull and !align are
1842 // kept when hoisting (see Instruction::dropUBImplyingAttrsAndMetadata).
1843 //
1844 // !nonnull, !align : Not support pointer type, no need to keep.
1845 // !range: Kept as a return attribute, widened over PassThru (see above).
1846 // !annotation: Not impact semantics. Keep it.
1847 I->dropUBImplyingAttrsAndUnknownMetadata({LLVMContext::MD_annotation});
1848 // FIXME: DIAssignID is not supported for masked store yet.
1849 // (Verifier::visitDIAssignIDMetadata)
1851 I->eraseMetadataIf([](unsigned MDKind, MDNode *Node) {
1852 return Node->getMetadataID() == Metadata::DIAssignIDKind;
1853 });
1854 MaskedLoadStore->copyMetadata(*I);
1855 I->eraseFromParent();
1856 }
1857}
1858
1860 const TargetTransformInfo &TTI) {
1861 // Not handle volatile or atomic.
1862 bool IsStore = false;
1863 if (auto *L = dyn_cast<LoadInst>(I)) {
1864 if (!L->isSimple() || !HoistLoadsWithCondFaulting)
1865 return false;
1866 } else if (auto *S = dyn_cast<StoreInst>(I)) {
1867 if (!S->isSimple() || !HoistStoresWithCondFaulting)
1868 return false;
1869 IsStore = true;
1870 } else
1871 return false;
1872
1873 // llvm.masked.load/store use i32 for alignment while load/store use i64.
1874 // That's why we have the alignment limitation.
1875 // FIXME: Update the prototype of the intrinsics?
1876 return TTI.hasConditionalLoadStoreForType(getLoadStoreType(I), IsStore) &&
1878}
1879
1880/// Hoist any common code in the successor blocks up into the block. This
1881/// function guarantees that BB dominates all successors. If AllInstsEqOnly is
1882/// given, only perform hoisting in case all successors blocks contain matching
1883/// instructions only. In that case, all instructions can be hoisted and the
1884/// original branch will be replaced and selects for PHIs are added.
1885bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(Instruction *TI,
1886 bool AllInstsEqOnly) {
1887 // This does very trivial matching, with limited scanning, to find identical
1888 // instructions in the two blocks. In particular, we don't want to get into
1889 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1890 // such, we currently just scan for obviously identical instructions in an
1891 // identical order, possibly separated by the same number of non-identical
1892 // instructions.
1893 BasicBlock *BB = TI->getParent();
1894 unsigned int SuccSize = succ_size(BB);
1895 if (SuccSize < 2)
1896 return false;
1897
1898 // If either of the blocks has it's address taken, then we can't do this fold,
1899 // because the code we'd hoist would no longer run when we jump into the block
1900 // by it's address.
1901 SmallSetVector<BasicBlock *, 4> UniqueSuccessors(from_range, successors(BB));
1902 for (auto *Succ : UniqueSuccessors) {
1903 if (Succ->hasAddressTaken())
1904 return false;
1905 // Use getUniquePredecessor instead of getSinglePredecessor to support
1906 // multi-cases successors in switch.
1907 if (Succ->getUniquePredecessor())
1908 continue;
1909 // If Succ has >1 predecessors, continue to check if the Succ contains only
1910 // one `unreachable` inst. Since executing `unreachable` inst is an UB, we
1911 // can relax the condition based on the assumptiom that the program would
1912 // never enter Succ and trigger such an UB.
1913 if (isa<UnreachableInst>(*Succ->begin()))
1914 continue;
1915 return false;
1916 }
1917 // The second of pair is a SkipFlags bitmask.
1918 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1919 SmallVector<SuccIterPair, 8> SuccIterPairs;
1920 for (auto *Succ : UniqueSuccessors) {
1921 BasicBlock::iterator SuccItr = Succ->begin();
1922 if (isa<PHINode>(*SuccItr))
1923 return false;
1924 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1925 }
1926
1927 if (AllInstsEqOnly) {
1928 // Check if all instructions in the successor blocks match. This allows
1929 // hoisting all instructions and removing the blocks we are hoisting from,
1930 // so does not add any new instructions.
1931
1932 // Check if sizes and terminators of all successors match.
1933 unsigned Size0 = UniqueSuccessors[0]->size();
1934 Instruction *Term0 = UniqueSuccessors[0]->getTerminator();
1935 bool AllSame =
1936 all_of(drop_begin(UniqueSuccessors), [Term0, Size0](BasicBlock *Succ) {
1937 return Succ->getTerminator()->isIdenticalTo(Term0) &&
1938 Succ->size() == Size0;
1939 });
1940 if (!AllSame)
1941 return false;
1942 LockstepReverseIterator<true> LRI(UniqueSuccessors.getArrayRef());
1943 while (LRI.isValid()) {
1944 Instruction *I0 = (*LRI)[0];
1945 if (any_of(*LRI, [I0](Instruction *I) {
1946 return !areIdenticalUpToCommutativity(I0, I);
1947 })) {
1948 return false;
1949 }
1950 --LRI;
1951 }
1952 // Now we know that all instructions in all successors can be hoisted. Let
1953 // the loop below handle the hoisting.
1954 }
1955
1956 // Count how many instructions were not hoisted so far. There's a limit on how
1957 // many instructions we skip, serving as a compilation time control as well as
1958 // preventing excessive increase of life ranges.
1959 unsigned NumSkipped = 0;
1960 // If we find an unreachable instruction at the beginning of a basic block, we
1961 // can still hoist instructions from the rest of the basic blocks.
1962 if (SuccIterPairs.size() > 2) {
1963 erase_if(SuccIterPairs,
1964 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1965 if (SuccIterPairs.size() < 2)
1966 return false;
1967 }
1968
1969 bool Changed = false;
1970
1971 for (;;) {
1972 auto *SuccIterPairBegin = SuccIterPairs.begin();
1973 auto &BB1ItrPair = *SuccIterPairBegin++;
1974 auto OtherSuccIterPairRange =
1975 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1976 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1977
1978 Instruction *I1 = &*BB1ItrPair.first;
1979
1980 bool AllInstsAreIdentical = true;
1981 bool HasTerminator = I1->isTerminator();
1982 for (auto &SuccIter : OtherSuccIterRange) {
1983 Instruction *I2 = &*SuccIter;
1984 HasTerminator |= I2->isTerminator();
1985 if (AllInstsAreIdentical && (!areIdenticalUpToCommutativity(I1, I2) ||
1986 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1987 AllInstsAreIdentical = false;
1988 }
1989
1990 SmallVector<Instruction *, 8> OtherInsts;
1991 for (auto &SuccIter : OtherSuccIterRange)
1992 OtherInsts.push_back(&*SuccIter);
1993
1994 // If we are hoisting the terminator instruction, don't move one (making a
1995 // broken BB), instead clone it, and remove BI.
1996 if (HasTerminator) {
1997 // Even if BB, which contains only one unreachable instruction, is ignored
1998 // at the beginning of the loop, we can hoist the terminator instruction.
1999 // If any instructions remain in the block, we cannot hoist terminators.
2000 if (NumSkipped || !AllInstsAreIdentical) {
2001 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2002 return Changed;
2003 }
2004
2005 return hoistSuccIdenticalTerminatorToSwitchOrIf(
2006 TI, I1, OtherInsts, UniqueSuccessors.getArrayRef()) ||
2007 Changed;
2008 }
2009
2010 if (AllInstsAreIdentical) {
2011 unsigned SkipFlagsBB1 = BB1ItrPair.second;
2012 AllInstsAreIdentical =
2013 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
2014 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
2015 Instruction *I2 = &*Pair.first;
2016 unsigned SkipFlagsBB2 = Pair.second;
2017 // Even if the instructions are identical, it may not
2018 // be safe to hoist them if we have skipped over
2019 // instructions with side effects or their operands
2020 // weren't hoisted.
2021 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
2023 });
2024 }
2025
2026 // A musttail call must be immediately followed by a ret, so hoisting is
2027 // only legal if its ret is hoisted with it on the next iteration. That is,
2028 // no instruction has been skipped (the entire successor can be hoisted into
2029 // the predecessor) and the call is directly followed by a ret.
2030 if (auto *CI = dyn_cast<CallInst>(I1);
2031 AllInstsAreIdentical && CI && CI->isMustTailCall()) {
2032 AllInstsAreIdentical =
2033 NumSkipped == 0 && all_of(SuccIterPairs, [](const SuccIterPair &P) {
2034 return isa<ReturnInst>(*std::next(P.first));
2035 });
2036 }
2037
2038 if (AllInstsAreIdentical) {
2039 BB1ItrPair.first++;
2040 // For a normal instruction, we just move one to right before the
2041 // branch, then replace all uses of the other with the first. Finally,
2042 // we remove the now redundant second instruction.
2043 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2044 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
2045 // and leave any that were not hoisted behind (by calling moveBefore
2046 // rather than moveBeforePreserving).
2047 I1->moveBefore(TI->getIterator());
2048 for (auto &SuccIter : OtherSuccIterRange) {
2049 Instruction *I2 = &*SuccIter++;
2050 assert(I2 != I1);
2051 if (!I2->use_empty())
2052 I2->replaceAllUsesWith(I1);
2053 I1->andIRFlags(I2);
2054 if (auto *CB = dyn_cast<CallBase>(I1)) {
2055 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I2));
2056 assert(Success && "We should not be trying to hoist callbases "
2057 "with non-intersectable attributes");
2058 // For NDEBUG Compile.
2059 (void)Success;
2060 }
2061
2062 combineMetadataForCSE(I1, I2, true);
2063 // If we are combining select instructions, we mark the profile
2064 // explicitly unknown given we are hoisting the instruction across
2065 // control flow and we have no guarantee that the control flow condition
2066 // we are hoisting across is independent of the select condition.
2067 if (auto *SI = dyn_cast<SelectInst>(I1))
2069 // I1 and I2 are being combined into a single instruction. Its debug
2070 // location is the merged locations of the original instructions.
2071 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
2072 I2->eraseFromParent();
2073 }
2074 // I1 now executes before the instructions we skipped.
2075 unsigned SkippedFlags = 0;
2076 for (const SuccIterPair &P : SuccIterPairs)
2077 SkippedFlags |= P.second;
2078 if (SkippedFlags & SkipImplicitControlFlow) {
2079 // One of them may throw or not return, so I1 is speculated.
2080 I1->dropUBImplyingAttrsAndMetadata();
2081 }
2082 if (!Changed)
2083 NumHoistCommonCode += SuccIterPairs.size();
2084 Changed = true;
2085 NumHoistCommonInstrs += SuccIterPairs.size();
2086 } else {
2087 if (NumSkipped >= HoistCommonSkipLimit) {
2088 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2089 return Changed;
2090 }
2091 // We are about to skip over a pair of non-identical instructions. Record
2092 // if any have characteristics that would prevent reordering instructions
2093 // across them.
2094 for (auto &SuccIterPair : SuccIterPairs) {
2095 Instruction *I = &*SuccIterPair.first++;
2096 SuccIterPair.second |= skippedInstrFlags(I);
2097 }
2098 ++NumSkipped;
2099 }
2100 }
2101}
2102
2103bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
2104 Instruction *TI, Instruction *I1,
2105 SmallVectorImpl<Instruction *> &OtherSuccTIs,
2106 ArrayRef<BasicBlock *> UniqueSuccessors) {
2107
2108 auto *BI = dyn_cast<CondBrInst>(TI);
2109
2110 bool Changed = false;
2111 BasicBlock *TIParent = TI->getParent();
2112 BasicBlock *BB1 = I1->getParent();
2113
2114 // Use only for an if statement.
2115 auto *I2 = *OtherSuccTIs.begin();
2116 auto *BB2 = I2->getParent();
2117 if (BI) {
2118 assert(OtherSuccTIs.size() == 1);
2119 assert(BI->getSuccessor(0) == I1->getParent());
2120 assert(BI->getSuccessor(1) == I2->getParent());
2121 }
2122
2123 // In the case of an if statement, we try to hoist an invoke.
2124 // FIXME: Can we define a safety predicate for CallBr?
2125 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
2126 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
2127 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
2128 return false;
2129
2130 // TODO: callbr hoisting currently disabled pending further study.
2131 if (isa<CallBrInst>(I1))
2132 return false;
2133
2134 for (BasicBlock *Succ : successors(BB1)) {
2135 for (PHINode &PN : Succ->phis()) {
2136 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2137 for (Instruction *OtherSuccTI : OtherSuccTIs) {
2138 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
2139 if (BB1V == BB2V)
2140 continue;
2141
2142 // In the case of an if statement, check for
2143 // passingValueIsAlwaysUndefined here because we would rather eliminate
2144 // undefined control flow then converting it to a select.
2145 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
2147 return false;
2148 }
2149 }
2150 }
2151
2152 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
2153 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
2154 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
2155 // Clone the terminator and hoist it into the pred, without any debug info.
2156 Instruction *NT = I1->clone();
2157 NT->insertInto(TIParent, TI->getIterator());
2158 if (!NT->getType()->isVoidTy()) {
2159 I1->replaceAllUsesWith(NT);
2160 for (Instruction *OtherSuccTI : OtherSuccTIs)
2161 OtherSuccTI->replaceAllUsesWith(NT);
2162 NT->takeName(I1);
2163 }
2164 Changed = true;
2165 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
2166
2167 // Ensure terminator gets a debug location, even an unknown one, in case
2168 // it involves inlinable calls.
2170 Locs.push_back(I1->getDebugLoc());
2171 for (auto *OtherSuccTI : OtherSuccTIs)
2172 Locs.push_back(OtherSuccTI->getDebugLoc());
2173 NT->setDebugLoc(DebugLoc::getMergedLocations(Locs));
2174
2175 // PHIs created below will adopt NT's merged DebugLoc.
2176 IRBuilder<NoFolder> Builder(NT);
2177
2178 // In the case of an if statement, hoisting one of the terminators from our
2179 // successor is a great thing. Unfortunately, the successors of the if/else
2180 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
2181 // must agree for all PHI nodes, so we insert select instruction to compute
2182 // the final result.
2183 if (BI) {
2184 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
2185 for (BasicBlock *Succ : successors(BB1)) {
2186 for (PHINode &PN : Succ->phis()) {
2187 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2188 Value *BB2V = PN.getIncomingValueForBlock(BB2);
2189 if (BB1V == BB2V)
2190 continue;
2191
2192 // These values do not agree. Insert a select instruction before NT
2193 // that determines the right value.
2194 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
2195 if (!SI) {
2196 // Propagate fast-math-flags from phi node to its replacement select.
2198 BI->getCondition(), BB1V, BB2V,
2199 isa<FPMathOperator>(PN) ? &PN : nullptr,
2200 BB1V->getName() + "." + BB2V->getName(), BI));
2201 }
2202
2203 // Make the PHI node use the select for all incoming values for BB1/BB2
2204 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2205 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
2206 PN.setIncomingValue(i, SI);
2207 }
2208 }
2209 }
2210
2212
2213 // Update any PHI nodes in our new successors.
2214 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
2215 for (BasicBlock *Succ : successors(BB1)) {
2216 addPredecessorToBlock(Succ, TIParent, BB1);
2217
2218 if (DTU && VisitedSuccs.insert(Succ).second)
2219 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
2220 }
2221
2222 if (DTU) {
2223 // TI might be a switch with multi-cases destination, so we need to care for
2224 // the duplication of successors.
2225 for (BasicBlock *Succ : UniqueSuccessors)
2226 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
2227 }
2228
2230 if (DTU)
2231 DTU->applyUpdates(Updates);
2232 return Changed;
2233}
2234
2235// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
2236// into variables.
2238 int OpIdx) {
2239 // Divide/Remainder by constant is typically much cheaper than by variable.
2240 if (I->isIntDivRem())
2241 return OpIdx != 1;
2242 return !isa<IntrinsicInst>(I);
2243}
2244
2245// All instructions in Insts belong to different blocks that all unconditionally
2246// branch to a common successor. Analyze each instruction and return true if it
2247// would be possible to sink them into their successor, creating one common
2248// instruction instead. For every value that would be required to be provided by
2249// PHI node (because an operand varies in each input block), add to PHIOperands.
2252 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
2253 // Prune out obviously bad instructions to move. Each instruction must have
2254 // the same number of uses, and we check later that the uses are consistent.
2255 std::optional<unsigned> NumUses;
2256 for (auto *I : Insts) {
2257 // These instructions may change or break semantics if moved.
2258 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
2259 I->getType()->isTokenTy())
2260 return false;
2261
2262 // Do not try to sink an instruction in an infinite loop - it can cause
2263 // this algorithm to infinite loop.
2264 if (I->getParent()->getSingleSuccessor() == I->getParent())
2265 return false;
2266
2267 // Conservatively return false if I is an inline-asm instruction. Sinking
2268 // and merging inline-asm instructions can potentially create arguments
2269 // that cannot satisfy the inline-asm constraints.
2270 // If the instruction has nomerge or convergent attribute, return false.
2271 if (const auto *C = dyn_cast<CallBase>(I))
2272 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
2273 return false;
2274
2275 if (!NumUses)
2276 NumUses = I->getNumUses();
2277 else if (NumUses != I->getNumUses())
2278 return false;
2279 }
2280
2281 const Instruction *I0 = Insts.front();
2282 const auto I0MMRA = MMRAMetadata(*I0);
2283 for (auto *I : Insts) {
2284 if (!I->isSameOperationAs(I0, Instruction::CompareUsingIntersectedAttrs))
2285 return false;
2286
2287 // Treat MMRAs conservatively. This pass can be quite aggressive and
2288 // could drop a lot of MMRAs otherwise.
2289 if (MMRAMetadata(*I) != I0MMRA)
2290 return false;
2291 }
2292
2293 // Uses must be consistent: If I0 is used in a phi node in the sink target,
2294 // then the other phi operands must match the instructions from Insts. This
2295 // also has to hold true for any phi nodes that would be created as a result
2296 // of sinking. Both of these cases are represented by PhiOperands.
2297 for (const Use &U : I0->uses()) {
2298 auto It = PHIOperands.find(&U);
2299 if (It == PHIOperands.end())
2300 // There may be uses in other blocks when sinking into a loop header.
2301 return false;
2302 if (!equal(Insts, It->second))
2303 return false;
2304 }
2305
2306 // For calls to be sinkable, they must all be indirect, or have same callee.
2307 // I.e. if we have two direct calls to different callees, we don't want to
2308 // turn that into an indirect call. Likewise, if we have an indirect call,
2309 // and a direct call, we don't actually want to have a single indirect call.
2310 if (isa<CallBase>(I0)) {
2311 auto IsIndirectCall = [](const Instruction *I) {
2312 return cast<CallBase>(I)->isIndirectCall();
2313 };
2314 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
2315 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
2316 if (HaveIndirectCalls) {
2317 if (!AllCallsAreIndirect)
2318 return false;
2319 } else {
2320 // All callees must be identical.
2321 Value *Callee = nullptr;
2322 for (const Instruction *I : Insts) {
2323 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
2324 if (!Callee)
2325 Callee = CurrCallee;
2326 else if (Callee != CurrCallee)
2327 return false;
2328 }
2329 }
2330 }
2331
2332 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2333 Value *Op = I0->getOperand(OI);
2334 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2335 assert(I->getNumOperands() == I0->getNumOperands());
2336 return I->getOperand(OI) == I0->getOperand(OI);
2337 };
2338 if (!all_of(Insts, SameAsI0)) {
2339 auto CanReplaceOperand = [OI](const Instruction *I) {
2340 return canReplaceOperandWithVariable(I, OI);
2341 };
2343 !all_of(Insts, CanReplaceOperand))
2344 // We can't create a PHI from this operand.
2345 return false;
2346 auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
2347 for (auto *I : Insts)
2348 Ops.push_back(I->getOperand(OI));
2349 }
2350 }
2351 return true;
2352}
2353
2354// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2355// instruction of every block in Blocks to their common successor, commoning
2356// into one instruction.
2358 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
2359
2360 // canSinkInstructions returning true guarantees that every block has at
2361 // least one non-terminator instruction.
2363 for (auto *BB : Blocks) {
2364 Instruction *I = BB->getTerminator();
2365 I = I->getPrevNode();
2366 Insts.push_back(I);
2367 }
2368
2369 // We don't need to do any more checking here; canSinkInstructions should
2370 // have done it all for us.
2371 SmallVector<Value*, 4> NewOperands;
2372 Instruction *I0 = Insts.front();
2373 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2374 // This check is different to that in canSinkInstructions. There, we
2375 // cared about the global view once simplifycfg (and instcombine) have
2376 // completed - it takes into account PHIs that become trivially
2377 // simplifiable. However here we need a more local view; if an operand
2378 // differs we create a PHI and rely on instcombine to clean up the very
2379 // small mess we may make.
2380 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2381 return I->getOperand(O) != I0->getOperand(O);
2382 });
2383 if (!NeedPHI) {
2384 NewOperands.push_back(I0->getOperand(O));
2385 continue;
2386 }
2387
2388 // Create a new PHI in the successor block and populate it.
2389 auto *Op = I0->getOperand(O);
2390 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2391 auto *PN =
2392 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2393 PN->insertBefore(BBEnd->begin());
2394 for (auto *I : Insts)
2395 PN->addIncoming(I->getOperand(O), I->getParent());
2396 NewOperands.push_back(PN);
2397 }
2398
2399 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2400 // and move it to the start of the successor block.
2401 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2402 I0->getOperandUse(O).set(NewOperands[O]);
2403
2404 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2405
2406 // Update metadata and IR flags, and merge debug locations.
2407 for (auto *I : Insts)
2408 if (I != I0) {
2409 // The debug location for the "common" instruction is the merged locations
2410 // of all the commoned instructions. We start with the original location
2411 // of the "common" instruction and iteratively merge each location in the
2412 // loop below.
2413 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2414 // However, as N-way merge for CallInst is rare, so we use simplified API
2415 // instead of using complex API for N-way merge.
2416 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2417 combineMetadataForCSE(I0, I, true);
2418 // We mark branch weights explicitly unknown for select instructions as we
2419 // might be sinking through control flow with conditions not independent
2420 // of the select condition, or pulling multiple conditions together
2421 // through a phi node.
2422 if (auto *SI = dyn_cast<SelectInst>(I0))
2424 I0->andIRFlags(I);
2425 if (auto *CB = dyn_cast<CallBase>(I0)) {
2426 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I));
2427 assert(Success && "We should not be trying to sink callbases "
2428 "with non-intersectable attributes");
2429 // For NDEBUG Compile.
2430 (void)Success;
2431 }
2432 }
2433
2434 for (User *U : make_early_inc_range(I0->users())) {
2435 // canSinkLastInstruction checked that all instructions are only used by
2436 // phi nodes in a way that allows replacing the phi node with the common
2437 // instruction.
2438 auto *PN = cast<PHINode>(U);
2439 PN->replaceAllUsesWith(I0);
2440 PN->eraseFromParent();
2441 }
2442
2443 // Finally nuke all instructions apart from the common instruction.
2444 for (auto *I : Insts) {
2445 if (I == I0)
2446 continue;
2447 // The remaining uses are debug users, replace those with the common inst.
2448 // In most (all?) cases this just introduces a use-before-def.
2449 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2450 I->replaceAllUsesWith(I0);
2451 I->eraseFromParent();
2452 }
2453}
2454
2455/// Check whether BB's predecessors end with unconditional branches. If it is
2456/// true, sink any common code from the predecessors to BB.
2458 DomTreeUpdater *DTU) {
2459 // We support two situations:
2460 // (1) all incoming arcs are unconditional
2461 // (2) there are non-unconditional incoming arcs
2462 //
2463 // (2) is very common in switch defaults and
2464 // else-if patterns;
2465 //
2466 // if (a) f(1);
2467 // else if (b) f(2);
2468 //
2469 // produces:
2470 //
2471 // [if]
2472 // / \
2473 // [f(1)] [if]
2474 // | | \
2475 // | | |
2476 // | [f(2)]|
2477 // \ | /
2478 // [ end ]
2479 //
2480 // [end] has two unconditional predecessor arcs and one conditional. The
2481 // conditional refers to the implicit empty 'else' arc. This conditional
2482 // arc can also be caused by an empty default block in a switch.
2483 //
2484 // In this case, we attempt to sink code from all *unconditional* arcs.
2485 // If we can sink instructions from these arcs (determined during the scan
2486 // phase below) we insert a common successor for all unconditional arcs and
2487 // connect that to [end], to enable sinking:
2488 //
2489 // [if]
2490 // / \
2491 // [x(1)] [if]
2492 // | | \
2493 // | | \
2494 // | [x(2)] |
2495 // \ / |
2496 // [sink.split] |
2497 // \ /
2498 // [ end ]
2499 //
2500 SmallVector<BasicBlock*,4> UnconditionalPreds;
2501 bool HaveNonUnconditionalPredecessors = false;
2502 for (auto *PredBB : predecessors(BB)) {
2503 auto *PredBr = dyn_cast<UncondBrInst>(PredBB->getTerminator());
2504 if (PredBr)
2505 UnconditionalPreds.push_back(PredBB);
2506 else
2507 HaveNonUnconditionalPredecessors = true;
2508 }
2509 if (UnconditionalPreds.size() < 2)
2510 return false;
2511
2512 // We take a two-step approach to tail sinking. First we scan from the end of
2513 // each block upwards in lockstep. If the n'th instruction from the end of each
2514 // block can be sunk, those instructions are added to ValuesToSink and we
2515 // carry on. If we can sink an instruction but need to PHI-merge some operands
2516 // (because they're not identical in each instruction) we add these to
2517 // PHIOperands.
2518 // We prepopulate PHIOperands with the phis that already exist in BB.
2520 for (PHINode &PN : BB->phis()) {
2522 for (const Use &U : PN.incoming_values())
2523 IncomingVals.insert({PN.getIncomingBlock(U), &U});
2524 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2525 for (BasicBlock *Pred : UnconditionalPreds)
2526 Ops.push_back(*IncomingVals[Pred]);
2527 }
2528
2529 int ScanIdx = 0;
2530 SmallPtrSet<Value*,4> InstructionsToSink;
2531 LockstepReverseIterator<true> LRI(UnconditionalPreds);
2532 while (LRI.isValid() &&
2533 canSinkInstructions(*LRI, PHIOperands)) {
2534 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2535 << "\n");
2536 InstructionsToSink.insert_range(*LRI);
2537 ++ScanIdx;
2538 --LRI;
2539 }
2540
2541 // If no instructions can be sunk, early-return.
2542 if (ScanIdx == 0)
2543 return false;
2544
2545 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2546
2547 if (!followedByDeoptOrUnreachable) {
2548 // Check whether this is the pointer operand of a load/store.
2549 auto IsMemOperand = [](Use &U) {
2550 auto *I = cast<Instruction>(U.getUser());
2551 if (isa<LoadInst>(I))
2552 return U.getOperandNo() == LoadInst::getPointerOperandIndex();
2553 if (isa<StoreInst>(I))
2554 return U.getOperandNo() == StoreInst::getPointerOperandIndex();
2555 return false;
2556 };
2557
2558 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2559 // actually sink before encountering instruction that is unprofitable to
2560 // sink?
2561 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator<true> &LRI) {
2562 unsigned NumPHIInsts = 0;
2563 for (Use &U : (*LRI)[0]->operands()) {
2564 auto It = PHIOperands.find(&U);
2565 if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2566 return InstructionsToSink.contains(V);
2567 })) {
2568 ++NumPHIInsts;
2569 // Do not separate a load/store from the gep producing the address.
2570 // The gep can likely be folded into the load/store as an addressing
2571 // mode. Additionally, a load of a gep is easier to analyze than a
2572 // load of a phi.
2573 if (IsMemOperand(U) &&
2574 any_of(It->second, [](Value *V) { return isa<GEPOperator>(V); }))
2575 return false;
2576 // FIXME: this check is overly optimistic. We may end up not sinking
2577 // said instruction, due to the very same profitability check.
2578 // See @creating_too_many_phis in sink-common-code.ll.
2579 }
2580 }
2581 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2582 return NumPHIInsts <= 1;
2583 };
2584
2585 // We've determined that we are going to sink last ScanIdx instructions,
2586 // and recorded them in InstructionsToSink. Now, some instructions may be
2587 // unprofitable to sink. But that determination depends on the instructions
2588 // that we are going to sink.
2589
2590 // First, forward scan: find the first instruction unprofitable to sink,
2591 // recording all the ones that are profitable to sink.
2592 // FIXME: would it be better, after we detect that not all are profitable.
2593 // to either record the profitable ones, or erase the unprofitable ones?
2594 // Maybe we need to choose (at runtime) the one that will touch least
2595 // instrs?
2596 LRI.reset();
2597 int Idx = 0;
2598 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2599 while (Idx < ScanIdx) {
2600 if (!ProfitableToSinkInstruction(LRI)) {
2601 // Too many PHIs would be created.
2602 LLVM_DEBUG(
2603 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2604 break;
2605 }
2606 InstructionsProfitableToSink.insert_range(*LRI);
2607 --LRI;
2608 ++Idx;
2609 }
2610
2611 // If no instructions can be sunk, early-return.
2612 if (Idx == 0)
2613 return false;
2614
2615 // Did we determine that (only) some instructions are unprofitable to sink?
2616 if (Idx < ScanIdx) {
2617 // Okay, some instructions are unprofitable.
2618 ScanIdx = Idx;
2619 InstructionsToSink = InstructionsProfitableToSink;
2620
2621 // But, that may make other instructions unprofitable, too.
2622 // So, do a backward scan, do any earlier instructions become
2623 // unprofitable?
2624 assert(
2625 !ProfitableToSinkInstruction(LRI) &&
2626 "We already know that the last instruction is unprofitable to sink");
2627 ++LRI;
2628 --Idx;
2629 while (Idx >= 0) {
2630 // If we detect that an instruction becomes unprofitable to sink,
2631 // all earlier instructions won't be sunk either,
2632 // so preemptively keep InstructionsProfitableToSink in sync.
2633 // FIXME: is this the most performant approach?
2634 for (auto *I : *LRI)
2635 InstructionsProfitableToSink.erase(I);
2636 if (!ProfitableToSinkInstruction(LRI)) {
2637 // Everything starting with this instruction won't be sunk.
2638 ScanIdx = Idx;
2639 InstructionsToSink = InstructionsProfitableToSink;
2640 }
2641 ++LRI;
2642 --Idx;
2643 }
2644 }
2645
2646 // If no instructions can be sunk, early-return.
2647 if (ScanIdx == 0)
2648 return false;
2649 }
2650
2651 bool Changed = false;
2652
2653 if (HaveNonUnconditionalPredecessors) {
2654 if (!followedByDeoptOrUnreachable) {
2655 // It is always legal to sink common instructions from unconditional
2656 // predecessors. However, if not all predecessors are unconditional,
2657 // this transformation might be pessimizing. So as a rule of thumb,
2658 // don't do it unless we'd sink at least one non-speculatable instruction.
2659 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2660 LRI.reset();
2661 int Idx = 0;
2662 bool Profitable = false;
2663 while (Idx < ScanIdx) {
2664 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2665 Profitable = true;
2666 break;
2667 }
2668 --LRI;
2669 ++Idx;
2670 }
2671 if (!Profitable)
2672 return false;
2673 }
2674
2675 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2676 // We have a conditional edge and we're going to sink some instructions.
2677 // Insert a new block postdominating all blocks we're going to sink from.
2678 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2679 // Edges couldn't be split.
2680 return false;
2681 Changed = true;
2682 }
2683
2684 // Now that we've analyzed all potential sinking candidates, perform the
2685 // actual sink. We iteratively sink the last non-terminator of the source
2686 // blocks into their common successor unless doing so would require too
2687 // many PHI instructions to be generated (currently only one PHI is allowed
2688 // per sunk instruction).
2689 //
2690 // We can use InstructionsToSink to discount values needing PHI-merging that will
2691 // actually be sunk in a later iteration. This allows us to be more
2692 // aggressive in what we sink. This does allow a false positive where we
2693 // sink presuming a later value will also be sunk, but stop half way through
2694 // and never actually sink it which means we produce more PHIs than intended.
2695 // This is unlikely in practice though.
2696 int SinkIdx = 0;
2697 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2698 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2699 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2700 << "\n");
2701
2702 // Because we've sunk every instruction in turn, the current instruction to
2703 // sink is always at index 0.
2704 LRI.reset();
2705
2706 sinkLastInstruction(UnconditionalPreds);
2707 NumSinkCommonInstrs++;
2708 Changed = true;
2709 }
2710 if (SinkIdx != 0)
2711 ++NumSinkCommonCode;
2712 return Changed;
2713}
2714
2715namespace {
2716
2717struct CompatibleSets {
2718 using SetTy = SmallVector<InvokeInst *, 2>;
2719
2721
2722 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2723
2724 SetTy &getCompatibleSet(InvokeInst *II);
2725
2726 void insert(InvokeInst *II);
2727};
2728
2729CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2730 // Perform a linear scan over all the existing sets, see if the new `invoke`
2731 // is compatible with any particular set. Since we know that all the `invokes`
2732 // within a set are compatible, only check the first `invoke` in each set.
2733 // WARNING: at worst, this has quadratic complexity.
2734 for (CompatibleSets::SetTy &Set : Sets) {
2735 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2736 return Set;
2737 }
2738
2739 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2740 return Sets.emplace_back();
2741}
2742
2743void CompatibleSets::insert(InvokeInst *II) {
2744 getCompatibleSet(II).emplace_back(II);
2745}
2746
2747bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2748 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2749
2750 // Can we theoretically merge these `invoke`s?
2751 auto IsIllegalToMerge = [](InvokeInst *II) {
2752 return II->cannotMerge() || II->isInlineAsm();
2753 };
2754 if (any_of(Invokes, IsIllegalToMerge))
2755 return false;
2756
2757 // Either both `invoke`s must be direct,
2758 // or both `invoke`s must be indirect.
2759 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2760 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2761 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2762 if (HaveIndirectCalls) {
2763 if (!AllCallsAreIndirect)
2764 return false;
2765 } else {
2766 // All callees must be identical.
2767 Value *Callee = nullptr;
2768 for (InvokeInst *II : Invokes) {
2769 Value *CurrCallee = II->getCalledOperand();
2770 assert(CurrCallee && "There is always a called operand.");
2771 if (!Callee)
2772 Callee = CurrCallee;
2773 else if (Callee != CurrCallee)
2774 return false;
2775 }
2776 }
2777
2778 // Either both `invoke`s must not have a normal destination,
2779 // or both `invoke`s must have a normal destination,
2780 auto HasNormalDest = [](InvokeInst *II) {
2781 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIIt());
2782 };
2783 if (any_of(Invokes, HasNormalDest)) {
2784 // Do not merge `invoke` that does not have a normal destination with one
2785 // that does have a normal destination, even though doing so would be legal.
2786 if (!all_of(Invokes, HasNormalDest))
2787 return false;
2788
2789 // All normal destinations must be identical.
2790 BasicBlock *NormalBB = nullptr;
2791 for (InvokeInst *II : Invokes) {
2792 BasicBlock *CurrNormalBB = II->getNormalDest();
2793 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2794 if (!NormalBB)
2795 NormalBB = CurrNormalBB;
2796 else if (NormalBB != CurrNormalBB)
2797 return false;
2798 }
2799
2800 // In the normal destination, the incoming values for these two `invoke`s
2801 // must be compatible.
2802 SmallPtrSet<Value *, 16> EquivalenceSet(llvm::from_range, Invokes);
2804 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2805 &EquivalenceSet))
2806 return false;
2807 }
2808
2809#ifndef NDEBUG
2810 // All unwind destinations must be identical.
2811 // We know that because we have started from said unwind destination.
2812 BasicBlock *UnwindBB = nullptr;
2813 for (InvokeInst *II : Invokes) {
2814 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2815 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2816 if (!UnwindBB)
2817 UnwindBB = CurrUnwindBB;
2818 else
2819 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2820 }
2821#endif
2822
2823 // In the unwind destination, the incoming values for these two `invoke`s
2824 // must be compatible.
2826 Invokes.front()->getUnwindDest(),
2827 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2828 return false;
2829
2830 // Ignoring arguments, these `invoke`s must be identical,
2831 // including operand bundles.
2832 const InvokeInst *II0 = Invokes.front();
2833 for (auto *II : Invokes.drop_front())
2834 if (!II->isSameOperationAs(II0, Instruction::CompareUsingIntersectedAttrs))
2835 return false;
2836
2837 // Can we theoretically form the data operands for the merged `invoke`?
2838 auto IsIllegalToMergeArguments = [](auto Ops) {
2839 Use &U0 = std::get<0>(Ops);
2840 Use &U1 = std::get<1>(Ops);
2841 if (U0 == U1)
2842 return false;
2844 U0.getOperandNo());
2845 };
2846 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2847 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2848 IsIllegalToMergeArguments))
2849 return false;
2850
2851 return true;
2852}
2853
2854} // namespace
2855
2856// Merge all invokes in the provided set, all of which are compatible
2857// as per the `CompatibleSets::shouldBelongToSameSet()`.
2859 DomTreeUpdater *DTU) {
2860 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2861
2863 if (DTU)
2864 Updates.reserve(2 + 3 * Invokes.size());
2865
2866 bool HasNormalDest =
2867 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIIt());
2868
2869 // Clone one of the invokes into a new basic block.
2870 // Since they are all compatible, it doesn't matter which invoke is cloned.
2871 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2872 InvokeInst *II0 = Invokes.front();
2873 BasicBlock *II0BB = II0->getParent();
2874 BasicBlock *InsertBeforeBlock =
2875 II0->getParent()->getIterator()->getNextNode();
2876 Function *Func = II0BB->getParent();
2877 LLVMContext &Ctx = II0->getContext();
2878
2879 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2880 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2881
2882 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2883 // NOTE: all invokes have the same attributes, so no handling needed.
2884 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2885
2886 if (!HasNormalDest) {
2887 // This set does not have a normal destination,
2888 // so just form a new block with unreachable terminator.
2889 BasicBlock *MergedNormalDest = BasicBlock::Create(
2890 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2891 auto *UI = new UnreachableInst(Ctx, MergedNormalDest);
2892 UI->setDebugLoc(DebugLoc::getTemporary());
2893 MergedInvoke->setNormalDest(MergedNormalDest);
2894 }
2895
2896 // The unwind destination, however, remainds identical for all invokes here.
2897
2898 return MergedInvoke;
2899 }();
2900
2901 if (DTU) {
2902 // Predecessor blocks that contained these invokes will now branch to
2903 // the new block that contains the merged invoke, ...
2904 for (InvokeInst *II : Invokes)
2905 Updates.push_back(
2906 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2907
2908 // ... which has the new `unreachable` block as normal destination,
2909 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2910 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2911 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2912 SuccBBOfMergedInvoke});
2913
2914 // Since predecessor blocks now unconditionally branch to a new block,
2915 // they no longer branch to their original successors.
2916 for (InvokeInst *II : Invokes)
2917 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2918 Updates.push_back(
2919 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2920 }
2921
2922 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2923
2924 // Form the merged operands for the merged invoke.
2925 for (Use &U : MergedInvoke->operands()) {
2926 // Only PHI together the indirect callees and data operands.
2927 if (MergedInvoke->isCallee(&U)) {
2928 if (!IsIndirectCall)
2929 continue;
2930 } else if (!MergedInvoke->isDataOperand(&U))
2931 continue;
2932
2933 // Don't create trivial PHI's with all-identical incoming values.
2934 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2935 return II->getOperand(U.getOperandNo()) != U.get();
2936 });
2937 if (!NeedPHI)
2938 continue;
2939
2940 // Form a PHI out of all the data ops under this index.
2942 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
2943 for (InvokeInst *II : Invokes)
2944 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2945
2946 U.set(PN);
2947 }
2948
2949 // We've ensured that each PHI node has compatible (identical) incoming values
2950 // when coming from each of the `invoke`s in the current merge set,
2951 // so update the PHI nodes accordingly.
2952 for (BasicBlock *Succ : successors(MergedInvoke))
2953 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2954 /*ExistPred=*/Invokes.front()->getParent());
2955
2956 // And finally, replace the original `invoke`s with an unconditional branch
2957 // to the block with the merged `invoke`. Also, give that merged `invoke`
2958 // the merged debugloc of all the original `invoke`s.
2959 DILocation *MergedDebugLoc = nullptr;
2960 for (InvokeInst *II : Invokes) {
2961 // Compute the debug location common to all the original `invoke`s.
2962 if (!MergedDebugLoc)
2963 MergedDebugLoc = II->getDebugLoc();
2964 else
2965 MergedDebugLoc =
2966 DebugLoc::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2967
2968 // And replace the old `invoke` with an unconditionally branch
2969 // to the block with the merged `invoke`.
2970 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2971 OrigSuccBB->removePredecessor(II->getParent());
2972 auto *BI = UncondBrInst::Create(MergedInvoke->getParent(), II->getParent());
2973 // The unconditional branch is part of the replacement for the original
2974 // invoke, so should use its DebugLoc.
2975 BI->setDebugLoc(II->getDebugLoc());
2976 bool Success = MergedInvoke->tryIntersectAttributes(II);
2977 assert(Success && "Merged invokes with incompatible attributes");
2978 // For NDEBUG Compile
2979 (void)Success;
2980 II->replaceAllUsesWith(MergedInvoke);
2981 II->eraseFromParent();
2982 ++NumInvokesMerged;
2983 }
2984 MergedInvoke->setDebugLoc(MergedDebugLoc);
2985 ++NumInvokeSetsFormed;
2986
2987 if (DTU)
2988 DTU->applyUpdates(Updates);
2989}
2990
2991/// If this block is a `landingpad` exception handling block, categorize all
2992/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2993/// being "mergeable" together, and then merge invokes in each set together.
2994///
2995/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2996/// [...] [...]
2997/// | |
2998/// [invoke0] [invoke1]
2999/// / \ / \
3000/// [cont0] [landingpad] [cont1]
3001/// to:
3002/// [...] [...]
3003/// \ /
3004/// [invoke]
3005/// / \
3006/// [cont] [landingpad]
3007///
3008/// But of course we can only do that if the invokes share the `landingpad`,
3009/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
3010/// and the invoked functions are "compatible".
3013 return false;
3014
3015 bool Changed = false;
3016
3017 // FIXME: generalize to all exception handling blocks?
3018 if (!BB->isLandingPad())
3019 return Changed;
3020
3021 CompatibleSets Grouper;
3022
3023 // Record all the predecessors of this `landingpad`. As per verifier,
3024 // the only allowed predecessor is the unwind edge of an `invoke`.
3025 // We want to group "compatible" `invokes` into the same set to be merged.
3026 for (BasicBlock *PredBB : predecessors(BB))
3027 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
3028
3029 // And now, merge `invoke`s that were grouped togeter.
3030 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
3031 if (Invokes.size() < 2)
3032 continue;
3033 Changed = true;
3034 mergeCompatibleInvokesImpl(Invokes, DTU);
3035 }
3036
3037 return Changed;
3038}
3039
3040namespace {
3041/// Track ephemeral values, which should be ignored for cost-modelling
3042/// purposes. Requires walking instructions in reverse order.
3043class EphemeralValueTracker {
3044 SmallPtrSet<const Instruction *, 32> EphValues;
3045
3046 bool isEphemeral(const Instruction *I) {
3047 if (isa<AssumeInst>(I))
3048 return true;
3049 return !I->mayHaveSideEffects() && !I->isTerminator() &&
3050 all_of(I->users(), [&](const User *U) {
3051 return EphValues.count(cast<Instruction>(U));
3052 });
3053 }
3054
3055public:
3056 bool track(const Instruction *I) {
3057 if (isEphemeral(I)) {
3058 EphValues.insert(I);
3059 return true;
3060 }
3061 return false;
3062 }
3063
3064 bool contains(const Instruction *I) const { return EphValues.contains(I); }
3065};
3066} // namespace
3067
3068/// Determine if we can hoist sink a sole store instruction out of a
3069/// conditional block.
3070///
3071/// We are looking for code like the following:
3072/// BrBB:
3073/// store i32 %add, i32* %arrayidx2
3074/// ... // No other stores or function calls (we could be calling a memory
3075/// ... // function).
3076/// %cmp = icmp ult %x, %y
3077/// br i1 %cmp, label %EndBB, label %ThenBB
3078/// ThenBB:
3079/// store i32 %add5, i32* %arrayidx2
3080/// br label EndBB
3081/// EndBB:
3082/// ...
3083/// We are going to transform this into:
3084/// BrBB:
3085/// store i32 %add, i32* %arrayidx2
3086/// ... //
3087/// %cmp = icmp ult %x, %y
3088/// %add.add5 = select i1 %cmp, i32 %add, %add5
3089/// store i32 %add.add5, i32* %arrayidx2
3090/// ...
3091///
3092/// \return The value from the previous access if the store can be hoisted into
3093/// the predecessor block. PreviousAccess is set to that access. Return
3094/// null otherwise.
3096 BasicBlock *StoreBB, BasicBlock *EndBB,
3097 Instruction *&PreviousAccess) {
3098 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
3099 if (!StoreToHoist)
3100 return nullptr;
3101
3102 // Volatile or atomic.
3103 if (!StoreToHoist->isSimple())
3104 return nullptr;
3105
3106 Value *StorePtr = StoreToHoist->getPointerOperand();
3107 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
3108
3109 // Look for a store to the same pointer in BrBB.
3110 unsigned MaxNumInstToLookAt = 9;
3111 // Skip pseudo probe intrinsic calls which are not really killing any memory
3112 // accesses.
3113 for (Instruction &CurI : reverse(*BrBB)) {
3114 if (!MaxNumInstToLookAt)
3115 break;
3116 --MaxNumInstToLookAt;
3117
3118 if (isa<PseudoProbeInst>(CurI))
3119 continue;
3120
3121 // Could be calling an instruction that affects memory like free().
3122 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
3123 return nullptr;
3124
3125 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
3126 // Found the previous store to same location and type. Make sure it is
3127 // simple, to avoid introducing a spurious non-atomic write after an
3128 // atomic write.
3129 if (SI->getPointerOperand() == StorePtr &&
3130 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
3131 SI->getAlign() >= StoreToHoist->getAlign()) {
3132 // Found the previous store, return its value operand.
3133 PreviousAccess = SI;
3134 return SI->getValueOperand();
3135 }
3136 return nullptr; // Unknown store.
3137 }
3138
3139 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
3140 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
3141 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
3142 Value *Obj = getUnderlyingObject(StorePtr);
3143 bool ExplicitlyDereferenceableOnly;
3144 // The dereferenceability query here is only required to satisfy the
3145 // writable contract, actual dereferenceability is proven by the
3146 // presence of an access. As such, we can ignore frees.
3147 if (isWritableObject(Obj, ExplicitlyDereferenceableOnly) &&
3150 .WithoutRet) &&
3151 (!ExplicitlyDereferenceableOnly ||
3152 isDereferenceablePointer(StorePtr, StoreTy, LI->getDataLayout(),
3153 /*IgnoreFree=*/true))) {
3154 // Found a previous load, return it.
3155 PreviousAccess = LI;
3156 return LI;
3157 }
3158 }
3159 // The load didn't work out, but we may still find a store.
3160 }
3161 }
3162
3163 return nullptr;
3164}
3165
3166/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
3167/// converted to selects.
3169 BasicBlock *EndBB,
3170 unsigned &SpeculatedInstructions,
3171 InstructionCost &Cost,
3172 const TargetTransformInfo &TTI) {
3174 BB->getParent()->hasMinSize()
3177
3178 bool HaveRewritablePHIs = false;
3179 for (PHINode &PN : EndBB->phis()) {
3180 Value *OrigV = PN.getIncomingValueForBlock(BB);
3181 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
3182
3183 // FIXME: Try to remove some of the duplication with
3184 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
3185 if (ThenV == OrigV)
3186 continue;
3187
3188 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(),
3189 Type::getInt1Ty(PN.getContext()),
3190 CmpInst::BAD_ICMP_PREDICATE, CostKind);
3191
3192 // Don't convert to selects if we could remove undefined behavior instead.
3193 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
3195 return false;
3196
3197 HaveRewritablePHIs = true;
3198 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
3199 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
3200 if (!OrigCE && !ThenCE)
3201 continue; // Known cheap (FIXME: Maybe not true for aggregates).
3202
3203 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
3204 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
3205 InstructionCost MaxCost =
3207 if (OrigCost + ThenCost > MaxCost)
3208 return false;
3209
3210 // Account for the cost of an unfolded ConstantExpr which could end up
3211 // getting expanded into Instructions.
3212 // FIXME: This doesn't account for how many operations are combined in the
3213 // constant expression.
3214 ++SpeculatedInstructions;
3215 if (SpeculatedInstructions > 1)
3216 return false;
3217 }
3218
3219 return HaveRewritablePHIs;
3220}
3221
3223 std::optional<bool> Invert,
3224 const TargetTransformInfo &TTI) {
3225 // If the branch is non-unpredictable, and is predicted to *not* branch to
3226 // the `then` block, then avoid speculating it.
3227 if (BI->getMetadata(LLVMContext::MD_unpredictable))
3228 return true;
3229
3230 uint64_t TWeight, FWeight;
3231 if (!extractBranchWeights(*BI, TWeight, FWeight) || (TWeight + FWeight) == 0)
3232 return true;
3233
3234 if (!Invert.has_value())
3235 return false;
3236
3237 uint64_t EndWeight = *Invert ? TWeight : FWeight;
3238 BranchProbability BIEndProb =
3239 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
3240 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3241 return BIEndProb < Likely;
3242}
3243
3244/// Speculate a conditional basic block flattening the CFG.
3245///
3246/// Note that this is a very risky transform currently. Speculating
3247/// instructions like this is most often not desirable. Instead, there is an MI
3248/// pass which can do it with full awareness of the resource constraints.
3249/// However, some cases are "obvious" and we should do directly. An example of
3250/// this is speculating a single, reasonably cheap instruction.
3251///
3252/// There is only one distinct advantage to flattening the CFG at the IR level:
3253/// it makes very common but simplistic optimizations such as are common in
3254/// instcombine and the DAG combiner more powerful by removing CFG edges and
3255/// modeling their effects with easier to reason about SSA value graphs.
3256///
3257///
3258/// An illustration of this transform is turning this IR:
3259/// \code
3260/// BB:
3261/// %cmp = icmp ult %x, %y
3262/// br i1 %cmp, label %EndBB, label %ThenBB
3263/// ThenBB:
3264/// %sub = sub %x, %y
3265/// br label BB2
3266/// EndBB:
3267/// %phi = phi [ %sub, %ThenBB ], [ 0, %BB ]
3268/// ...
3269/// \endcode
3270///
3271/// Into this IR:
3272/// \code
3273/// BB:
3274/// %cmp = icmp ult %x, %y
3275/// %sub = sub %x, %y
3276/// %cond = select i1 %cmp, 0, %sub
3277/// ...
3278/// \endcode
3279///
3280/// \returns true if the conditional block is removed.
3281bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
3282 BasicBlock *ThenBB) {
3283 if (!Options.SpeculateBlocks)
3284 return false;
3285
3286 BasicBlock *BB = BI->getParent();
3287 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
3288 InstructionCost Budget =
3290
3291 // If ThenBB is actually on the false edge of the conditional branch, remember
3292 // to swap the select operands later.
3293 bool Invert = false;
3294 if (ThenBB != BI->getSuccessor(0)) {
3295 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3296 Invert = true;
3297 }
3298 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3299
3300 if (!isProfitableToSpeculate(BI, Invert, TTI))
3301 return false;
3302
3303 // Keep a count of how many times instructions are used within ThenBB when
3304 // they are candidates for sinking into ThenBB. Specifically:
3305 // - They are defined in BB, and
3306 // - They have no side effects, and
3307 // - All of their uses are in ThenBB.
3308 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3309
3310 SmallVector<Instruction *, 4> SpeculatedPseudoProbes;
3311
3312 unsigned SpeculatedInstructions = 0;
3313 bool HoistLoadsStores = Options.HoistLoadsStoresWithCondFaulting;
3314 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
3315 Value *SpeculatedStoreValue = nullptr;
3316 StoreInst *SpeculatedStore = nullptr;
3317 Instruction *PreviousStoreAccess = nullptr;
3318 EphemeralValueTracker EphTracker;
3319 for (Instruction &I : reverse(drop_end(*ThenBB))) {
3320 // Skip pseudo probes. The consequence is we lose track of the branch
3321 // probability for ThenBB, which is fine since the optimization here takes
3322 // place regardless of the branch probability.
3323 if (isa<PseudoProbeInst>(I)) {
3324 // The probe should be deleted so that it will not be over-counted when
3325 // the samples collected on the non-conditional path are counted towards
3326 // the conditional path. We leave it for the counts inference algorithm to
3327 // figure out a proper count for an unknown probe.
3328 SpeculatedPseudoProbes.push_back(&I);
3329 continue;
3330 }
3331
3332 // Ignore ephemeral values, they will be dropped by the transform.
3333 if (EphTracker.track(&I))
3334 continue;
3335
3336 // Only speculatively execute a single instruction (not counting the
3337 // terminator) for now.
3338 bool IsSafeCheapLoadStore = HoistLoadsStores &&
3340 SpeculatedConditionalLoadsStores.size() <
3342 // Not count load/store into cost if target supports conditional faulting
3343 // b/c it's cheap to speculate it.
3344 if (IsSafeCheapLoadStore)
3345 SpeculatedConditionalLoadsStores.push_back(&I);
3346 else
3347 ++SpeculatedInstructions;
3348
3349 if (SpeculatedInstructions > 1)
3350 return false;
3351
3352 // Don't hoist the instruction if it's unsafe or expensive.
3353 if (!IsSafeCheapLoadStore &&
3355 !(HoistCondStores && !SpeculatedStoreValue &&
3356 (SpeculatedStoreValue = isSafeToSpeculateStore(&I, BB, ThenBB, EndBB,
3357 PreviousStoreAccess))))
3358 return false;
3359 if (!IsSafeCheapLoadStore && !SpeculatedStoreValue &&
3362 return false;
3363
3364 // Store the store speculation candidate.
3365 if (!SpeculatedStore && SpeculatedStoreValue)
3366 SpeculatedStore = cast<StoreInst>(&I);
3367
3368 // Do not hoist the instruction if any of its operands are defined but not
3369 // used in BB. The transformation will prevent the operand from
3370 // being sunk into the use block.
3371 for (Use &Op : I.operands()) {
3373 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3374 continue; // Not a candidate for sinking.
3375
3376 ++SinkCandidateUseCounts[OpI];
3377 }
3378 }
3379
3380 // Consider any sink candidates which are only used in ThenBB as costs for
3381 // speculation. Note, while we iterate over a DenseMap here, we are summing
3382 // and so iteration order isn't significant.
3383 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3384 if (Inst->hasNUses(Count)) {
3385 ++SpeculatedInstructions;
3386 if (SpeculatedInstructions > 1)
3387 return false;
3388 }
3389
3390 // Check that we can insert the selects and that it's not too expensive to do
3391 // so.
3392 bool Convert =
3393 SpeculatedStore != nullptr || !SpeculatedConditionalLoadsStores.empty();
3395 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3396 SpeculatedInstructions, Cost, TTI);
3397 if (!Convert || Cost > Budget)
3398 return false;
3399
3400 // If we get here, we can hoist the instruction and if-convert.
3401 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3402
3403 Instruction *Sel = nullptr;
3404 Value *BrCond = BI->getCondition();
3405 // Insert a select of the value of the speculated store.
3406 if (SpeculatedStoreValue) {
3407 IRBuilder<NoFolder> Builder(BI);
3408 Value *OrigV = SpeculatedStore->getValueOperand();
3409 Value *TrueV = SpeculatedStore->getValueOperand();
3410 Value *FalseV = SpeculatedStoreValue;
3411 if (Invert)
3412 std::swap(TrueV, FalseV);
3413 Value *S = Builder.CreateSelect(
3414 BrCond, TrueV, FalseV, "spec.store.select", BI);
3415 Sel = cast<Instruction>(S);
3416 SpeculatedStore->setOperand(0, S);
3417 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3418 SpeculatedStore->getDebugLoc());
3419 // The value stored is still conditional, but the store itself is now
3420 // unconditionally executed, so we must be sure that any linked dbg.assign
3421 // intrinsics are tracking the new stored value (the result of the
3422 // select). If we don't, and the store were to be removed by another pass
3423 // (e.g. DSE), then we'd eventually end up emitting a location describing
3424 // the conditional value, unconditionally.
3425 //
3426 // === Before this transformation ===
3427 // pred:
3428 // store %one, %x.dest, !DIAssignID !1
3429 // dbg.assign %one, "x", ..., !1, ...
3430 // br %cond if.then
3431 //
3432 // if.then:
3433 // store %two, %x.dest, !DIAssignID !2
3434 // dbg.assign %two, "x", ..., !2, ...
3435 //
3436 // === After this transformation ===
3437 // pred:
3438 // store %one, %x.dest, !DIAssignID !1
3439 // dbg.assign %one, "x", ..., !1
3440 /// ...
3441 // %merge = select %cond, %two, %one
3442 // store %merge, %x.dest, !DIAssignID !2
3443 // dbg.assign %merge, "x", ..., !2
3444 for (DbgVariableRecord *DbgAssign :
3445 at::getDVRAssignmentMarkers(SpeculatedStore))
3446 if (llvm::is_contained(DbgAssign->location_ops(), OrigV))
3447 DbgAssign->replaceVariableLocationOp(OrigV, S);
3448 }
3449
3450 // Metadata can be dependent on the condition we are hoisting above.
3451 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3452 // to avoid making it appear as if the condition is a constant, which would
3453 // be misleading while debugging.
3454 // Similarly strip attributes that maybe dependent on condition we are
3455 // hoisting above.
3456 for (auto &I : make_early_inc_range(*ThenBB)) {
3457 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3458 I.dropLocation();
3459 I.dropUBImplyingAttrsAndMetadata();
3460 } else {
3461 assert(PreviousStoreAccess && "Missing previous store access");
3462 AAMDNodes MergedAA = SpeculatedStore->getAAMetadata().merge(
3463 PreviousStoreAccess->getAAMetadata());
3464 I.dropUBImplyingAttrsAndMetadata();
3465 I.setAAMetadata(MergedAA);
3466 }
3467
3468 // Drop ephemeral values.
3469 if (EphTracker.contains(&I)) {
3470 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3471 I.eraseFromParent();
3472 }
3473 }
3474
3475 // Hoist the instructions.
3476 // Drop DbgVariableRecords attached to these instructions.
3477 for (auto &It : *ThenBB)
3478 for (DbgRecord &DR : make_early_inc_range(It.getDbgRecordRange()))
3479 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3480 // equivalent).
3481 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
3482 !DVR || !DVR->isDbgAssign())
3483 It.dropOneDbgRecord(&DR);
3484 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3485 std::prev(ThenBB->end()));
3486
3487 if (!SpeculatedConditionalLoadsStores.empty())
3488 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores, Invert,
3489 Sel);
3490
3491 // Insert selects and rewrite the PHI operands.
3492 IRBuilder<NoFolder> Builder(BI);
3493 for (PHINode &PN : EndBB->phis()) {
3494 unsigned OrigI = PN.getBasicBlockIndex(BB);
3495 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3496 Value *OrigV = PN.getIncomingValue(OrigI);
3497 Value *ThenV = PN.getIncomingValue(ThenI);
3498
3499 // Skip PHIs which are trivial.
3500 if (OrigV == ThenV)
3501 continue;
3502
3503 // Create a select whose true value is the speculatively executed value and
3504 // false value is the pre-existing value. Swap them if the branch
3505 // destinations were inverted.
3506 Value *TrueV = ThenV, *FalseV = OrigV;
3507 if (Invert)
3508 std::swap(TrueV, FalseV);
3509 // Propagate fast-math flags from the phi node to the replacement select.
3510 Value *V = Builder.CreateSelectFMF(
3511 BrCond, TrueV, FalseV, PN.getFastMathFlagsOrNone(), "spec.select", BI);
3512 PN.setIncomingValue(OrigI, V);
3513 PN.setIncomingValue(ThenI, V);
3514 }
3515
3516 // Remove speculated pseudo probes.
3517 for (Instruction *I : SpeculatedPseudoProbes)
3518 I->eraseFromParent();
3519
3520 ++NumSpeculations;
3521 return true;
3522}
3523
3525
3526// Return false if number of blocks searched is too much.
3527static bool findReaching(BasicBlock *BB, BasicBlock *DefBB,
3528 BlocksSet &ReachesNonLocalUses) {
3529 if (BB == DefBB)
3530 return true;
3531 if (!ReachesNonLocalUses.insert(BB).second)
3532 return true;
3533
3534 if (ReachesNonLocalUses.size() > MaxJumpThreadingLiveBlocks)
3535 return false;
3536 for (BasicBlock *Pred : predecessors(BB))
3537 if (!findReaching(Pred, DefBB, ReachesNonLocalUses))
3538 return false;
3539 return true;
3540}
3541
3542/// Return true if threading \p PredBBs through \p Header to \p RealDest
3543/// eliminates the loop's single backedge. \p Header must have two predecessors
3544/// (one entry and one backedge), the threaded predecessor must be dominated by
3545/// \p Header, and \p RealDest must not reach it without passing through
3546/// \p Header.
3548 ArrayRef<BasicBlock *> PredBBs,
3549 BasicBlock *RealDest) {
3550 if (!Header->hasNPredecessors(2))
3551 return false;
3552 BlocksSet Visited;
3553 SmallVector<BasicBlock *, 8> Worklist(PredBBs);
3554 while (!Worklist.empty()) {
3555 BasicBlock *BB = Worklist.pop_back_val();
3556 if (BB == Header || !Visited.insert(BB).second)
3557 continue;
3558 if (BB == RealDest)
3559 return false;
3561 return false;
3562 if (pred_empty(BB))
3563 return false;
3564 append_range(Worklist, predecessors(BB));
3565 }
3566 return true;
3567}
3568
3569/// Return true if we can thread a branch across this block.
3571 BlocksSet &NonLocalUseBlocks) {
3572 int Size = 0;
3573 EphemeralValueTracker EphTracker;
3574
3575 // Walk the loop in reverse so that we can identify ephemeral values properly
3576 // (values only feeding assumes).
3577 for (Instruction &I : reverse(*BB)) {
3578 // Can't fold blocks that contain noduplicate or convergent calls.
3579 if (CallInst *CI = dyn_cast<CallInst>(&I))
3580 if (CI->cannotDuplicate() || CI->isConvergent())
3581 return false;
3582
3583 // Ignore ephemeral values which are deleted during codegen.
3584 // We will delete Phis while threading, so Phis should not be accounted in
3585 // block's size.
3586 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3587 if (Size++ > MaxSmallBlockSize)
3588 return false; // Don't clone large BB's.
3589 }
3590
3591 // Record blocks with non-local uses of values defined in the current basic
3592 // block.
3593 for (User *U : I.users()) {
3595 BasicBlock *UsedInBB = UI->getParent();
3596 if (UsedInBB == BB) {
3597 if (isa<PHINode>(UI))
3598 return false;
3599 } else
3600 NonLocalUseBlocks.insert(UsedInBB);
3601 }
3602
3603 // Looks ok, continue checking.
3604 }
3605
3606 return true;
3607}
3608
3610 BasicBlock *To) {
3611 // Don't look past the block defining the value, we might get the value from
3612 // a previous loop iteration.
3613 auto *I = dyn_cast<Instruction>(V);
3614 if (I && I->getParent() == To)
3615 return nullptr;
3616
3617 // We know the value if the From block branches on it.
3618 auto *BI = dyn_cast<CondBrInst>(From->getTerminator());
3619 if (BI && BI->getCondition() == V &&
3620 BI->getSuccessor(0) != BI->getSuccessor(1))
3621 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3623
3624 return nullptr;
3625}
3626
3628 return CB->isConvergent() && !isa<ConvergenceControlInst>(CB) &&
3630}
3631
3633 BasicBlock *StopBB) {
3634 static constexpr unsigned MaxInstructionsToScan = 512;
3635
3636 // Walk predecessors of StopBB to find blocks that can reach it. Only
3637 // convergent calls on a cycle with StopBB matter - a convergent call on a
3638 // path to function exit cannot have its dynamic instance changed by
3639 // threading.
3640 SmallPtrSet<BasicBlock *, 8> CanReachStop;
3641 SmallPtrSet<BasicBlock *, 8> BlocksWithUncontrolledConvergentCalls;
3643 for (BasicBlock *Pred : predecessors(StopBB))
3644 Worklist.push_back(Pred);
3645
3646 // Cache blocks with relevant calls while building CanReachStop. This keeps
3647 // the instruction scan bounded without a separate block limit.
3648 unsigned NumScannedInstructions = 0;
3649 while (!Worklist.empty()) {
3650 BasicBlock *BB = Worklist.pop_back_val();
3651 if (BB == StopBB)
3652 continue;
3653 if (!CanReachStop.insert(BB).second)
3654 continue;
3655
3656 for (Instruction &I : *BB) {
3657 if (++NumScannedInstructions > MaxInstructionsToScan)
3658 return true;
3659 auto *CB = dyn_cast<CallBase>(&I);
3660 if (CB && isUncontrolledConvergentCall(CB)) {
3661 BlocksWithUncontrolledConvergentCalls.insert(BB);
3662 break;
3663 }
3664 }
3665
3666 append_range(Worklist, predecessors(BB));
3667 }
3668
3669 if (!CanReachStop.contains(From))
3670 return false;
3671
3673 Worklist.push_back(From);
3674
3675 while (!Worklist.empty()) {
3676 BasicBlock *BB = Worklist.pop_back_val();
3677 if (BB == StopBB || !CanReachStop.contains(BB))
3678 continue;
3679
3680 if (!Visited.insert(BB).second)
3681 continue;
3682
3683 if (BlocksWithUncontrolledConvergentCalls.contains(BB))
3684 return true;
3685
3686 append_range(Worklist, successors(BB));
3687 }
3688
3689 return false;
3690}
3691
3692/// If we have a conditional branch on something for which we know the constant
3693/// value in predecessors (e.g. a phi node in the current block), thread edges
3694/// from the predecessor to their ultimate destination.
3697 AssumptionCache *AC, const DataLayout &DL, bool KeepCanonicalLoop) {
3699 BasicBlock *BB = BI->getParent();
3700 Value *Cond = BI->getCondition();
3702 if (PN && PN->getParent() == BB) {
3703 // Degenerate case of a single entry PHI.
3704 if (PN->getNumIncomingValues() == 1) {
3706 return true;
3707 }
3708
3709 for (Use &U : PN->incoming_values())
3710 if (auto *CB = dyn_cast<ConstantInt>(U))
3711 KnownValues[CB].insert(PN->getIncomingBlock(U));
3712 } else {
3713 for (BasicBlock *Pred : predecessors(BB)) {
3714 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3715 KnownValues[CB].insert(Pred);
3716 }
3717 }
3718
3719 if (KnownValues.empty())
3720 return false;
3721
3722 // Now we know that this block has multiple preds and two succs.
3723 // Check that the block is small enough and record which non-local blocks use
3724 // values defined in the block.
3725
3726 BlocksSet NonLocalUseBlocks;
3727 BlocksSet ReachesNonLocalUseBlocks;
3728 if (!blockIsSimpleEnoughToThreadThrough(BB, NonLocalUseBlocks))
3729 return false;
3730
3731 // Jump-threading can only be done to destinations where no values defined
3732 // in BB are live.
3733
3734 // Quickly check if both destinations have uses. If so, jump-threading cannot
3735 // be done.
3736 if (NonLocalUseBlocks.contains(BI->getSuccessor(0)) &&
3737 NonLocalUseBlocks.contains(BI->getSuccessor(1)))
3738 return false;
3739
3740 // Search backward from NonLocalUseBlocks to find which blocks
3741 // reach non-local uses.
3742 for (BasicBlock *UseBB : NonLocalUseBlocks)
3743 // Give up if too many blocks are searched.
3744 if (!findReaching(UseBB, BB, ReachesNonLocalUseBlocks))
3745 return false;
3746
3747 for (const auto &Pair : KnownValues) {
3748 ConstantInt *CB = Pair.first;
3749 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3750 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3751
3752 // Okay, we now know that all edges from PredBB should be revectored to
3753 // branch to RealDest.
3754 if (RealDest == BB)
3755 continue; // Skip self loops.
3756
3757 // Skip if the predecessor's terminator is an indirect branch.
3758 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3759 return isa<IndirectBrInst>(PredBB->getTerminator());
3760 }))
3761 continue;
3762
3763 // Only revector to RealDest if no values defined in BB are live.
3764 if (ReachesNonLocalUseBlocks.contains(RealDest))
3765 continue;
3766
3767 if (KeepCanonicalLoop &&
3768 !isSafeToThreadThroughLoopHeader(BB, PredBBs, RealDest))
3769 continue;
3770
3771 // Threading through a branch can bypass a reconvergence point. If the
3772 // destination can execute an uncontrolled convergent operation before
3773 // returning to this block, this may change the dynamic instance of that
3774 // operation.
3775 if (TTI.hasBranchDivergence(BB->getParent()) &&
3777 continue;
3778
3779 LLVM_DEBUG({
3780 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3781 << " has value " << *Pair.first << " in predecessors:\n";
3782 for (const BasicBlock *PredBB : Pair.second)
3783 dbgs() << " " << PredBB->getName() << "\n";
3784 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3785 });
3786
3787 // Split the predecessors we are threading into a new edge block. We'll
3788 // clone the instructions into this block, and then redirect it to RealDest.
3789 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3790 if (!EdgeBB)
3791 continue;
3792
3793 // TODO: These just exist to reduce test diff, we can drop them if we like.
3794 EdgeBB->setName(RealDest->getName() + ".critedge");
3795 EdgeBB->moveBefore(RealDest);
3796
3797 // Update PHI nodes.
3798 addPredecessorToBlock(RealDest, EdgeBB, BB);
3799
3800 // BB may have instructions that are being threaded over. Clone these
3801 // instructions into EdgeBB. We know that there will be no uses of the
3802 // cloned instructions outside of EdgeBB.
3803 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3804 ValueToValueMapTy TranslateMap; // Track translated values.
3805 TranslateMap[Cond] = CB;
3806
3807 // RemoveDIs: track instructions that we optimise away while folding, so
3808 // that we can copy DbgVariableRecords from them later.
3809 BasicBlock::iterator SrcDbgCursor = BB->begin();
3810 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3811 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3812 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3813 continue;
3814 }
3815 // Clone the instruction.
3816 Instruction *N = BBI->clone();
3817 // Insert the new instruction into its new home.
3818 N->insertInto(EdgeBB, InsertPt);
3819
3820 if (BBI->hasName())
3821 N->setName(BBI->getName() + ".c");
3822
3823 // Update operands due to translation.
3824 // Key Instructions: Remap all the atom groups.
3825 if (const DebugLoc &DL = BBI->getDebugLoc())
3826 mapAtomInstance(DL, TranslateMap);
3827 RemapInstruction(N, TranslateMap,
3829
3830 // Check for trivial simplification.
3831 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3832 if (!BBI->use_empty())
3833 TranslateMap[&*BBI] = V;
3834 if (!N->mayHaveSideEffects()) {
3835 N->eraseFromParent(); // Instruction folded away, don't need actual
3836 // inst
3837 N = nullptr;
3838 }
3839 } else {
3840 if (!BBI->use_empty())
3841 TranslateMap[&*BBI] = N;
3842 }
3843 if (N) {
3844 // Copy all debug-info attached to instructions from the last we
3845 // successfully clone, up to this instruction (they might have been
3846 // folded away).
3847 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3848 N->cloneDebugInfoFrom(&*SrcDbgCursor);
3849 SrcDbgCursor = std::next(BBI);
3850 // Clone debug-info on this instruction too.
3851 N->cloneDebugInfoFrom(&*BBI);
3852
3853 // Register the new instruction with the assumption cache if necessary.
3854 if (auto *Assume = dyn_cast<AssumeInst>(N))
3855 if (AC)
3856 AC->registerAssumption(Assume);
3857 }
3858 }
3859
3860 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3861 InsertPt->cloneDebugInfoFrom(&*SrcDbgCursor);
3862 InsertPt->cloneDebugInfoFrom(BI);
3863
3864 BB->removePredecessor(EdgeBB);
3865 UncondBrInst *EdgeBI = cast<UncondBrInst>(EdgeBB->getTerminator());
3866 EdgeBI->setSuccessor(0, RealDest);
3867 EdgeBI->setDebugLoc(BI->getDebugLoc());
3868
3869 if (DTU) {
3871 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3872 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3873 DTU->applyUpdates(Updates);
3874 }
3875
3876 // For simplicity, we created a separate basic block for the edge. Merge
3877 // it back into the predecessor if possible. This not only avoids
3878 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3879 // bypass the check for trivial cycles above.
3880 MergeBlockIntoPredecessor(EdgeBB, DTU);
3881
3882 // Signal repeat, simplifying any other constants.
3883 return std::nullopt;
3884 }
3885
3886 return false;
3887}
3888
3889bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
3890 // Threading through a loop header can introduce a cycle that bypasses the
3891 // header.
3892 bool KeepCanonicalLoop =
3893 Options.NeedCanonicalLoop && is_contained(LoopHeaders, BI->getParent());
3894
3895 std::optional<bool> Result;
3896 bool EverChanged = false;
3897 do {
3898 // Note that None means "we changed things, but recurse further."
3900 BI, TTI, DTU, Options.AC, DL, KeepCanonicalLoop);
3901 EverChanged |= Result == std::nullopt || *Result;
3902 } while (Result == std::nullopt);
3903 return EverChanged;
3904}
3905
3906/// Given a BB that starts with the specified two-entry PHI node,
3907/// see if we can eliminate it.
3910 const DataLayout &DL,
3911 bool SpeculateUnpredictables) {
3912 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3913 // statement", which has a very simple dominance structure. Basically, we
3914 // are trying to find the condition that is being branched on, which
3915 // subsequently causes this merge to happen. We really want control
3916 // dependence information for this check, but simplifycfg can't keep it up
3917 // to date, and this catches most of the cases we care about anyway.
3918 BasicBlock *BB = PN->getParent();
3919
3920 BasicBlock *IfTrue, *IfFalse;
3921 CondBrInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3922 if (!DomBI)
3923 return false;
3924 Value *IfCond = DomBI->getCondition();
3925 // Don't bother if the branch will be constant folded trivially.
3926 if (isa<ConstantInt>(IfCond))
3927 return false;
3928
3929 BasicBlock *DomBlock = DomBI->getParent();
3931 llvm::copy_if(PN->blocks(), std::back_inserter(IfBlocks),
3932 [](BasicBlock *IfBlock) {
3933 return isa<UncondBrInst>(IfBlock->getTerminator());
3934 });
3935 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3936 "Will have either one or two blocks to speculate.");
3937
3938 // If the branch is non-unpredictable, see if we either predictably jump to
3939 // the merge bb (if we have only a single 'then' block), or if we predictably
3940 // jump to one specific 'then' block (if we have two of them).
3941 // It isn't beneficial to speculatively execute the code
3942 // from the block that we know is predictably not entered.
3943 bool IsUnpredictable = DomBI->getMetadata(LLVMContext::MD_unpredictable);
3944 if (!IsUnpredictable) {
3945 uint64_t TWeight, FWeight;
3946 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3947 (TWeight + FWeight) != 0) {
3948 BranchProbability BITrueProb =
3949 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3950 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3951 BranchProbability BIFalseProb = BITrueProb.getCompl();
3952 if (IfBlocks.size() == 1) {
3953 BranchProbability BIBBProb =
3954 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3955 if (BIBBProb >= Likely)
3956 return false;
3957 } else {
3958 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3959 return false;
3960 }
3961 }
3962 }
3963
3964 // Don't try to fold an unreachable block. For example, the phi node itself
3965 // can't be the candidate if-condition for a select that we want to form.
3966 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3967 if (IfCondPhiInst->getParent() == BB)
3968 return false;
3969
3970 // Okay, we found that we can merge this two-entry phi node into a select.
3971 // Doing so would require us to fold *all* two entry phi nodes in this block.
3972 // At some point this becomes non-profitable (particularly if the target
3973 // doesn't support cmov's). Only do this transformation if there are two or
3974 // fewer PHI nodes in this block.
3975 unsigned NumPhis = 0;
3976 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3977 if (NumPhis > 2)
3978 return false;
3979
3980 // Loop over the PHI's seeing if we can promote them all to select
3981 // instructions. While we are at it, keep track of the instructions
3982 // that need to be moved to the dominating block.
3983 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3984 SmallPtrSet<Instruction *, 2> ZeroCostInstructions;
3985 InstructionCost Cost = 0;
3986 InstructionCost Budget =
3988 if (SpeculateUnpredictables && IsUnpredictable)
3989 Budget += TTI.getBranchMispredictPenalty();
3990
3991 bool Changed = false;
3992 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3993 PHINode *PN = cast<PHINode>(II++);
3994 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3995 PN->replaceAllUsesWith(V);
3996 PN->eraseFromParent();
3997 Changed = true;
3998 continue;
3999 }
4000
4001 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, DomBI,
4002 AggressiveInsts, Cost, Budget, TTI, AC,
4003 ZeroCostInstructions) ||
4004 !dominatesMergePoint(PN->getIncomingValue(1), BB, DomBI,
4005 AggressiveInsts, Cost, Budget, TTI, AC,
4006 ZeroCostInstructions))
4007 return Changed;
4008 }
4009
4010 // If we folded the first phi, PN dangles at this point. Refresh it. If
4011 // we ran out of PHIs then we simplified them all.
4012 PN = dyn_cast<PHINode>(BB->begin());
4013 if (!PN)
4014 return true;
4015
4016 // Don't fold i1 branches on PHIs which contain binary operators or
4017 // (possibly inverted) select form of or/ands if their parameters are
4018 // an equality test.
4019 auto IsBinOpOrAndEq = [](Value *V) {
4020 CmpPredicate Pred;
4021 if (match(V, m_CombineOr(
4023 m_BinOp(m_Cmp(Pred, m_Value(), m_Value()), m_Value()),
4024 m_BinOp(m_Value(), m_Cmp(Pred, m_Value(), m_Value()))),
4026 m_Cmp(Pred, m_Value(), m_Value()))))) {
4027 return CmpInst::isEquality(Pred);
4028 }
4029 return false;
4030 };
4031 if (PN->getType()->isIntegerTy(1) &&
4032 (IsBinOpOrAndEq(PN->getIncomingValue(0)) ||
4033 IsBinOpOrAndEq(PN->getIncomingValue(1)) || IsBinOpOrAndEq(IfCond)))
4034 return Changed;
4035
4036 // If all PHI nodes are promotable, check to make sure that all instructions
4037 // in the predecessor blocks can be promoted as well. If not, we won't be able
4038 // to get rid of the control flow, so it's not worth promoting to select
4039 // instructions.
4040 for (BasicBlock *IfBlock : IfBlocks)
4041 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
4042 if (!AggressiveInsts.count(&*I) && !isa<PseudoProbeInst>(I)) {
4043 // This is not an aggressive instruction that we can promote.
4044 // Because of this, we won't be able to get rid of the control flow, so
4045 // the xform is not worth it.
4046 return Changed;
4047 }
4048
4049 // If either of the blocks has it's address taken, we can't do this fold.
4050 if (any_of(IfBlocks,
4051 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
4052 return Changed;
4053
4054 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
4055 if (IsUnpredictable) dbgs() << " (unpredictable)";
4056 dbgs() << " T: " << IfTrue->getName()
4057 << " F: " << IfFalse->getName() << "\n");
4058
4059 // If we can still promote the PHI nodes after this gauntlet of tests,
4060 // do all of the PHI's now.
4061
4062 // Move all 'aggressive' instructions, which are defined in the
4063 // conditional parts of the if's up to the dominating block.
4064 for (BasicBlock *IfBlock : IfBlocks)
4065 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
4066
4067 IRBuilder<NoFolder> Builder(DomBI);
4068 // Propagate fast-math-flags from phi nodes to replacement selects.
4069 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
4070 // Change the PHI node into a select instruction.
4071 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
4072 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
4073
4074 Value *Sel = Builder.CreateSelectFMF(IfCond, TrueVal, FalseVal,
4075 isa<FPMathOperator>(PN) ? PN : nullptr,
4076 "", DomBI);
4077 PN->replaceAllUsesWith(Sel);
4078 Sel->takeName(PN);
4079 PN->eraseFromParent();
4080 }
4081
4082 // At this point, all IfBlocks are empty, so our if statement
4083 // has been flattened. Change DomBlock to jump directly to our new block to
4084 // avoid other simplifycfg's kicking in on the diamond.
4085 Builder.CreateBr(BB);
4086
4088 if (DTU) {
4089 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
4090 for (auto *Successor : successors(DomBlock))
4091 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
4092 }
4093
4094 DomBI->eraseFromParent();
4095 if (DTU)
4096 DTU->applyUpdates(Updates);
4097
4098 return true;
4099}
4100
4103 Value *RHS, const Twine &Name = "") {
4104 // Try to relax logical op to binary op.
4105 if (impliesPoison(RHS, LHS))
4106 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
4107 if (Opc == Instruction::And)
4108 return Builder.CreateLogicalAnd(LHS, RHS, Name);
4109 if (Opc == Instruction::Or)
4110 return Builder.CreateLogicalOr(LHS, RHS, Name);
4111 llvm_unreachable("Invalid logical opcode");
4112}
4113
4114/// Return true if either PBI or BI has branch weight available, and store
4115/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
4116/// not have branch weight, use 1:1 as its weight.
4118 uint64_t &PredTrueWeight,
4119 uint64_t &PredFalseWeight,
4120 uint64_t &SuccTrueWeight,
4121 uint64_t &SuccFalseWeight) {
4122 bool PredHasWeights =
4123 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
4124 bool SuccHasWeights =
4125 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
4126 if (PredHasWeights || SuccHasWeights) {
4127 if (!PredHasWeights)
4128 PredTrueWeight = PredFalseWeight = 1;
4129 if (!SuccHasWeights)
4130 SuccTrueWeight = SuccFalseWeight = 1;
4131 return true;
4132 } else {
4133 return false;
4134 }
4135}
4136
4137/// Determine if the two branches share a common destination and deduce a glue
4138/// that joins the branches' conditions to arrive at the common destination if
4139/// that would be profitable.
4140static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
4142 const TargetTransformInfo *TTI) {
4143 assert(BI && PBI && "Both blocks must end with a conditional branches.");
4145 "PredBB must be a predecessor of BB.");
4146
4147 // We have the potential to fold the conditions together, but if the
4148 // predecessor branch is predictable, we may not want to merge them.
4149 uint64_t PTWeight, PFWeight;
4150 BranchProbability PBITrueProb, Likely;
4151 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4152 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
4153 (PTWeight + PFWeight) != 0) {
4154 PBITrueProb =
4155 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
4156 Likely = TTI->getPredictableBranchThreshold();
4157 }
4158
4159 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4160 // Speculate the 2nd condition unless the 1st is probably true.
4161 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4162 return {{BI->getSuccessor(0), Instruction::Or, false}};
4163 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4164 // Speculate the 2nd condition unless the 1st is probably false.
4165 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4166 return {{BI->getSuccessor(1), Instruction::And, false}};
4167 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4168 // Speculate the 2nd condition unless the 1st is probably true.
4169 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4170 return {{BI->getSuccessor(1), Instruction::And, true}};
4171 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4172 // Speculate the 2nd condition unless the 1st is probably false.
4173 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4174 return {{BI->getSuccessor(0), Instruction::Or, true}};
4175 }
4176 return std::nullopt;
4177}
4178
4180 DomTreeUpdater *DTU,
4181 MemorySSAUpdater *MSSAU,
4182 const TargetTransformInfo *TTI) {
4183 BasicBlock *BB = BI->getParent();
4184 BasicBlock *PredBlock = PBI->getParent();
4185
4186 // Determine if the two branches share a common destination.
4187 BasicBlock *CommonSucc;
4189 bool InvertPredCond;
4190 std::tie(CommonSucc, Opc, InvertPredCond) =
4192
4193 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
4194
4196 *BB->getModule(), ConstantFolder{},
4198 // The builder is used to create instructions to eliminate the branch in
4199 // BB. If BB's terminator has !annotation metadata, add it to the new
4200 // instructions.
4201 I->copyMetadata(*BB->getTerminator(), LLVMContext::MD_annotation);
4202 }));
4203 Builder.SetInsertPoint(PBI);
4204
4205 // If we need to invert the condition in the pred block to match, do so now.
4206 if (InvertPredCond) {
4207 InvertBranch(PBI, Builder);
4208 }
4209
4210 BasicBlock *UniqueSucc =
4211 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
4212
4213 // Before cloning instructions, notify the successor basic block that it
4214 // is about to have a new predecessor. This will update PHI nodes,
4215 // which will allow us to update live-out uses of bonus instructions.
4216 addPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
4217
4218 // Try to update branch weights.
4219 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4220 SmallVector<uint64_t, 2> MDWeights;
4221 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4222 SuccTrueWeight, SuccFalseWeight)) {
4223
4224 if (PBI->getSuccessor(0) == BB) {
4225 // PBI: br i1 %x, BB, FalseDest
4226 // BI: br i1 %y, UniqueSucc, FalseDest
4227 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
4228 MDWeights.push_back(PredTrueWeight * SuccTrueWeight);
4229 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
4230 // TrueWeight for PBI * FalseWeight for BI.
4231 // We assume that total weights of a CondBrInst can fit into 32 bits.
4232 // Therefore, we will not have overflow using 64-bit arithmetic.
4233 MDWeights.push_back(PredFalseWeight * (SuccFalseWeight + SuccTrueWeight) +
4234 PredTrueWeight * SuccFalseWeight);
4235 } else {
4236 // PBI: br i1 %x, TrueDest, BB
4237 // BI: br i1 %y, TrueDest, UniqueSucc
4238 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
4239 // FalseWeight for PBI * TrueWeight for BI.
4240 MDWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
4241 PredFalseWeight * SuccTrueWeight);
4242 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
4243 MDWeights.push_back(PredFalseWeight * SuccFalseWeight);
4244 }
4245
4246 setFittedBranchWeights(*PBI, MDWeights, /*IsExpected=*/false,
4247 /*ElideAllZero=*/true);
4248
4249 // TODO: If BB is reachable from all paths through PredBlock, then we
4250 // could replace PBI's branch probabilities with BI's.
4251 } else {
4252 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
4254 }
4255
4256 // Now, update the CFG.
4257 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
4258
4259 if (DTU)
4260 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
4261 {DominatorTree::Delete, PredBlock, BB}});
4262
4263 // If BI was a loop latch, it may have had associated loop metadata.
4264 // We need to copy it to the new latch, that is, PBI.
4265 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
4266 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
4267
4268 ValueToValueMapTy VMap; // maps original values to cloned values
4270
4271 Module *M = BB->getModule();
4272
4273 PredBlock->getTerminator()->cloneDebugInfoFrom(BB->getTerminator());
4274 for (DbgVariableRecord &DVR :
4276 RemapDbgRecord(M, &DVR, VMap,
4278 }
4279
4280 // Now that the Cond was cloned into the predecessor basic block,
4281 // or/and the two conditions together.
4282 Value *BICond = VMap[BI->getCondition()];
4283 PBI->setCondition(
4284 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
4285 if (auto *SI = dyn_cast<SelectInst>(PBI->getCondition())) {
4286 if (!MDWeights.empty()) {
4287 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4288 setFittedBranchWeights(*SI, {MDWeights[0], MDWeights[1]},
4289 /*IsExpected=*/false, /*ElideAllZero=*/true);
4290 } else {
4292 }
4293 }
4294
4295 ++NumFoldBranchToCommonDest;
4296 return true;
4297}
4298
4299/// Return if an instruction's type or any of its operands' types are a vector
4300/// type.
4301static bool isVectorOp(Instruction &I) {
4302 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
4303 return U->getType()->isVectorTy();
4304 });
4305}
4306
4307/// If this basic block is simple enough, and if a predecessor branches to us
4308/// and one of our successors, fold the block into the predecessor and use
4309/// logical operations to pick the right destination.
4311 MemorySSAUpdater *MSSAU,
4312 const TargetTransformInfo *TTI,
4313 AssumptionCache *AC,
4314 unsigned BonusInstThreshold) {
4315 BasicBlock *BB = BI->getParent();
4319
4321
4323 Cond->getParent() != BB || !Cond->hasOneUse())
4324 return false;
4325
4326 // Finally, don't infinitely unroll conditional loops.
4327 if (is_contained(successors(BB), BB))
4328 return false;
4329
4330 // With which predecessors will we want to deal with?
4332 for (BasicBlock *PredBlock : predecessors(BB)) {
4333 CondBrInst *PBI = dyn_cast<CondBrInst>(PredBlock->getTerminator());
4334
4335 // Check that we have two conditional branches. If there is a PHI node in
4336 // the common successor, verify that the same value flows in from both
4337 // blocks.
4338 if (!PBI || !safeToMergeTerminators(BI, PBI))
4339 continue;
4340
4341 // Determine if the two branches share a common destination.
4342 BasicBlock *CommonSucc;
4344 bool InvertPredCond;
4345 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
4346 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
4347 else
4348 continue;
4349
4350 // Check the cost of inserting the necessary logic before performing the
4351 // transformation.
4352 if (TTI) {
4353 Type *Ty = BI->getCondition()->getType();
4354 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
4355 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
4356 !isa<CmpInst>(PBI->getCondition())))
4357 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
4358
4360 continue;
4361 }
4362
4363 // Ok, we do want to deal with this predecessor. Record it.
4364 Preds.emplace_back(PredBlock);
4365 }
4366
4367 // If there aren't any predecessors into which we can fold,
4368 // don't bother checking the cost.
4369 if (Preds.empty())
4370 return false;
4371
4372 // Only allow this transformation if computing the condition doesn't involve
4373 // too many instructions and these involved instructions can be executed
4374 // unconditionally. We denote all involved instructions except the condition
4375 // as "bonus instructions", and only allow this transformation when the
4376 // number of the bonus instructions we'll need to create when cloning into
4377 // each predecessor does not exceed a certain threshold.
4378 unsigned NumBonusInsts = 0;
4379 bool SawVectorOp = false;
4380 const unsigned PredCount = Preds.size();
4381 // Speculated instructions will be inserted before the terminator of the
4382 // predecessor. Only handle the simple case of one predecessor.
4383 const Instruction *CtxI =
4384 PredCount == 1 ? Preds[0]->getTerminator() : nullptr;
4385 for (Instruction &I : *BB) {
4386 // Don't check the branch condition comparison itself.
4387 if (&I == Cond)
4388 continue;
4389 // Ignore the terminator.
4391 continue;
4392 // Pseudo probes aren't speculatable but can be dropped on fold.
4394 continue;
4395 // I must be safe to execute unconditionally.
4396 if (!isSafeToSpeculativelyExecute(&I, CtxI, AC))
4397 return false;
4398 SawVectorOp |= isVectorOp(I);
4399
4400 // Account for the cost of duplicating this instruction into each
4401 // predecessor. Ignore free instructions.
4402 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
4404 NumBonusInsts += PredCount;
4405
4406 // Early exits once we reach the limit.
4407 if (NumBonusInsts >
4408 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
4409 return false;
4410 }
4411
4412 auto IsBCSSAUse = [BB, &I](Use &U) {
4413 auto *UI = cast<Instruction>(U.getUser());
4414 if (auto *PN = dyn_cast<PHINode>(UI))
4415 return PN->getIncomingBlock(U) == BB;
4416 return UI->getParent() == BB && I.comesBefore(UI);
4417 };
4418
4419 // Does this instruction require rewriting of uses?
4420 if (!all_of(I.uses(), IsBCSSAUse))
4421 return false;
4422 }
4423 if (NumBonusInsts >
4424 BonusInstThreshold *
4425 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
4426 return false;
4427
4428 // Ok, we have the budget. Perform the transformation.
4429 for (BasicBlock *PredBlock : Preds) {
4430 auto *PBI = cast<CondBrInst>(PredBlock->getTerminator());
4431 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4432 }
4433 return false;
4434}
4435
4436// If there is only one store in BB1 and BB2, return it, otherwise return
4437// nullptr.
4439 StoreInst *S = nullptr;
4440 for (auto *BB : {BB1, BB2}) {
4441 if (!BB)
4442 continue;
4443 for (auto &I : *BB)
4444 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4445 if (S)
4446 // Multiple stores seen.
4447 return nullptr;
4448 else
4449 S = SI;
4450 }
4451 }
4452 return S;
4453}
4454
4456 Value *AlternativeV = nullptr) {
4457 // PHI is going to be a PHI node that allows the value V that is defined in
4458 // BB to be referenced in BB's only successor.
4459 //
4460 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4461 // doesn't matter to us what the other operand is (it'll never get used). We
4462 // could just create a new PHI with an undef incoming value, but that could
4463 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4464 // other PHI. So here we directly look for some PHI in BB's successor with V
4465 // as an incoming operand. If we find one, we use it, else we create a new
4466 // one.
4467 //
4468 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4469 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4470 // where OtherBB is the single other predecessor of BB's only successor.
4471 PHINode *PHI = nullptr;
4472 BasicBlock *Succ = BB->getSingleSuccessor();
4473
4474 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
4475 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
4476 PHI = cast<PHINode>(I);
4477 if (!AlternativeV)
4478 break;
4479
4480 assert(Succ->hasNPredecessors(2));
4481 auto PredI = pred_begin(Succ);
4482 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4483 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
4484 break;
4485 PHI = nullptr;
4486 }
4487 if (PHI)
4488 return PHI;
4489
4490 // If V is not an instruction defined in BB, just return it.
4491 if (!AlternativeV &&
4492 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
4493 return V;
4494
4495 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
4496 PHI->insertBefore(Succ->begin());
4497 PHI->addIncoming(V, BB);
4498 for (BasicBlock *PredBB : predecessors(Succ))
4499 if (PredBB != BB)
4500 PHI->addIncoming(
4501 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
4502 return PHI;
4503}
4504
4506 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4507 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4508 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4509 // For every pointer, there must be exactly two stores, one coming from
4510 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4511 // store (to any address) in PTB,PFB or QTB,QFB.
4512 // FIXME: We could relax this restriction with a bit more work and performance
4513 // testing.
4514 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
4515 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
4516 if (!PStore || !QStore)
4517 return false;
4518
4519 // Now check the stores are compatible.
4520 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4521 PStore->getOrdering() != QStore->getOrdering() ||
4522 PStore->getSyncScopeID() != QStore->getSyncScopeID() ||
4523 PStore->getValueOperand()->getType() !=
4524 QStore->getValueOperand()->getType())
4525 return false;
4526
4527 // Check that sinking the store won't cause program behavior changes. Sinking
4528 // the store out of the Q blocks won't change any behavior as we're sinking
4529 // from a block to its unconditional successor. But we're moving a store from
4530 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4531 // So we need to check that there are no aliasing loads or stores in
4532 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4533 // operations between PStore and the end of its parent block.
4534 //
4535 // The ideal way to do this is to query AliasAnalysis, but we don't
4536 // preserve AA currently so that is dangerous. Be super safe and just
4537 // check there are no other memory operations at all.
4538 for (auto &I : *QFB->getSinglePredecessor())
4539 if (I.mayReadOrWriteMemory())
4540 return false;
4541 for (auto &I : *QFB)
4542 if (&I != QStore && I.mayReadOrWriteMemory())
4543 return false;
4544 if (QTB)
4545 for (auto &I : *QTB)
4546 if (&I != QStore && I.mayReadOrWriteMemory())
4547 return false;
4548 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4549 I != E; ++I)
4550 if (&*I != PStore && I->mayReadOrWriteMemory())
4551 return false;
4552
4553 // If we're not in aggressive mode, we only optimize if we have some
4554 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4555 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4556 if (!BB)
4557 return true;
4558 // Heuristic: if the block can be if-converted/phi-folded and the
4559 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4560 // thread this store.
4561 InstructionCost Cost = 0;
4562 InstructionCost Budget =
4564 for (auto &I : *BB) {
4565 // Consider terminator instruction to be free.
4566 if (I.isTerminator())
4567 continue;
4568 // If this is one the stores that we want to speculate out of this BB,
4569 // then don't count it's cost, consider it to be free.
4570 if (auto *S = dyn_cast<StoreInst>(&I))
4571 if (llvm::find(FreeStores, S))
4572 continue;
4573 // Else, we have a white-list of instructions that we are ak speculating.
4575 return false; // Not in white-list - not worthwhile folding.
4576 // And finally, if this is a non-free instruction that we are okay
4577 // speculating, ensure that we consider the speculation budget.
4578 Cost +=
4579 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
4580 if (Cost > Budget)
4581 return false; // Eagerly refuse to fold as soon as we're out of budget.
4582 }
4583 assert(Cost <= Budget &&
4584 "When we run out of budget we will eagerly return from within the "
4585 "per-instruction loop.");
4586 return true;
4587 };
4588
4589 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4591 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4592 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4593 return false;
4594
4595 // If PostBB has more than two predecessors, we need to split it so we can
4596 // sink the store.
4597 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4598 // We know that QFB's only successor is PostBB. And QFB has a single
4599 // predecessor. If QTB exists, then its only successor is also PostBB.
4600 // If QTB does not exist, then QFB's only predecessor has a conditional
4601 // branch to QFB and PostBB.
4602 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4603 BasicBlock *NewBB =
4604 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4605 if (!NewBB)
4606 return false;
4607 PostBB = NewBB;
4608 }
4609
4610 // OK, we're going to sink the stores to PostBB. The store has to be
4611 // conditional though, so first create the predicate.
4612 CondBrInst *PBranch =
4614 CondBrInst *QBranch =
4616 Value *PCond = PBranch->getCondition();
4617 Value *QCond = QBranch->getCondition();
4618
4620 PStore->getParent());
4622 QStore->getParent(), PPHI);
4623
4624 IRBuilder<> QB(PostBB->getFirstInsertionPt());
4625
4626 InvertPCond ^= (PStore->getParent() != PTB);
4627 InvertQCond ^= (QStore->getParent() != QTB);
4628 Value *PPred = InvertPCond ? QB.CreateNot(PCond) : PCond;
4629 Value *QPred = InvertQCond ? QB.CreateNot(QCond) : QCond;
4630
4631 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4632
4633 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4634 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4635 /*Unreachable=*/false,
4636 /*BranchWeights=*/nullptr, DTU);
4637 if (hasBranchWeightMD(*PBranch) && hasBranchWeightMD(*QBranch)) {
4638 SmallVector<uint32_t, 2> PWeights, QWeights;
4639 extractBranchWeights(*PBranch, PWeights);
4640 extractBranchWeights(*QBranch, QWeights);
4641 if (InvertPCond)
4642 std::swap(PWeights[0], PWeights[1]);
4643 if (InvertQCond)
4644 std::swap(QWeights[0], QWeights[1]);
4645 auto CombinedWeights = getDisjunctionWeights(PWeights, QWeights);
4647 {CombinedWeights[0], CombinedWeights[1]},
4648 /*IsExpected=*/false, /*ElideAllZero=*/true);
4649 }
4650
4651 QB.SetInsertPoint(T);
4652 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4653 combineMetadataForCSE(QStore, PStore, true);
4654 SI->copyMetadata(*QStore);
4655 // Update any dbg.assign intrinsics to track the merged value (QPHI) instead
4656 // of the original constant values, likely making these identical.
4657 for (auto *DbgAssign : at::getDVRAssignmentMarkers(SI)) {
4658 if (llvm::is_contained(DbgAssign->location_ops(),
4659 PStore->getValueOperand()))
4660 DbgAssign->replaceVariableLocationOp(PStore->getValueOperand(), QPHI);
4661 if (llvm::is_contained(DbgAssign->location_ops(),
4662 QStore->getValueOperand()))
4663 DbgAssign->replaceVariableLocationOp(QStore->getValueOperand(), QPHI);
4664 }
4665
4666 // Choose the minimum alignment. If we could prove both stores execute, we
4667 // could use biggest one. In this case, though, we only know that one of the
4668 // stores executes. And we don't know it's safe to take the alignment from a
4669 // store that doesn't execute.
4670 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4671
4672 if (QStore->isAtomic())
4673 SI->setAtomic(QStore->getOrdering(), QStore->getSyncScopeID());
4674
4675 QStore->eraseFromParent();
4676 PStore->eraseFromParent();
4677
4678 return true;
4679}
4680
4682 DomTreeUpdater *DTU, const DataLayout &DL,
4683 const TargetTransformInfo &TTI) {
4684 // The intention here is to find diamonds or triangles (see below) where each
4685 // conditional block contains a store to the same address. Both of these
4686 // stores are conditional, so they can't be unconditionally sunk. But it may
4687 // be profitable to speculatively sink the stores into one merged store at the
4688 // end, and predicate the merged store on the union of the two conditions of
4689 // PBI and QBI.
4690 //
4691 // This can reduce the number of stores executed if both of the conditions are
4692 // true, and can allow the blocks to become small enough to be if-converted.
4693 // This optimization will also chain, so that ladders of test-and-set
4694 // sequences can be if-converted away.
4695 //
4696 // We only deal with simple diamonds or triangles:
4697 //
4698 // PBI or PBI or a combination of the two
4699 // / \ | \
4700 // PTB PFB | PFB
4701 // \ / | /
4702 // QBI QBI
4703 // / \ | \
4704 // QTB QFB | QFB
4705 // \ / | /
4706 // PostBB PostBB
4707 //
4708 // We model triangles as a type of diamond with a nullptr "true" block.
4709 // Triangles are canonicalized so that the fallthrough edge is represented by
4710 // a true condition, as in the diagram above.
4711 BasicBlock *PTB = PBI->getSuccessor(0);
4712 BasicBlock *PFB = PBI->getSuccessor(1);
4713 BasicBlock *QTB = QBI->getSuccessor(0);
4714 BasicBlock *QFB = QBI->getSuccessor(1);
4715 BasicBlock *PostBB = QFB->getSingleSuccessor();
4716
4717 // Make sure we have a good guess for PostBB. If QTB's only successor is
4718 // QFB, then QFB is a better PostBB.
4719 if (QTB->getSingleSuccessor() == QFB)
4720 PostBB = QFB;
4721
4722 // If we couldn't find a good PostBB, stop.
4723 if (!PostBB)
4724 return false;
4725
4726 bool InvertPCond = false, InvertQCond = false;
4727 // Canonicalize fallthroughs to the true branches.
4728 if (PFB == QBI->getParent()) {
4729 std::swap(PFB, PTB);
4730 InvertPCond = true;
4731 }
4732 if (QFB == PostBB) {
4733 std::swap(QFB, QTB);
4734 InvertQCond = true;
4735 }
4736
4737 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4738 // and QFB may not. Model fallthroughs as a nullptr block.
4739 if (PTB == QBI->getParent())
4740 PTB = nullptr;
4741 if (QTB == PostBB)
4742 QTB = nullptr;
4743
4744 // Legality bailouts. We must have at least the non-fallthrough blocks and
4745 // the post-dominating block, and the non-fallthroughs must only have one
4746 // predecessor.
4747 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4748 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4749 };
4750 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4751 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4752 return false;
4753 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4754 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4755 return false;
4756 if (!QBI->getParent()->hasNUses(2))
4757 return false;
4758
4759 // OK, this is a sequence of two diamonds or triangles.
4760 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4761 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4762 for (auto *BB : {PTB, PFB}) {
4763 if (!BB)
4764 continue;
4765 for (auto &I : *BB)
4767 PStoreAddresses.insert(SI->getPointerOperand());
4768 }
4769 for (auto *BB : {QTB, QFB}) {
4770 if (!BB)
4771 continue;
4772 for (auto &I : *BB)
4774 QStoreAddresses.insert(SI->getPointerOperand());
4775 }
4776
4777 set_intersect(PStoreAddresses, QStoreAddresses);
4778 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4779 // clear what it contains.
4780 auto &CommonAddresses = PStoreAddresses;
4781
4782 bool Changed = false;
4783 for (auto *Address : CommonAddresses)
4784 Changed |=
4785 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4786 InvertPCond, InvertQCond, DTU, DL, TTI);
4787 return Changed;
4788}
4789
4790/// If the previous block ended with a widenable branch, determine if reusing
4791/// the target block is profitable and legal. This will have the effect of
4792/// "widening" PBI, but doesn't require us to reason about hosting safety.
4794 DomTreeUpdater *DTU) {
4795 // TODO: This can be generalized in two important ways:
4796 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4797 // values from the PBI edge.
4798 // 2) We can sink side effecting instructions into BI's fallthrough
4799 // successor provided they doesn't contribute to computation of
4800 // BI's condition.
4801 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4802 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4803 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4804 !BI->getParent()->getSinglePredecessor())
4805 return false;
4806 if (!IfFalseBB->phis().empty())
4807 return false; // TODO
4808 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4809 // may undo the transform done here.
4810 // TODO: There might be a more fine-grained solution to this.
4811 if (!llvm::succ_empty(IfFalseBB))
4812 return false;
4813 // Use lambda to lazily compute expensive condition after cheap ones.
4814 auto NoSideEffects = [](BasicBlock &BB) {
4815 return llvm::none_of(BB, [](const Instruction &I) {
4816 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4817 });
4818 };
4819 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4820 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4821 NoSideEffects(*BI->getParent())) {
4822 auto *OldSuccessor = BI->getSuccessor(1);
4823 OldSuccessor->removePredecessor(BI->getParent());
4824 BI->setSuccessor(1, IfFalseBB);
4825 if (DTU)
4826 DTU->applyUpdates(
4827 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4828 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4829 return true;
4830 }
4831 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4832 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4833 NoSideEffects(*BI->getParent())) {
4834 auto *OldSuccessor = BI->getSuccessor(0);
4835 OldSuccessor->removePredecessor(BI->getParent());
4836 BI->setSuccessor(0, IfFalseBB);
4837 if (DTU)
4838 DTU->applyUpdates(
4839 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4840 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4841 return true;
4842 }
4843 return false;
4844}
4845
4846/// If we have a conditional branch as a predecessor of another block,
4847/// this function tries to simplify it. We know
4848/// that PBI and BI are both conditional branches, and BI is in one of the
4849/// successor blocks of PBI - PBI branches to BI.
4851 DomTreeUpdater *DTU,
4852 const DataLayout &DL,
4853 const TargetTransformInfo &TTI) {
4854 BasicBlock *BB = BI->getParent();
4855
4856 // If this block ends with a branch instruction, and if there is a
4857 // predecessor that ends on a branch of the same condition, make
4858 // this conditional branch redundant.
4859 if (PBI->getCondition() == BI->getCondition() &&
4860 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4861 // Okay, the outcome of this conditional branch is statically
4862 // knowable. If this block had a single pred, handle specially, otherwise
4863 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4864 if (BB->getSinglePredecessor()) {
4865 // Turn this into a branch on constant.
4866 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4867 BI->setCondition(
4868 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4869 return true; // Nuke the branch on constant.
4870 }
4871 }
4872
4873 // If the previous block ended with a widenable branch, determine if reusing
4874 // the target block is profitable and legal. This will have the effect of
4875 // "widening" PBI, but doesn't require us to reason about hosting safety.
4876 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4877 return true;
4878
4879 // If both branches are conditional and both contain stores to the same
4880 // address, remove the stores from the conditionals and create a conditional
4881 // merged store at the end.
4882 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4883 return true;
4884
4885 // If this is a conditional branch in an empty block, and if any
4886 // predecessors are a conditional branch to one of our destinations,
4887 // fold the conditions into logical ops and one cond br.
4888
4889 // Ignore dbg intrinsics.
4890 if (&*BB->begin() != BI)
4891 return false;
4892
4893 int PBIOp, BIOp;
4894 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4895 PBIOp = 0;
4896 BIOp = 0;
4897 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4898 PBIOp = 0;
4899 BIOp = 1;
4900 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4901 PBIOp = 1;
4902 BIOp = 0;
4903 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4904 PBIOp = 1;
4905 BIOp = 1;
4906 } else {
4907 return false;
4908 }
4909
4910 // Check to make sure that the other destination of this branch
4911 // isn't BB itself. If so, this is an infinite loop that will
4912 // keep getting unwound.
4913 if (PBI->getSuccessor(PBIOp) == BB)
4914 return false;
4915
4916 // If predecessor's branch probability to BB is too low don't merge branches.
4917 SmallVector<uint32_t, 2> PredWeights;
4918 if (!PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4919 extractBranchWeights(*PBI, PredWeights) &&
4920 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4921
4923 PredWeights[PBIOp],
4924 static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4925
4926 BranchProbability Likely = TTI.getPredictableBranchThreshold();
4927 if (CommonDestProb >= Likely)
4928 return false;
4929 }
4930
4931 // Do not perform this transformation if it would require
4932 // insertion of a large number of select instructions. For targets
4933 // without predication/cmovs, this is a big pessimization.
4934
4935 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4936 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4937 unsigned NumPhis = 0;
4938 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4939 ++II, ++NumPhis) {
4940 if (NumPhis > 2) // Disable this xform.
4941 return false;
4942 }
4943
4944 // Finally, if everything is ok, fold the branches to logical ops.
4945 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4946
4947 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4948 << "AND: " << *BI->getParent());
4949
4951
4952 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4953 // branch in it, where one edge (OtherDest) goes back to itself but the other
4954 // exits. We don't *know* that the program avoids the infinite loop
4955 // (even though that seems likely). If we do this xform naively, we'll end up
4956 // recursively unpeeling the loop. Since we know that (after the xform is
4957 // done) that the block *is* infinite if reached, we just make it an obviously
4958 // infinite loop with no cond branch.
4959 if (OtherDest == BB) {
4960 // Insert it at the end of the function, because it's either code,
4961 // or it won't matter if it's hot. :)
4962 BasicBlock *InfLoopBlock =
4963 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4964 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
4965 if (DTU)
4966 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4967 OtherDest = InfLoopBlock;
4968 }
4969
4970 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4971
4972 // BI may have other predecessors. Because of this, we leave
4973 // it alone, but modify PBI.
4974
4975 // Make sure we get to CommonDest on True&True directions.
4976 Value *PBICond = PBI->getCondition();
4977 IRBuilder<NoFolder> Builder(PBI);
4978 if (PBIOp)
4979 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4980
4981 Value *BICond = BI->getCondition();
4982 if (BIOp)
4983 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4984
4985 // Merge the conditions.
4986 Value *Cond =
4987 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4988
4989 // Modify PBI to branch on the new condition to the new dests.
4990 PBI->setCondition(Cond);
4991 PBI->setSuccessor(0, CommonDest);
4992 PBI->setSuccessor(1, OtherDest);
4993
4994 if (DTU) {
4995 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4996 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4997
4998 DTU->applyUpdates(Updates);
4999 }
5000
5001 // Update branch weight for PBI.
5002 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
5003 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
5004 bool HasWeights =
5005 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
5006 SuccTrueWeight, SuccFalseWeight);
5007 if (HasWeights) {
5008 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
5009 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
5010 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
5011 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
5012 // The weight to CommonDest should be PredCommon * SuccTotal +
5013 // PredOther * SuccCommon.
5014 // The weight to OtherDest should be PredOther * SuccOther.
5015 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
5016 PredOther * SuccCommon,
5017 PredOther * SuccOther};
5018
5019 setFittedBranchWeights(*PBI, NewWeights, /*IsExpected=*/false,
5020 /*ElideAllZero=*/true);
5021 // Cond may be a select instruction with the first operand set to "true", or
5022 // the second to "false" (see how createLogicalOp works for `and` and `or`)
5023 if (auto *SI = dyn_cast<SelectInst>(Cond)) {
5024 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
5025 // The select is predicated on PBICond
5026 assert(SI->getCondition() == PBICond);
5027 // The corresponding probabilities are what was referred to above as
5028 // PredCommon and PredOther.
5029 setFittedBranchWeights(*SI, {PredCommon, PredOther},
5030 /*IsExpected=*/false, /*ElideAllZero=*/true);
5031 }
5032 }
5033
5034 // OtherDest may have phi nodes. If so, add an entry from PBI's
5035 // block that are identical to the entries for BI's block.
5036 addPredecessorToBlock(OtherDest, PBI->getParent(), BB);
5037
5038 // We know that the CommonDest already had an edge from PBI to
5039 // it. If it has PHIs though, the PHIs may have different
5040 // entries for BB and PBI's BB. If so, insert a select to make
5041 // them agree.
5042 for (PHINode &PN : CommonDest->phis()) {
5043 Value *BIV = PN.getIncomingValueForBlock(BB);
5044 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
5045 Value *PBIV = PN.getIncomingValue(PBBIdx);
5046 if (BIV != PBIV) {
5047 // Insert a select in PBI to pick the right value.
5049 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
5050 PN.setIncomingValue(PBBIdx, NV);
5051 // The select has the same condition as PBI, in the same BB. The
5052 // probabilities don't change.
5053 if (HasWeights) {
5054 uint64_t TrueWeight = PBIOp ? PredFalseWeight : PredTrueWeight;
5055 uint64_t FalseWeight = PBIOp ? PredTrueWeight : PredFalseWeight;
5056 setFittedBranchWeights(*NV, {TrueWeight, FalseWeight},
5057 /*IsExpected=*/false, /*ElideAllZero=*/true);
5058 }
5059 }
5060 }
5061
5062 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
5063 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
5064
5065 // This basic block is probably dead. We know it has at least
5066 // one fewer predecessor.
5067 return true;
5068}
5069
5070// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
5071// true or to FalseBB if Cond is false.
5072// Takes care of updating the successors and removing the old terminator.
5073// Also makes sure not to introduce new successors by assuming that edges to
5074// non-successor TrueBBs and FalseBBs aren't reachable.
5075bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
5076 Value *Cond, BasicBlock *TrueBB,
5077 BasicBlock *FalseBB,
5078 uint32_t TrueWeight,
5079 uint32_t FalseWeight) {
5080 auto *BB = OldTerm->getParent();
5081 // Remove any superfluous successor edges from the CFG.
5082 // First, figure out which successors to preserve.
5083 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
5084 // successor.
5085 BasicBlock *KeepEdge1 = TrueBB;
5086 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
5087
5088 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
5089
5090 // Then remove the rest.
5091 for (BasicBlock *Succ : successors(OldTerm)) {
5092 // Make sure only to keep exactly one copy of each edge.
5093 if (Succ == KeepEdge1)
5094 KeepEdge1 = nullptr;
5095 else if (Succ == KeepEdge2)
5096 KeepEdge2 = nullptr;
5097 else {
5098 Succ->removePredecessor(BB,
5099 /*KeepOneInputPHIs=*/true);
5100
5101 if (Succ != TrueBB && Succ != FalseBB)
5102 RemovedSuccessors.insert(Succ);
5103 }
5104 }
5105
5106 IRBuilder<> Builder(OldTerm);
5107 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
5108
5109 // Insert an appropriate new terminator.
5110 if (!KeepEdge1 && !KeepEdge2) {
5111 if (TrueBB == FalseBB) {
5112 // We were only looking for one successor, and it was present.
5113 // Create an unconditional branch to it.
5114 Builder.CreateBr(TrueBB);
5115 } else {
5116 // We found both of the successors we were looking for.
5117 // Create a conditional branch sharing the condition of the select.
5118 CondBrInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
5119 setBranchWeights(*NewBI, {TrueWeight, FalseWeight},
5120 /*IsExpected=*/false, /*ElideAllZero=*/true);
5121 }
5122 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
5123 // Neither of the selected blocks were successors, so this
5124 // terminator must be unreachable.
5125 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
5126 } else {
5127 // One of the selected values was a successor, but the other wasn't.
5128 // Insert an unconditional branch to the one that was found;
5129 // the edge to the one that wasn't must be unreachable.
5130 if (!KeepEdge1) {
5131 // Only TrueBB was found.
5132 Builder.CreateBr(TrueBB);
5133 } else {
5134 // Only FalseBB was found.
5135 Builder.CreateBr(FalseBB);
5136 }
5137 }
5138
5140
5141 if (DTU) {
5142 SmallVector<DominatorTree::UpdateType, 2> Updates;
5143 Updates.reserve(RemovedSuccessors.size());
5144 for (auto *RemovedSuccessor : RemovedSuccessors)
5145 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
5146 DTU->applyUpdates(Updates);
5147 }
5148
5149 return true;
5150}
5151
5152// Folds switch(select(icmp eq X, C, K, X)) into switch(X), retargeting
5153// (or adding) the case for C to wherever K currently dispatches to:
5154// %cmp = icmp eq T %x, C
5155// %key = select i1 %cmp, T K, T %x
5156// switch T %key, label %default [ T K, label %case_k ... ]
5157// becomes
5158// switch T %x, label %default [ T C, label %case_k
5159// T K, label %case_k ... ]
5160bool SimplifyCFGOpt::simplifySwitchOnSelectRemap(SwitchInst *SI,
5161 SelectInst *Select, Value *X,
5162 ConstantInt *C, bool Negate) {
5163 Value *TrueVal = Select->getTrueValue();
5164 Value *FalseVal = Select->getFalseValue();
5165 if (Negate)
5166 std::swap(TrueVal, FalseVal);
5167 if (FalseVal != X)
5168 return false;
5169 auto *K = dyn_cast<ConstantInt>(TrueVal);
5170 if (!K)
5171 return false;
5172
5173 BasicBlock *DestFork = SI->findCaseValue(K)->getCaseSuccessor();
5174 auto CaseC = SI->findCaseValue(C);
5175 bool IsDefault = CaseC == SI->case_default();
5176 // Save before setSuccessor()/addCase() change it.
5177 BasicBlock *OldDest = CaseC->getCaseSuccessor();
5178 BasicBlock *BB = SI->getParent();
5179
5180 // Switch on X first: removePredecessor() below may fold X away if it is a
5181 // PHI in OldDest, and the RAUW must update the switch condition too.
5182 SI->setCondition(X);
5183
5184 if (OldDest != DestFork) {
5185 if (!IsDefault)
5186 OldDest->removePredecessor(BB);
5187 if (IsDefault)
5188 SI->addCase(C, DestFork);
5189 else
5190 CaseC->setSuccessor(DestFork);
5191 // Not a new edge (BB->DestFork exists via K), just adding the PHI
5192 // entry.
5193 addPredecessorToBlock(DestFork, BB, BB);
5194
5195 if (!IsDefault) {
5196 // Edge to OldDest is gone only if nothing else still uses it.
5197 bool OldDestStillTargeted = any_of(
5198 successors(SI), [&](BasicBlock *Succ) { return Succ == OldDest; });
5199 if (DTU && !OldDestStillTargeted)
5200 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
5201 }
5202
5203 // Update the profile information on the switch if we had a profile
5204 // for both it and the select instruction.
5205 SmallVector<uint32_t> SwitchWeights;
5206 bool SwitchHasBranchWeights = extractBranchWeights(*SI, SwitchWeights);
5207 // If we add a case, ensure the length of the branch weights list matches
5208 // to make iterating over them easier later.
5209 if (IsDefault)
5210 SwitchWeights.push_back(0);
5213 bool SelectHasBranchWeights =
5215 uint64_t SelectTotalWeight = SelectTrueWeight + SelectFalseWeight;
5216 if (Negate)
5218 if (SwitchHasBranchWeights && SelectHasBranchWeights &&
5220 // We update the branch weights by subtracting P(x=C) from the probability
5221 // of case K in the switch (what C redirect to before the transformation),
5222 // plugging the probability for case C into the switch (which we derive
5223 // from the select), and ensuring everything is scaled to have a common
5224 // denominator.
5225 uint64_t SwitchTotalWeight = sum_of(SwitchWeights, uint64_t{0});
5226 SmallVector<uint64_t> NewSwitchWeights;
5227 NewSwitchWeights.reserve(SwitchWeights.size());
5228 NewSwitchWeights.push_back(SwitchWeights[0] * SelectTotalWeight);
5229 for (const auto &[SwitchCase, SwitchWeight] :
5230 zip(SI->cases(), drop_begin(SwitchWeights))) {
5231 if (SwitchCase.getCaseValue() == C) {
5232 NewSwitchWeights.push_back(SwitchTotalWeight * SelectTrueWeight);
5233 } else if (SwitchCase.getCaseValue() == K) {
5234 // In reality, P(key=K) > P(x=C) should always hold, but explicitly
5235 // guard against bad profiles here to prevent underflow by saturating
5236 // to zero.
5237 uint64_t ProbabilityKeyEqualsK = SwitchWeight * SelectTotalWeight;
5238 uint64_t ProbabilityXEqualsC = SelectTrueWeight * SwitchTotalWeight;
5239 uint64_t ProbabilityXEqualsK =
5240 ProbabilityKeyEqualsK > ProbabilityXEqualsC
5241 ? ProbabilityKeyEqualsK - ProbabilityXEqualsC
5242 : 0;
5243 NewSwitchWeights.push_back(ProbabilityXEqualsK);
5244 } else {
5245 NewSwitchWeights.push_back(SwitchWeight * SelectTotalWeight);
5246 }
5247 }
5248 setFittedBranchWeights(*SI, NewSwitchWeights, /*IsExpected=*/false);
5249 } else if (SwitchHasBranchWeights) {
5250 // If we only have branch weights on the switch, we cannot reconstruct
5251 // branch weights correctly, so mark them as unknown if the function has
5252 // a profile count. Reset the branch weights first to ensure we remove
5253 // the now invalid branch weights if the function is not otherwise
5254 // profiled.
5255 SI->setMetadata(LLVMContext::MD_prof, nullptr);
5257 }
5258 }
5259
5260 // The compare/select are now dead.
5262 return true;
5263}
5264
5265// Replaces
5266// (switch (select cond, X, Y)) on constant X, Y
5267// with a branch - conditional if X and Y lead to distinct BBs,
5268// unconditional otherwise.
5269bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
5270 SelectInst *Select) {
5271 CmpPredicate Pred;
5272 Value *X;
5273 ConstantInt *C;
5274 if (Select->hasOneUse() &&
5275 match(Select->getCondition(),
5276 m_ICmp(Pred, m_Value(X), m_ConstantInt(C))) &&
5277 ICmpInst::isEquality(Pred) &&
5278 simplifySwitchOnSelectRemap(SI, Select, X, C, Pred == ICmpInst::ICMP_NE))
5279 return true;
5280
5281 // Check for constant integer values in the select.
5282 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
5283 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
5284 if (!TrueVal || !FalseVal)
5285 return false;
5286
5287 // Find the relevant condition and destinations.
5288 Value *Condition = Select->getCondition();
5289 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
5290 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
5291
5292 // Get weight for TrueBB and FalseBB.
5293 uint32_t TrueWeight = 0, FalseWeight = 0;
5294 SmallVector<uint64_t, 8> Weights;
5295 bool HasWeights = hasBranchWeightMD(*SI);
5296 if (HasWeights) {
5297 getBranchWeights(SI, Weights);
5298 if (Weights.size() == 1 + SI->getNumCases()) {
5299 TrueWeight =
5300 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
5301 FalseWeight =
5302 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
5303 }
5304 }
5305
5306 // Perform the actual simplification.
5307 return simplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
5308 FalseWeight);
5309}
5310
5311// Replaces
5312// (indirectbr (select cond, blockaddress(@fn, BlockA),
5313// blockaddress(@fn, BlockB)))
5314// with
5315// (br cond, BlockA, BlockB).
5316bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
5317 SelectInst *SI) {
5318 // Check that both operands of the select are block addresses.
5319 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
5320 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
5321 if (!TBA || !FBA)
5322 return false;
5323
5324 // Extract the actual blocks.
5325 BasicBlock *TrueBB = TBA->getBasicBlock();
5326 BasicBlock *FalseBB = FBA->getBasicBlock();
5327
5328 // The select's profile becomes the profile of the conditional branch that
5329 // replaces the indirect branch.
5330 SmallVector<uint32_t> SelectBranchWeights(2);
5331 extractBranchWeights(*SI, SelectBranchWeights);
5332 // Perform the actual simplification.
5333 return simplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
5334 SelectBranchWeights[0],
5335 SelectBranchWeights[1]);
5336}
5337
5338/// This is called when we find an icmp instruction
5339/// (a seteq/setne with a constant) as the only instruction in a
5340/// block that ends with an uncond branch. We are looking for a very specific
5341/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
5342/// this case, we merge the first two "or's of icmp" into a switch, but then the
5343/// default value goes to an uncond block with a seteq in it, we get something
5344/// like:
5345///
5346/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
5347/// DEFAULT:
5348/// %tmp = icmp eq i8 %A, 92
5349/// br label %end
5350/// end:
5351/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
5352///
5353/// We prefer to split the edge to 'end' so that there is a true/false entry to
5354/// the PHI, merging the third icmp into the switch.
5355bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
5356 ICmpInst *ICI, IRBuilder<> &Builder) {
5357 // Select == nullptr means we assume that there is a hidden no-op select
5358 // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...`
5359 return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, nullptr, Builder);
5360}
5361
5362/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic
5363/// case. This is called when we find an icmp instruction (a seteq/setne with a
5364/// constant) and its following select instruction as the only TWO instructions
5365/// in a block that ends with an uncond branch. We are looking for a very
5366/// specific pattern that occurs when "
5367/// if (A == 1) return C1;
5368/// if (A == 2) return C2;
5369/// if (A < 3) return C3;
5370/// return C4;
5371/// " gets simplified. In this case, we merge the first two "branches of icmp"
5372/// into a switch, but then the default value goes to an uncond block with a lt
5373/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2".
5374/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might
5375/// get something like:
5376///
5377/// case1:
5378/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ]
5379/// case2:
5380/// br label %end
5381/// DEFAULT:
5382/// %tmp = icmp eq i8 %A, 2
5383/// %val = select i1 %tmp, i8 C3, i8 C4
5384/// br label %end
5385/// end:
5386/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ]
5387///
5388/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4
5389/// to the PHI, merging the icmp & select into the switch, as follows:
5390///
5391/// case1:
5392/// switch i8 %A, label %DEFAULT [
5393/// i8 0, label %end
5394/// i8 1, label %case2
5395/// i8 2, label %case3
5396/// ]
5397/// case2:
5398/// br label %end
5399/// case3:
5400/// br label %end
5401/// DEFAULT:
5402/// br label %end
5403/// end:
5404/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT]
5405bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
5406 ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) {
5407 BasicBlock *BB = ICI->getParent();
5408
5409 // If the block has any PHIs in it or the icmp/select has multiple uses, it is
5410 // too complex.
5411 /// TODO: support multi-phis in succ BB of select's BB.
5412 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse() ||
5413 (Select && !Select->hasOneUse()))
5414 return false;
5415
5416 // The pattern we're looking for is where our only predecessor is a switch on
5417 // 'V' and this block is the default case for the switch. In this case we can
5418 // fold the compared value into the switch to simplify things.
5419 BasicBlock *Pred = BB->getSinglePredecessor();
5420 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
5421 return false;
5422
5423 Value *IcmpCond;
5424 ConstantInt *NewCaseVal;
5425 CmpPredicate Predicate;
5426
5427 // Match icmp X, C
5428 if (!match(ICI,
5429 m_ICmp(Predicate, m_Value(IcmpCond), m_ConstantInt(NewCaseVal))))
5430 return false;
5431
5432 Value *SelectCond, *SelectTrueVal, *SelectFalseVal;
5434 if (!Select) {
5435 // If Select == nullptr, we can assume that there is a hidden no-op select
5436 // just after icmp
5437 SelectCond = ICI;
5438 SelectTrueVal = Builder.getTrue();
5439 SelectFalseVal = Builder.getFalse();
5440 User = ICI->user_back();
5441 } else {
5442 SelectCond = Select->getCondition();
5443 // Check if the select condition is the same as the icmp condition.
5444 if (SelectCond != ICI)
5445 return false;
5446 SelectTrueVal = Select->getTrueValue();
5447 SelectFalseVal = Select->getFalseValue();
5448 User = Select->user_back();
5449 }
5450
5451 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
5452 if (SI->getCondition() != IcmpCond)
5453 return false;
5454
5455 // If BB is reachable on a non-default case, then we simply know the value of
5456 // V in this block. Substitute it and constant fold the icmp instruction
5457 // away.
5458 if (SI->getDefaultDest() != BB) {
5459 ConstantInt *VVal = SI->findCaseDest(BB);
5460 assert(VVal && "Should have a unique destination value");
5461 ICI->setOperand(0, VVal);
5462
5463 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
5464 ICI->replaceAllUsesWith(V);
5465 ICI->eraseFromParent();
5466 }
5467 // BB is now empty, so it is likely to simplify away.
5468 return requestResimplify();
5469 }
5470
5471 // Ok, the block is reachable from the default dest. If the constant we're
5472 // comparing exists in one of the other edges, then we can constant fold ICI
5473 // and zap it.
5474 if (SI->findCaseValue(NewCaseVal) != SI->case_default()) {
5475 Value *V;
5476 if (Predicate == ICmpInst::ICMP_EQ)
5478 else
5480
5481 ICI->replaceAllUsesWith(V);
5482 ICI->eraseFromParent();
5483 // BB is now empty, so it is likely to simplify away.
5484 return requestResimplify();
5485 }
5486
5487 // The use of the select has to be in the 'end' block, by the only PHI node in
5488 // the block.
5489 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
5490 PHINode *PHIUse = dyn_cast<PHINode>(User);
5491 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
5493 return false;
5494
5495 // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new
5496 // edge gets SelectTrueVal in the PHI.
5497 Value *DefaultCst = SelectFalseVal;
5498 Value *NewCst = SelectTrueVal;
5499
5500 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
5501 std::swap(DefaultCst, NewCst);
5502
5503 // Replace Select (which is used by the PHI for the default value) with
5504 // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE.
5505 if (Select) {
5506 Select->replaceAllUsesWith(DefaultCst);
5507 Select->eraseFromParent();
5508 } else {
5509 ICI->replaceAllUsesWith(DefaultCst);
5510 }
5511 ICI->eraseFromParent();
5512
5513 SmallVector<DominatorTree::UpdateType, 2> Updates;
5514
5515 // Okay, the switch goes to this block on a default value. Add an edge from
5516 // the switch to the merge point on the compared value.
5517 BasicBlock *NewBB =
5518 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
5519 {
5520 SwitchInstProfUpdateWrapper SIW(*SI);
5521 auto W0 = SIW.getSuccessorWeight(0);
5523 if (W0) {
5524 NewW = ((uint64_t(*W0) + 1) >> 1);
5525 SIW.setSuccessorWeight(0, *NewW);
5526 }
5527 SIW.addCase(NewCaseVal, NewBB, NewW);
5528 if (DTU)
5529 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
5530 }
5531
5532 // NewBB branches to the phi block, add the uncond branch and the phi entry.
5533 Builder.SetInsertPoint(NewBB);
5534 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
5535 Builder.CreateBr(SuccBlock);
5536 PHIUse->addIncoming(NewCst, NewBB);
5537 if (DTU) {
5538 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
5539 DTU->applyUpdates(Updates);
5540 }
5541 return true;
5542}
5543
5544/// Check to see if it is branching on an or/and chain of icmp instructions, and
5545/// fold it into a switch instruction if so.
5546bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
5547 IRBuilder<> &Builder,
5548 const DataLayout &DL) {
5550 if (!Cond)
5551 return false;
5552
5553 // Change br (X == 0 | X == 1), T, F into a switch instruction.
5554 // If this is a bunch of seteq's or'd together, or if it's a bunch of
5555 // 'setne's and'ed together, collect them.
5556
5557 // Try to gather values from a chain of and/or to be turned into a switch
5558 ConstantComparesGatherer ConstantCompare(Cond, DL);
5559 // Unpack the result
5560 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
5561 Value *CompVal = ConstantCompare.CompValue;
5562 unsigned UsedICmps = ConstantCompare.UsedICmps;
5563 Value *ExtraCase = ConstantCompare.Extra;
5564 bool TrueWhenEqual = ConstantCompare.IsEq;
5565
5566 // If we didn't have a multiply compared value, fail.
5567 if (!CompVal)
5568 return false;
5569
5570 // Avoid turning single icmps into a switch.
5571 if (UsedICmps <= 1)
5572 return false;
5573
5574 // There might be duplicate constants in the list, which the switch
5575 // instruction can't handle, remove them now.
5577 Values.erase(llvm::unique(Values), Values.end());
5578
5579 // If Extra was used, we require at least two switch values to do the
5580 // transformation. A switch with one value is just a conditional branch.
5581 if (ExtraCase && Values.size() < 2)
5582 return false;
5583
5584 SmallVector<uint32_t> BranchWeights;
5585 const bool HasProfile = extractBranchWeights(*BI, BranchWeights);
5586
5587 // Figure out which block is which destination.
5588 BasicBlock *DefaultBB = BI->getSuccessor(1);
5589 BasicBlock *EdgeBB = BI->getSuccessor(0);
5590 if (!TrueWhenEqual) {
5591 std::swap(DefaultBB, EdgeBB);
5592 if (HasProfile)
5593 std::swap(BranchWeights[0], BranchWeights[1]);
5594 }
5595
5596 BasicBlock *BB = BI->getParent();
5597
5598 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
5599 << " cases into SWITCH. BB is:\n"
5600 << *BB);
5601
5602 SmallVector<DominatorTree::UpdateType, 2> Updates;
5603
5604 // If there are any extra values that couldn't be folded into the switch
5605 // then we evaluate them with an explicit branch first. Split the block
5606 // right before the condbr to handle it.
5607 if (ExtraCase) {
5608 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
5609 /*MSSAU=*/nullptr, "switch.early.test");
5610
5611 // Remove the uncond branch added to the old block.
5612 Instruction *OldTI = BB->getTerminator();
5613 Builder.SetInsertPoint(OldTI);
5614
5615 // There can be an unintended UB if extra values are Poison. Before the
5616 // transformation, extra values may not be evaluated according to the
5617 // condition, and it will not raise UB. But after transformation, we are
5618 // evaluating extra values before checking the condition, and it will raise
5619 // UB. It can be solved by adding freeze instruction to extra values.
5620 AssumptionCache *AC = Options.AC;
5621
5622 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
5623 ExtraCase = Builder.CreateFreeze(ExtraCase);
5624
5625 // We don't have any info about this condition.
5626 auto *Br = TrueWhenEqual ? Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB)
5627 : Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
5629
5630 OldTI->eraseFromParent();
5631
5632 if (DTU)
5633 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
5634
5635 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
5636 // for the edge we just added.
5637 addPredecessorToBlock(EdgeBB, BB, NewBB);
5638
5639 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
5640 << "\nEXTRABB = " << *BB);
5641 BB = NewBB;
5642 }
5643
5644 Builder.SetInsertPoint(BI);
5645 // Convert pointer to int before we switch.
5646 if (CompVal->getType()->isPointerTy()) {
5647 assert(!DL.hasUnstableRepresentation(CompVal->getType()) &&
5648 "Should not end up here with unstable pointers");
5649 CompVal = Builder.CreatePtrToInt(
5650 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
5651 }
5652
5653 // Check if we can represent the values as a contiguous range. If so, we use a
5654 // range check + conditional branch instead of a switch.
5655 if (Values.front()->getValue() - Values.back()->getValue() ==
5656 Values.size() - 1) {
5657 ConstantRange RangeToCheck = ConstantRange::getNonEmpty(
5658 Values.back()->getValue(), Values.front()->getValue() + 1);
5659 APInt Offset, RHS;
5660 ICmpInst::Predicate Pred;
5661 RangeToCheck.getEquivalentICmp(Pred, RHS, Offset);
5662 Value *X = CompVal;
5663 if (!Offset.isZero())
5664 X = Builder.CreateAdd(X, ConstantInt::get(CompVal->getType(), Offset));
5665 Value *Cond =
5666 Builder.CreateICmp(Pred, X, ConstantInt::get(CompVal->getType(), RHS));
5667 CondBrInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
5668 if (HasProfile)
5669 setBranchWeights(*NewBI, BranchWeights, /*IsExpected=*/false);
5670 else
5672 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5673 NewBI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5674 // We don't need to update PHI nodes since we don't add any new edges.
5675 } else {
5676 // Create the new switch instruction now.
5677 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
5678 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5679 New->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5680 if (HasProfile) {
5681 // We know the weight of the default case. We don't know the weight of the
5682 // other cases, but rather than completely lose profiling info, we split
5683 // the remaining probability equally over them.
5684 SmallVector<uint32_t> NewWeights(Values.size() + 1);
5685 NewWeights[0] = BranchWeights[1]; // this is the default, and we swapped
5686 // if TrueWhenEqual.
5687 for (auto &V : drop_begin(NewWeights))
5688 V = BranchWeights[0] / Values.size();
5689 setBranchWeights(*New, NewWeights, /*IsExpected=*/false);
5690 } else {
5692 }
5693
5694 // Add all of the 'cases' to the switch instruction.
5695 for (ConstantInt *Val : Values)
5696 New->addCase(Val, EdgeBB);
5697
5698 // We added edges from PI to the EdgeBB. As such, if there were any
5699 // PHI nodes in EdgeBB, they need entries to be added corresponding to
5700 // the number of edges added.
5701 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
5702 PHINode *PN = cast<PHINode>(BBI);
5703 Value *InVal = PN->getIncomingValueForBlock(BB);
5704 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5705 PN->addIncoming(InVal, BB);
5706 }
5707 }
5708
5709 // Erase the old branch instruction.
5711 if (DTU)
5712 DTU->applyUpdates(Updates);
5713
5714 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5715 return true;
5716}
5717
5718bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5719 if (isa<PHINode>(RI->getValue()))
5720 return simplifyCommonResume(RI);
5721 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHIIt()) &&
5722 RI->getValue() == &*RI->getParent()->getFirstNonPHIIt())
5723 // The resume must unwind the exception that caused control to branch here.
5724 return simplifySingleResume(RI);
5725
5726 return false;
5727}
5728
5729// Check if cleanup block is empty
5731 for (Instruction &I : R) {
5732 auto *II = dyn_cast<IntrinsicInst>(&I);
5733 if (!II || II->getIntrinsicID() != Intrinsic::lifetime_end)
5734 return false;
5735 }
5736 return true;
5737}
5738
5739// Simplify resume that is shared by several landing pads (phi of landing pad).
5740bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5741 BasicBlock *BB = RI->getParent();
5742
5743 // Check that there are no other instructions except for debug and lifetime
5744 // intrinsics between the phi's and resume instruction.
5745 if (!isCleanupBlockEmpty(make_range(RI->getParent()->getFirstNonPHIIt(),
5746 BB->getTerminator()->getIterator())))
5747 return false;
5748
5749 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5750 auto *PhiLPInst = cast<PHINode>(RI->getValue());
5751
5752 // Check incoming blocks to see if any of them are trivial.
5753 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5754 Idx++) {
5755 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
5756 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
5757
5758 // If the block has other successors, we can not delete it because
5759 // it has other dependents.
5760 if (IncomingBB->getUniqueSuccessor() != BB)
5761 continue;
5762
5763 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHIIt());
5764 // Not the landing pad that caused the control to branch here.
5765 if (IncomingValue != LandingPad)
5766 continue;
5767
5769 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
5770 TrivialUnwindBlocks.insert(IncomingBB);
5771 }
5772
5773 // If no trivial unwind blocks, don't do any simplifications.
5774 if (TrivialUnwindBlocks.empty())
5775 return false;
5776
5777 // Turn all invokes that unwind here into calls.
5778 for (auto *TrivialBB : TrivialUnwindBlocks) {
5779 // Blocks that will be simplified should be removed from the phi node.
5780 // Note there could be multiple edges to the resume block, and we need
5781 // to remove them all.
5782 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
5783 BB->removePredecessor(TrivialBB, true);
5784
5785 for (BasicBlock *Pred :
5787 removeUnwindEdge(Pred, DTU);
5788 ++NumInvokes;
5789 }
5790
5791 // In each SimplifyCFG run, only the current processed block can be erased.
5792 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5793 // of erasing TrivialBB, we only remove the branch to the common resume
5794 // block so that we can later erase the resume block since it has no
5795 // predecessors.
5796 TrivialBB->getTerminator()->eraseFromParent();
5797 new UnreachableInst(RI->getContext(), TrivialBB);
5798 if (DTU)
5799 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
5800 }
5801
5802 // Delete the resume block if all its predecessors have been removed.
5803 if (pred_empty(BB))
5804 DeleteDeadBlock(BB, DTU);
5805
5806 return !TrivialUnwindBlocks.empty();
5807}
5808
5809// Simplify resume that is only used by a single (non-phi) landing pad.
5810bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5811 BasicBlock *BB = RI->getParent();
5812 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHIIt());
5813 assert(RI->getValue() == LPInst &&
5814 "Resume must unwind the exception that caused control to here");
5815
5816 // Check that there are no other instructions except for debug intrinsics.
5818 make_range<Instruction *>(LPInst->getNextNode(), RI)))
5819 return false;
5820
5821 // Turn all invokes that unwind here into calls and delete the basic block.
5822 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
5823 removeUnwindEdge(Pred, DTU);
5824 ++NumInvokes;
5825 }
5826
5827 // The landingpad is now unreachable. Zap it.
5828 DeleteDeadBlock(BB, DTU);
5829 return true;
5830}
5831
5833 // If this is a trivial cleanup pad that executes no instructions, it can be
5834 // eliminated. If the cleanup pad continues to the caller, any predecessor
5835 // that is an EH pad will be updated to continue to the caller and any
5836 // predecessor that terminates with an invoke instruction will have its invoke
5837 // instruction converted to a call instruction. If the cleanup pad being
5838 // simplified does not continue to the caller, each predecessor will be
5839 // updated to continue to the unwind destination of the cleanup pad being
5840 // simplified.
5841 BasicBlock *BB = RI->getParent();
5842 CleanupPadInst *CPInst = RI->getCleanupPad();
5843 if (CPInst->getParent() != BB)
5844 // This isn't an empty cleanup.
5845 return false;
5846
5847 // We cannot kill the pad if it has multiple uses. This typically arises
5848 // from unreachable basic blocks.
5849 if (!CPInst->hasOneUse())
5850 return false;
5851
5852 // Check that there are no other instructions except for benign intrinsics.
5854 make_range<Instruction *>(CPInst->getNextNode(), RI)))
5855 return false;
5856
5857 // If the cleanup return we are simplifying unwinds to the caller, this will
5858 // set UnwindDest to nullptr.
5859 BasicBlock *UnwindDest = RI->getUnwindDest();
5860
5861 // We're about to remove BB from the control flow. Before we do, sink any
5862 // PHINodes into the unwind destination. Doing this before changing the
5863 // control flow avoids some potentially slow checks, since we can currently
5864 // be certain that UnwindDest and BB have no common predecessors (since they
5865 // are both EH pads).
5866 if (UnwindDest) {
5867 // First, go through the PHI nodes in UnwindDest and update any nodes that
5868 // reference the block we are removing
5869 for (PHINode &DestPN : UnwindDest->phis()) {
5870 int Idx = DestPN.getBasicBlockIndex(BB);
5871 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5872 assert(Idx != -1);
5873 // This PHI node has an incoming value that corresponds to a control
5874 // path through the cleanup pad we are removing. If the incoming
5875 // value is in the cleanup pad, it must be a PHINode (because we
5876 // verified above that the block is otherwise empty). Otherwise, the
5877 // value is either a constant or a value that dominates the cleanup
5878 // pad being removed.
5879 //
5880 // Because BB and UnwindDest are both EH pads, all of their
5881 // predecessors must unwind to these blocks, and since no instruction
5882 // can have multiple unwind destinations, there will be no overlap in
5883 // incoming blocks between SrcPN and DestPN.
5884 Value *SrcVal = DestPN.getIncomingValue(Idx);
5885 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
5886
5887 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5888 for (auto *Pred : predecessors(BB)) {
5889 Value *Incoming =
5890 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
5891 DestPN.addIncoming(Incoming, Pred);
5892 }
5893 }
5894
5895 // Sink any remaining PHI nodes directly into UnwindDest.
5896 BasicBlock::iterator InsertPt = UnwindDest->getFirstNonPHIIt();
5897 for (PHINode &PN : make_early_inc_range(BB->phis())) {
5898 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5899 // If the PHI node has no uses or all of its uses are in this basic
5900 // block (meaning they are debug or lifetime intrinsics), just leave
5901 // it. It will be erased when we erase BB below.
5902 continue;
5903
5904 // Otherwise, sink this PHI node into UnwindDest.
5905 // Any predecessors to UnwindDest which are not already represented
5906 // must be back edges which inherit the value from the path through
5907 // BB. In this case, the PHI value must reference itself.
5908 for (auto *pred : predecessors(UnwindDest))
5909 if (pred != BB)
5910 PN.addIncoming(&PN, pred);
5911 PN.moveBefore(InsertPt);
5912 // Also, add a dummy incoming value for the original BB itself,
5913 // so that the PHI is well-formed until we drop said predecessor.
5914 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5915 }
5916 }
5917
5918 std::vector<DominatorTree::UpdateType> Updates;
5919
5920 // We use make_early_inc_range here because we will remove all predecessors.
5922 if (UnwindDest == nullptr) {
5923 if (DTU) {
5924 DTU->applyUpdates(Updates);
5925 Updates.clear();
5926 }
5927 removeUnwindEdge(PredBB, DTU);
5928 ++NumInvokes;
5929 } else {
5930 BB->removePredecessor(PredBB);
5931 Instruction *TI = PredBB->getTerminator();
5932 TI->replaceUsesOfWith(BB, UnwindDest);
5933 if (DTU) {
5934 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5935 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5936 }
5937 }
5938 }
5939
5940 if (DTU)
5941 DTU->applyUpdates(Updates);
5942
5943 DeleteDeadBlock(BB, DTU);
5944
5945 return true;
5946}
5947
5948// Try to merge two cleanuppads together.
5950 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5951 // with.
5952 BasicBlock *UnwindDest = RI->getUnwindDest();
5953 if (!UnwindDest)
5954 return false;
5955
5956 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5957 // be safe to merge without code duplication.
5958 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5959 return false;
5960
5961 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5962 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5963 if (!SuccessorCleanupPad)
5964 return false;
5965
5966 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5967 // Replace any uses of the successor cleanupad with the predecessor pad
5968 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5969 // funclet bundle operands.
5970 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5971 // Remove the old cleanuppad.
5972 SuccessorCleanupPad->eraseFromParent();
5973 // Now, we simply replace the cleanupret with a branch to the unwind
5974 // destination.
5975 UncondBrInst::Create(UnwindDest, RI->getParent());
5976 RI->eraseFromParent();
5977
5978 return true;
5979}
5980
5981bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5982 // It is possible to transiantly have an undef cleanuppad operand because we
5983 // have deleted some, but not all, dead blocks.
5984 // Eventually, this block will be deleted.
5985 if (isa<UndefValue>(RI->getOperand(0)))
5986 return false;
5987
5988 if (mergeCleanupPad(RI))
5989 return true;
5990
5991 if (removeEmptyCleanup(RI, DTU))
5992 return true;
5993
5994 return false;
5995}
5996
5997// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5998bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5999 BasicBlock *BB = UI->getParent();
6000
6001 bool Changed = false;
6002
6003 // Ensure that any debug-info records that used to occur after the Unreachable
6004 // are moved to in front of it -- otherwise they'll "dangle" at the end of
6005 // the block.
6007
6008 // Debug-info records on the unreachable inst itself should be deleted, as
6009 // below we delete everything past the final executable instruction.
6010 UI->dropDbgRecords();
6011
6012 // If there are any instructions immediately before the unreachable that can
6013 // be removed, do so.
6014 while (UI->getIterator() != BB->begin()) {
6016 --BBI;
6017
6019 break; // Can not drop any more instructions. We're done here.
6020 // Otherwise, this instruction can be freely erased,
6021 // even if it is not side-effect free.
6022
6023 // Note that deleting EH's here is in fact okay, although it involves a bit
6024 // of subtle reasoning. If this inst is an EH, all the predecessors of this
6025 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
6026 // and we can therefore guarantee this block will be erased.
6027
6028 // If we're deleting this, we're deleting any subsequent debug info, so
6029 // delete DbgRecords.
6030 BBI->dropDbgRecords();
6031
6032 // Delete this instruction (any uses are guaranteed to be dead)
6033 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
6034 BBI->eraseFromParent();
6035 Changed = true;
6036 }
6037
6038 // If the unreachable instruction is the first in the block, take a gander
6039 // at all of the predecessors of this instruction, and simplify them.
6040 if (&BB->front() != UI)
6041 return Changed;
6042
6043 std::vector<DominatorTree::UpdateType> Updates;
6044
6045 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
6046 for (BasicBlock *Predecessor : Preds) {
6047 Instruction *TI = Predecessor->getTerminator();
6048 IRBuilder<> Builder(TI);
6049 if (isa<UncondBrInst>(TI)) {
6050 new UnreachableInst(TI->getContext(), TI->getIterator());
6051 TI->eraseFromParent();
6052 Changed = true;
6053 if (DTU)
6054 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6055 } else if (auto *BI = dyn_cast<CondBrInst>(TI)) {
6056 // We could either have a proper unconditional branch,
6057 // or a degenerate conditional branch with matching destinations.
6058 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
6059 new UnreachableInst(TI->getContext(), TI->getIterator());
6060 TI->eraseFromParent();
6061 Changed = true;
6062 } else {
6063 Value* Cond = BI->getCondition();
6064 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
6065 "The destinations are guaranteed to be different here.");
6066 CallInst *Assumption;
6067 if (BI->getSuccessor(0) == BB) {
6068 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
6069 Builder.CreateBr(BI->getSuccessor(1));
6070 } else {
6071 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
6072 Assumption = Builder.CreateAssumption(Cond);
6073 Builder.CreateBr(BI->getSuccessor(0));
6074 }
6075 if (Options.AC)
6076 Options.AC->registerAssumption(cast<AssumeInst>(Assumption));
6077
6079 Changed = true;
6080 }
6081 if (DTU)
6082 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6083 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
6084 SwitchInstProfUpdateWrapper SU(*SI);
6085 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
6086 if (i->getCaseSuccessor() != BB) {
6087 ++i;
6088 continue;
6089 }
6090 BB->removePredecessor(SU->getParent());
6091 i = SU.removeCase(i);
6092 e = SU->case_end();
6093 Changed = true;
6094 }
6095 // Note that the default destination can't be removed!
6096 if (DTU && SI->getDefaultDest() != BB)
6097 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6098 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
6099 if (II->getUnwindDest() == BB) {
6100 if (DTU) {
6101 DTU->applyUpdates(Updates);
6102 Updates.clear();
6103 }
6104 auto *CI = cast<CallInst>(removeUnwindEdge(TI->getParent(), DTU));
6105 if (!CI->doesNotThrow())
6106 CI->setDoesNotThrow();
6107 Changed = true;
6108 }
6109 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
6110 if (CSI->getUnwindDest() == BB) {
6111 if (DTU) {
6112 DTU->applyUpdates(Updates);
6113 Updates.clear();
6114 }
6115 removeUnwindEdge(TI->getParent(), DTU);
6116 Changed = true;
6117 continue;
6118 }
6119
6120 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
6121 E = CSI->handler_end();
6122 I != E; ++I) {
6123 if (*I == BB) {
6124 CSI->removeHandler(I);
6125 --I;
6126 --E;
6127 Changed = true;
6128 }
6129 }
6130 if (DTU)
6131 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6132 if (CSI->getNumHandlers() == 0) {
6133 if (CSI->hasUnwindDest()) {
6134 // Redirect all predecessors of the block containing CatchSwitchInst
6135 // to instead branch to the CatchSwitchInst's unwind destination.
6136 if (DTU) {
6137 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
6138 Updates.push_back({DominatorTree::Insert,
6139 PredecessorOfPredecessor,
6140 CSI->getUnwindDest()});
6141 Updates.push_back({DominatorTree::Delete,
6142 PredecessorOfPredecessor, Predecessor});
6143 }
6144 }
6145 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
6146 } else {
6147 // Rewrite all preds to unwind to caller (or from invoke to call).
6148 if (DTU) {
6149 DTU->applyUpdates(Updates);
6150 Updates.clear();
6151 }
6152 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
6153 for (BasicBlock *EHPred : EHPreds)
6154 removeUnwindEdge(EHPred, DTU);
6155 }
6156 // The catchswitch is no longer reachable.
6157 new UnreachableInst(CSI->getContext(), CSI->getIterator());
6158 CSI->eraseFromParent();
6159 Changed = true;
6160 }
6161 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
6162 (void)CRI;
6163 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
6164 "Expected to always have an unwind to BB.");
6165 if (DTU)
6166 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6167 new UnreachableInst(TI->getContext(), TI->getIterator());
6168 TI->eraseFromParent();
6169 Changed = true;
6170 }
6171 }
6172
6173 if (DTU)
6174 DTU->applyUpdates(Updates);
6175
6176 // If this block is now dead, remove it.
6177 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
6178 DeleteDeadBlock(BB, DTU);
6179 return true;
6180 }
6181
6182 return Changed;
6183}
6184
6193
6194static std::optional<ContiguousCasesResult>
6197 BasicBlock *Dest, BasicBlock *OtherDest) {
6198 assert(Cases.size() >= 1);
6199
6201 const APInt &Min = Cases.back()->getValue();
6202 const APInt &Max = Cases.front()->getValue();
6203 APInt Offset = Max - Min;
6204 size_t ContiguousOffset = Cases.size() - 1;
6205 if (Offset == ContiguousOffset) {
6206 return ContiguousCasesResult{
6207 /*Min=*/Cases.back(),
6208 /*Max=*/Cases.front(),
6209 /*Dest=*/Dest,
6210 /*OtherDest=*/OtherDest,
6211 /*Cases=*/&Cases,
6212 /*OtherCases=*/&OtherCases,
6213 };
6214 }
6215 ConstantRange CR = computeConstantRange(Condition, /*ForSigned=*/false,
6216 SimplifyQuery(Dest->getDataLayout()));
6217 // If this is a wrapping contiguous range, that is, [Min, OtherMin] +
6218 // [OtherMax, Max] (also [OtherMax, OtherMin]), [OtherMin+1, OtherMax-1] is a
6219 // contiguous range for the other destination. N.B. If CR is not a full range,
6220 // Max+1 is not equal to Min. It's not continuous in arithmetic.
6221 if (Max == CR.getUnsignedMax() && Min == CR.getUnsignedMin()) {
6222 assert(Cases.size() >= 2);
6223 auto *It =
6224 std::adjacent_find(Cases.begin(), Cases.end(), [](auto L, auto R) {
6225 return L->getValue() != R->getValue() + 1;
6226 });
6227 if (It == Cases.end())
6228 return std::nullopt;
6229 auto [OtherMax, OtherMin] = std::make_pair(*It, *std::next(It));
6230 if ((Max - OtherMax->getValue()) + (OtherMin->getValue() - Min) ==
6231 Cases.size() - 2) {
6232 return ContiguousCasesResult{
6233 /*Min=*/cast<ConstantInt>(
6234 ConstantInt::get(OtherMin->getType(), OtherMin->getValue() + 1)),
6235 /*Max=*/
6237 ConstantInt::get(OtherMax->getType(), OtherMax->getValue() - 1)),
6238 /*Dest=*/OtherDest,
6239 /*OtherDest=*/Dest,
6240 /*Cases=*/&OtherCases,
6241 /*OtherCases=*/&Cases,
6242 };
6243 }
6244 }
6245 return std::nullopt;
6246}
6247
6249 DomTreeUpdater *DTU,
6250 bool RemoveOrigDefaultBlock = true) {
6251 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
6252 auto *BB = Switch->getParent();
6253 auto *OrigDefaultBlock = Switch->getDefaultDest();
6254 if (RemoveOrigDefaultBlock)
6255 OrigDefaultBlock->removePredecessor(BB);
6256 BasicBlock *NewDefaultBlock = BasicBlock::Create(
6257 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
6258 OrigDefaultBlock);
6259 auto *UI = new UnreachableInst(Switch->getContext(), NewDefaultBlock);
6261 Switch->setDefaultDest(&*NewDefaultBlock);
6262 if (DTU) {
6264 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
6265 if (RemoveOrigDefaultBlock &&
6266 !is_contained(successors(BB), OrigDefaultBlock))
6267 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
6268 DTU->applyUpdates(Updates);
6269 }
6270}
6271
6272/// Turn a switch into an integer range comparison and branch.
6273/// Switches with more than 2 destinations are ignored.
6274/// Switches with 1 destination are also ignored.
6275bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
6276 IRBuilder<> &Builder) {
6277 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6278
6279 bool HasDefault = !SI->defaultDestUnreachable();
6280
6281 auto *BB = SI->getParent();
6282 // Partition the cases into two sets with different destinations.
6283 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
6284 BasicBlock *DestB = nullptr;
6287
6288 for (auto Case : SI->cases()) {
6289 BasicBlock *Dest = Case.getCaseSuccessor();
6290 if (!DestA)
6291 DestA = Dest;
6292 if (Dest == DestA) {
6293 CasesA.push_back(Case.getCaseValue());
6294 continue;
6295 }
6296 if (!DestB)
6297 DestB = Dest;
6298 if (Dest == DestB) {
6299 CasesB.push_back(Case.getCaseValue());
6300 continue;
6301 }
6302 return false; // More than two destinations.
6303 }
6304 if (!DestB)
6305 return false; // All destinations are the same and the default is unreachable
6306
6307 assert(DestA && DestB &&
6308 "Single-destination switch should have been folded.");
6309 assert(DestA != DestB);
6310 assert(DestB != SI->getDefaultDest());
6311 assert(!CasesB.empty() && "There must be non-default cases.");
6312 assert(!CasesA.empty() || HasDefault);
6313
6314 // Figure out if one of the sets of cases form a contiguous range.
6315 std::optional<ContiguousCasesResult> ContiguousCases;
6316
6317 // Only one icmp is needed when there is only one case.
6318 if (!HasDefault && CasesA.size() == 1)
6319 ContiguousCases = ContiguousCasesResult{
6320 /*Min=*/CasesA[0],
6321 /*Max=*/CasesA[0],
6322 /*Dest=*/DestA,
6323 /*OtherDest=*/DestB,
6324 /*Cases=*/&CasesA,
6325 /*OtherCases=*/&CasesB,
6326 };
6327 else if (CasesB.size() == 1)
6328 ContiguousCases = ContiguousCasesResult{
6329 /*Min=*/CasesB[0],
6330 /*Max=*/CasesB[0],
6331 /*Dest=*/DestB,
6332 /*OtherDest=*/DestA,
6333 /*Cases=*/&CasesB,
6334 /*OtherCases=*/&CasesA,
6335 };
6336 // Correctness: Cases to the default destination cannot be contiguous cases.
6337 else if (!HasDefault)
6338 ContiguousCases =
6339 findContiguousCases(SI->getCondition(), CasesA, CasesB, DestA, DestB);
6340
6341 if (!ContiguousCases)
6342 ContiguousCases =
6343 findContiguousCases(SI->getCondition(), CasesB, CasesA, DestB, DestA);
6344
6345 if (!ContiguousCases)
6346 return false;
6347
6348 auto [Min, Max, Dest, OtherDest, Cases, OtherCases] = *ContiguousCases;
6349
6350 // Start building the compare and branch.
6351
6353 Constant *NumCases = ConstantInt::get(Offset->getType(),
6354 Max->getValue() - Min->getValue() + 1);
6355 Instruction *NewBI;
6356 if (NumCases->isOneValue()) {
6357 assert(Max->getValue() == Min->getValue());
6358 Value *Cmp = Builder.CreateICmpEQ(SI->getCondition(), Min);
6359 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6360 }
6361 // If NumCases overflowed, then all possible values jump to the successor.
6362 else if (NumCases->isNullValue() && !Cases->empty()) {
6363 NewBI = Builder.CreateBr(Dest);
6364 } else {
6365 Value *Sub = SI->getCondition();
6366 if (!Offset->isNullValue())
6367 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
6368 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
6369 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6370 }
6371
6372 // Update weight for the newly-created conditional branch.
6373 if (hasBranchWeightMD(*SI) && isa<CondBrInst>(NewBI)) {
6374 SmallVector<uint64_t, 8> Weights;
6375 getBranchWeights(SI, Weights);
6376 if (Weights.size() == 1 + SI->getNumCases()) {
6377 uint64_t TrueWeight = 0;
6378 uint64_t FalseWeight = 0;
6379 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
6380 if (SI->getSuccessor(I) == Dest)
6381 TrueWeight += Weights[I];
6382 else
6383 FalseWeight += Weights[I];
6384 }
6385 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
6386 TrueWeight /= 2;
6387 FalseWeight /= 2;
6388 }
6389 setFittedBranchWeights(*NewBI, {TrueWeight, FalseWeight},
6390 /*IsExpected=*/false, /*ElideAllZero=*/true);
6391 }
6392 }
6393
6394 // Prune obsolete incoming values off the successors' PHI nodes.
6395 for (auto &PHI : make_early_inc_range(Dest->phis())) {
6396 unsigned PreviousEdges = Cases->size();
6397 if (Dest == SI->getDefaultDest())
6398 ++PreviousEdges;
6399 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
6400 PHI.removeIncomingValue(SI->getParent());
6401 }
6402 for (auto &PHI : make_early_inc_range(OtherDest->phis())) {
6403 unsigned PreviousEdges = OtherCases->size();
6404 if (OtherDest == SI->getDefaultDest())
6405 ++PreviousEdges;
6406 unsigned E = PreviousEdges - 1;
6407 // Remove all incoming values from OtherDest if OtherDest is unreachable.
6408 if (isa<UncondBrInst>(NewBI))
6409 ++E;
6410 for (unsigned I = 0; I != E; ++I)
6411 PHI.removeIncomingValue(SI->getParent());
6412 }
6413
6414 // Clean up the default block.
6415 SmallVector<DominatorTree::UpdateType, 2> Updates;
6416 if (!HasDefault) {
6417 BasicBlock *OrigDefaultBlock = SI->getDefaultDest();
6418 OrigDefaultBlock->removePredecessor(BB);
6419 Updates.push_back({DominatorTree::Delete, BB, OrigDefaultBlock});
6420 }
6421
6422 // Drop the switch.
6423 SI->eraseFromParent();
6424
6425 if (isa<UncondBrInst>(NewBI))
6426 Updates.push_back({DominatorTree::Delete, BB, OtherDest});
6427
6428 if (DTU)
6429 DTU->applyUpdates(Updates);
6430 return true;
6431}
6432
6433/// Compute masked bits for the condition of a switch
6434/// and use it to remove dead cases.
6436 AssumptionCache *AC,
6437 const DataLayout &DL) {
6438 Value *Cond = SI->getCondition();
6441 bool IsKnownValuesValid = collectPossibleValues(Cond, KnownValues, 4);
6442
6443 // We can also eliminate cases by determining that their values are outside of
6444 // the limited range of the condition based on how many significant (non-sign)
6445 // bits are in the condition value.
6446 unsigned MaxSignificantBitsInCond =
6448
6449 // Gather dead cases.
6451 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
6452 SmallVector<BasicBlock *, 8> UniqueSuccessors;
6453 for (const auto &Case : SI->cases()) {
6454 auto *Successor = Case.getCaseSuccessor();
6455 if (DTU) {
6456 auto [It, Inserted] = NumPerSuccessorCases.try_emplace(Successor);
6457 if (Inserted)
6458 UniqueSuccessors.push_back(Successor);
6459 ++It->second;
6460 }
6461 ConstantInt *CaseC = Case.getCaseValue();
6462 const APInt &CaseVal = CaseC->getValue();
6463 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
6464 (CaseVal.getSignificantBits() > MaxSignificantBitsInCond) ||
6465 (IsKnownValuesValid && !KnownValues.contains(CaseC))) {
6466 DeadCases.push_back(CaseC);
6467 if (DTU)
6468 --NumPerSuccessorCases[Successor];
6469 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
6470 << " is dead.\n");
6471 } else if (IsKnownValuesValid)
6472 KnownValues.erase(CaseC);
6473 }
6474
6475 // If we can prove that the cases must cover all possible values, the
6476 // default destination becomes dead and we can remove it. If we know some
6477 // of the bits in the value, we can use that to more precisely compute the
6478 // number of possible unique case values.
6479 bool HasDefault = !SI->defaultDestUnreachable();
6480 const unsigned NumUnknownBits =
6481 Known.getBitWidth() - (Known.Zero | Known.One).popcount();
6482 assert(NumUnknownBits <= Known.getBitWidth());
6483 if (HasDefault && DeadCases.empty()) {
6484 if (IsKnownValuesValid && all_of(KnownValues, IsaPred<UndefValue>)) {
6486 return true;
6487 }
6488
6489 if (NumUnknownBits < 64 /* avoid overflow */) {
6490 uint64_t AllNumCases = 1ULL << NumUnknownBits;
6491 if (SI->getNumCases() == AllNumCases) {
6493 return true;
6494 }
6495 // When only one case value is missing, replace default with that case.
6496 // Eliminating the default branch will provide more opportunities for
6497 // optimization, such as lookup tables.
6498 if (SI->getNumCases() == AllNumCases - 1) {
6499 assert(NumUnknownBits > 1 && "Should be canonicalized to a branch");
6500 IntegerType *CondTy = cast<IntegerType>(Cond->getType());
6501 if (CondTy->getIntegerBitWidth() > 64 ||
6502 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6503 return false;
6504
6505 uint64_t MissingCaseVal = 0;
6506 for (const auto &Case : SI->cases())
6507 MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
6508 auto *MissingCase = cast<ConstantInt>(
6509 ConstantInt::get(Cond->getType(), MissingCaseVal));
6511 SIW.addCase(MissingCase, SI->getDefaultDest(),
6512 SIW.getSuccessorWeight(0));
6514 /*RemoveOrigDefaultBlock*/ false);
6515 SIW.setSuccessorWeight(0, 0);
6516 return true;
6517 }
6518 }
6519 }
6520
6521 if (DeadCases.empty())
6522 return false;
6523
6525 for (ConstantInt *DeadCase : DeadCases) {
6526 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
6527 assert(CaseI != SI->case_default() &&
6528 "Case was not found. Probably mistake in DeadCases forming.");
6529 // Prune unused values from PHI nodes.
6530 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
6531 SIW.removeCase(CaseI);
6532 }
6533
6534 if (DTU) {
6535 std::vector<DominatorTree::UpdateType> Updates;
6536 for (auto *Successor : UniqueSuccessors)
6537 if (NumPerSuccessorCases[Successor] == 0)
6538 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
6539 DTU->applyUpdates(Updates);
6540 }
6541
6542 return true;
6543}
6544
6545/// If BB would be eligible for simplification by
6546/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
6547/// by an unconditional branch), look at the phi node for BB in the successor
6548/// block and see if the incoming value is equal to CaseValue. If so, return
6549/// the phi node, and set PhiIndex to BB's index in the phi node.
6551 BasicBlock *BB, int *PhiIndex) {
6552 if (&*BB->getFirstNonPHIIt() != BB->getTerminator())
6553 return nullptr; // BB must be empty to be a candidate for simplification.
6554 if (!BB->getSinglePredecessor())
6555 return nullptr; // BB must be dominated by the switch.
6556
6558 if (!Branch)
6559 return nullptr; // Terminator must be unconditional branch.
6560
6561 BasicBlock *Succ = Branch->getSuccessor();
6562
6563 for (PHINode &PHI : Succ->phis()) {
6564 int Idx = PHI.getBasicBlockIndex(BB);
6565 assert(Idx >= 0 && "PHI has no entry for predecessor?");
6566
6567 Value *InValue = PHI.getIncomingValue(Idx);
6568 if (InValue != CaseValue)
6569 continue;
6570
6571 *PhiIndex = Idx;
6572 return &PHI;
6573 }
6574
6575 return nullptr;
6576}
6577
6578/// Try to forward the condition of a switch instruction to a phi node
6579/// dominated by the switch, if that would mean that some of the destination
6580/// blocks of the switch can be folded away. Return true if a change is made.
6582 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
6583
6584 ForwardingNodesMap ForwardingNodes;
6585 BasicBlock *SwitchBlock = SI->getParent();
6586 bool Changed = false;
6587 for (const auto &Case : SI->cases()) {
6588 ConstantInt *CaseValue = Case.getCaseValue();
6589 BasicBlock *CaseDest = Case.getCaseSuccessor();
6590
6591 // Replace phi operands in successor blocks that are using the constant case
6592 // value rather than the switch condition variable:
6593 // switchbb:
6594 // switch i32 %x, label %default [
6595 // i32 17, label %succ
6596 // ...
6597 // succ:
6598 // %r = phi i32 ... [ 17, %switchbb ] ...
6599 // -->
6600 // %r = phi i32 ... [ %x, %switchbb ] ...
6601
6602 for (PHINode &Phi : CaseDest->phis()) {
6603 // This only works if there is exactly 1 incoming edge from the switch to
6604 // a phi. If there is >1, that means multiple cases of the switch map to 1
6605 // value in the phi, and that phi value is not the switch condition. Thus,
6606 // this transform would not make sense (the phi would be invalid because
6607 // a phi can't have different incoming values from the same block).
6608 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
6609 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
6610 count(Phi.blocks(), SwitchBlock) == 1) {
6611 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
6612 Changed = true;
6613 }
6614 }
6615
6616 // Collect phi nodes that are indirectly using this switch's case constants.
6617 int PhiIdx;
6618 if (auto *Phi = findPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
6619 ForwardingNodes[Phi].push_back(PhiIdx);
6620 }
6621
6622 for (auto &ForwardingNode : ForwardingNodes) {
6623 PHINode *Phi = ForwardingNode.first;
6624 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
6625 // Check if it helps to fold PHI.
6626 if (Indexes.size() < 2 && !llvm::is_contained(Phi->incoming_values(), SI->getCondition()))
6627 continue;
6628
6629 for (int Index : Indexes)
6630 Phi->setIncomingValue(Index, SI->getCondition());
6631 Changed = true;
6632 }
6633
6634 return Changed;
6635}
6636
6637/// Return true if the backend will be able to handle
6638/// initializing an array of constants like C.
6640 if (C->isThreadDependent())
6641 return false;
6642 if (C->isDLLImportDependent())
6643 return false;
6644
6647 return false;
6648
6649 // Globals cannot contain scalable types.
6650 if (C->getType()->isScalableTy())
6651 return false;
6652
6654 // Pointer casts and in-bounds GEPs will not prohibit the backend from
6655 // materializing the array of constants.
6656 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
6657 if (StrippedC == C || !validLookupTableConstant(StrippedC, TTI))
6658 return false;
6659 }
6660
6661 if (!TTI.shouldBuildLookupTablesForConstant(C))
6662 return false;
6663
6664 return true;
6665}
6666
6667/// If V is a Constant, return it. Otherwise, try to look up
6668/// its constant value in ConstantPool, returning 0 if it's not there.
6669static Constant *
6672 if (Constant *C = dyn_cast<Constant>(V))
6673 return C;
6674 return ConstantPool.lookup(V);
6675}
6676
6677/// Try to fold instruction I into a constant. This works for
6678/// simple instructions such as binary operations where both operands are
6679/// constant or can be replaced by constants from the ConstantPool. Returns the
6680/// resulting constant on success, 0 otherwise.
6681static Constant *
6685 Constant *A = lookupConstant(Select->getCondition(), ConstantPool);
6686 if (!A)
6687 return nullptr;
6688 if (A->isAllOnesValue())
6689 return lookupConstant(Select->getTrueValue(), ConstantPool);
6690 if (A->isNullValue())
6691 return lookupConstant(Select->getFalseValue(), ConstantPool);
6692 return nullptr;
6693 }
6694
6696 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
6697 if (Constant *A = lookupConstant(I->getOperand(N), ConstantPool))
6698 COps.push_back(A);
6699 else
6700 return nullptr;
6701 }
6702
6703 return ConstantFoldInstOperands(I, COps, DL);
6704}
6705
6706/// Try to determine the resulting constant values in phi nodes
6707/// at the common destination basic block, *CommonDest, for one of the case
6708/// destinations CaseDest corresponding to value CaseVal (nullptr for the
6709/// default case), of a switch instruction SI.
6710static bool
6712 BasicBlock **CommonDest,
6713 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
6714 const DataLayout &DL) {
6715 // The block from which we enter the common destination.
6716 BasicBlock *Pred = SI->getParent();
6717
6718 // If CaseDest is empty except for some side-effect free instructions through
6719 // which we can constant-propagate the CaseVal, continue to its successor.
6721 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
6722 for (Instruction &I : *CaseDest) {
6723 if (I.isTerminator()) {
6724 // If the terminator is a simple branch, continue to the next block.
6725 if (I.getNumSuccessors() != 1 || I.isSpecialTerminator())
6726 return false;
6727 Pred = CaseDest;
6728 CaseDest = I.getSuccessor(0);
6729 } else if (Constant *C = constantFold(&I, DL, ConstantPool)) {
6730 // Instruction is side-effect free and constant.
6731
6732 // If the instruction has uses outside this block or a phi node slot for
6733 // the block, it is not safe to bypass the instruction since it would then
6734 // no longer dominate all its uses.
6735 for (auto &Use : I.uses()) {
6736 User *User = Use.getUser();
6738 if (I->getParent() == CaseDest)
6739 continue;
6740 if (PHINode *Phi = dyn_cast<PHINode>(User))
6741 if (Phi->getIncomingBlock(Use) == CaseDest)
6742 continue;
6743 return false;
6744 }
6745
6746 ConstantPool.insert(std::make_pair(&I, C));
6747 } else {
6748 break;
6749 }
6750 }
6751
6752 // If we did not have a CommonDest before, use the current one.
6753 if (!*CommonDest)
6754 *CommonDest = CaseDest;
6755 // If the destination isn't the common one, abort.
6756 if (CaseDest != *CommonDest)
6757 return false;
6758
6759 // Get the values for this case from phi nodes in the destination block.
6760 for (PHINode &PHI : (*CommonDest)->phis()) {
6761 int Idx = PHI.getBasicBlockIndex(Pred);
6762 if (Idx == -1)
6763 continue;
6764
6765 Constant *ConstVal =
6766 lookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
6767 if (!ConstVal)
6768 return false;
6769
6770 Res.push_back(std::make_pair(&PHI, ConstVal));
6771 }
6772
6773 return Res.size() > 0;
6774}
6775
6776// Helper function used to add CaseVal to the list of cases that generate
6777// Result. Returns the updated number of cases that generate this result.
6778static size_t mapCaseToResult(ConstantInt *CaseVal,
6779 SwitchCaseResultVectorTy &UniqueResults,
6780 Constant *Result) {
6781 for (auto &I : UniqueResults) {
6782 if (I.first == Result) {
6783 I.second.push_back(CaseVal);
6784 return I.second.size();
6785 }
6786 }
6787 UniqueResults.push_back(
6788 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
6789 return 1;
6790}
6791
6792// Helper function that initializes a map containing
6793// results for the PHI node of the common destination block for a switch
6794// instruction. Returns false if multiple PHI nodes have been found or if
6795// there is not a common destination block for the switch.
6797 BasicBlock *&CommonDest,
6798 SwitchCaseResultVectorTy &UniqueResults,
6799 Constant *&DefaultResult,
6800 const DataLayout &DL,
6801 uintptr_t MaxUniqueResults) {
6802 for (const auto &I : SI->cases()) {
6803 ConstantInt *CaseVal = I.getCaseValue();
6804
6805 // Resulting value at phi nodes for this case value.
6806 SwitchCaseResultsTy Results;
6807 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
6808 DL))
6809 return false;
6810
6811 // Only one value per case is permitted.
6812 if (Results.size() > 1)
6813 return false;
6814
6815 // Add the case->result mapping to UniqueResults.
6816 const size_t NumCasesForResult =
6817 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
6818
6819 // Early out if there are too many cases for this result.
6820 if (NumCasesForResult > MaxSwitchCasesPerResult)
6821 return false;
6822
6823 // Early out if there are too many unique results.
6824 if (UniqueResults.size() > MaxUniqueResults)
6825 return false;
6826
6827 // Check the PHI consistency.
6828 if (!PHI)
6829 PHI = Results[0].first;
6830 else if (PHI != Results[0].first)
6831 return false;
6832 }
6833 // Find the default result value.
6835 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
6836 DL);
6837 // If the default value is not found abort unless the default destination
6838 // is unreachable.
6839 DefaultResult =
6840 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
6841
6842 return DefaultResult || SI->defaultDestUnreachable();
6843}
6844
6845// Helper function that checks if it is possible to transform a switch with only
6846// two cases (or two cases + default) that produces a result into a select.
6847// TODO: Handle switches with more than 2 cases that map to the same result.
6848// The branch weights correspond to the provided Condition (i.e. if Condition is
6849// modified from the original SwitchInst, the caller must adjust the weights)
6850static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
6851 Constant *DefaultResult, Value *Condition,
6852 IRBuilder<> &Builder, const DataLayout &DL,
6853 ArrayRef<uint32_t> BranchWeights) {
6854 // If we are selecting between only two cases transform into a simple
6855 // select or a two-way select if default is possible.
6856 // Example:
6857 // switch (a) { %0 = icmp eq i32 %a, 10
6858 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
6859 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
6860 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
6861 // }
6862
6863 const bool HasBranchWeights = !BranchWeights.empty();
6864
6865 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
6866 ResultVector[1].second.size() == 1) {
6867 ConstantInt *FirstCase = ResultVector[0].second[0];
6868 ConstantInt *SecondCase = ResultVector[1].second[0];
6869 Value *SelectValue = ResultVector[1].first;
6870 if (DefaultResult) {
6871 Value *ValueCompare =
6872 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
6873 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
6874 DefaultResult, "switch.select");
6875 if (auto *SI = dyn_cast<SelectInst>(SelectValue);
6876 SI && HasBranchWeights) {
6877 // We start with 3 probabilities, where the numerator is the
6878 // corresponding BranchWeights[i], and the denominator is the sum over
6879 // BranchWeights. We want the probability and negative probability of
6880 // Condition == SecondCase.
6881 assert(BranchWeights.size() == 3);
6883 *SI, {BranchWeights[2], BranchWeights[0] + BranchWeights[1]},
6884 /*IsExpected=*/false, /*ElideAllZero=*/true);
6885 }
6886 }
6887 Value *ValueCompare =
6888 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
6889 Value *Ret = Builder.CreateSelect(ValueCompare, ResultVector[0].first,
6890 SelectValue, "switch.select");
6891 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6892 // We may have had a DefaultResult. Base the position of the first and
6893 // second's branch weights accordingly. Also the proability that Condition
6894 // != FirstCase needs to take that into account.
6895 assert(BranchWeights.size() >= 2);
6896 size_t FirstCasePos = (Condition != nullptr);
6897 size_t SecondCasePos = FirstCasePos + 1;
6898 uint32_t DefaultCase = (Condition != nullptr) ? BranchWeights[0] : 0;
6900 {BranchWeights[FirstCasePos],
6901 DefaultCase + BranchWeights[SecondCasePos]},
6902 /*IsExpected=*/false, /*ElideAllZero=*/true);
6903 }
6904 return Ret;
6905 }
6906
6907 // Handle the degenerate case where two cases have the same result value.
6908 if (ResultVector.size() == 1 && DefaultResult) {
6909 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
6910 unsigned CaseCount = CaseValues.size();
6911 // n bits group cases map to the same result:
6912 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
6913 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
6914 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
6915 if (isPowerOf2_32(CaseCount)) {
6916 ConstantInt *MinCaseVal = CaseValues[0];
6917 // If there are bits that are set exclusively by CaseValues, we
6918 // can transform the switch into a select if the conjunction of
6919 // all the values uniquely identify CaseValues.
6920 APInt AndMask = APInt::getAllOnes(MinCaseVal->getBitWidth());
6921
6922 // Find the minimum value and compute the and of all the case values.
6923 for (auto *Case : CaseValues) {
6924 if (Case->getValue().slt(MinCaseVal->getValue()))
6925 MinCaseVal = Case;
6926 AndMask &= Case->getValue();
6927 }
6928 KnownBits Known = computeKnownBits(Condition, DL);
6929
6930 if (!AndMask.isZero() && Known.getMaxValue().uge(AndMask)) {
6931 // Compute the number of bits that are free to vary.
6932 unsigned FreeBits = Known.countMaxActiveBits() - AndMask.popcount();
6933
6934 // Check if the number of values covered by the mask is equal
6935 // to the number of cases.
6936 if (FreeBits == Log2_32(CaseCount)) {
6937 Value *And = Builder.CreateAnd(Condition, AndMask);
6938 Value *Cmp = Builder.CreateICmpEQ(
6939 And, Constant::getIntegerValue(And->getType(), AndMask));
6940 Value *Ret =
6941 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6942 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6943 // We know there's a Default case. We base the resulting branch
6944 // weights off its probability.
6945 assert(BranchWeights.size() >= 2);
6947 *SI,
6948 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6949 /*IsExpected=*/false, /*ElideAllZero=*/true);
6950 }
6951 return Ret;
6952 }
6953 }
6954
6955 // Mark the bits case number touched.
6956 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
6957 for (auto *Case : CaseValues)
6958 BitMask |= (Case->getValue() - MinCaseVal->getValue());
6959
6960 // Check if cases with the same result can cover all number
6961 // in touched bits.
6962 if (BitMask.popcount() == Log2_32(CaseCount)) {
6963 if (!MinCaseVal->isNullValue())
6964 Condition = Builder.CreateSub(Condition, MinCaseVal);
6965 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
6966 Value *Cmp = Builder.CreateICmpEQ(
6967 And, Constant::getNullValue(And->getType()), "switch.selectcmp");
6968 Value *Ret =
6969 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6970 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6971 assert(BranchWeights.size() >= 2);
6973 *SI,
6974 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6975 /*IsExpected=*/false, /*ElideAllZero=*/true);
6976 }
6977 return Ret;
6978 }
6979 }
6980
6981 // Handle the degenerate case where two cases have the same value.
6982 if (CaseValues.size() == 2) {
6983 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
6984 "switch.selectcmp.case1");
6985 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
6986 "switch.selectcmp.case2");
6987 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
6988 Value *Ret =
6989 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6990 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6991 assert(BranchWeights.size() >= 2);
6993 *SI, {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6994 /*IsExpected=*/false, /*ElideAllZero=*/true);
6995 }
6996 return Ret;
6997 }
6998 }
6999
7000 return nullptr;
7001}
7002
7003// Helper function to cleanup a switch instruction that has been converted into
7004// a select, fixing up PHI nodes and basic blocks.
7006 Value *SelectValue,
7007 IRBuilder<> &Builder,
7008 DomTreeUpdater *DTU) {
7009 std::vector<DominatorTree::UpdateType> Updates;
7010
7011 BasicBlock *SelectBB = SI->getParent();
7012 BasicBlock *DestBB = PHI->getParent();
7013
7014 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
7015 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
7016 Builder.CreateBr(DestBB);
7017
7018 // Remove the switch.
7019
7020 PHI->removeIncomingValueIf(
7021 [&](unsigned Idx) { return PHI->getIncomingBlock(Idx) == SelectBB; });
7022 PHI->addIncoming(SelectValue, SelectBB);
7023
7024 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
7025 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
7026 BasicBlock *Succ = SI->getSuccessor(i);
7027
7028 if (Succ == DestBB)
7029 continue;
7030 Succ->removePredecessor(SelectBB);
7031 if (DTU && RemovedSuccessors.insert(Succ).second)
7032 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
7033 }
7034 SI->eraseFromParent();
7035 if (DTU)
7036 DTU->applyUpdates(Updates);
7037}
7038
7039/// If a switch is only used to initialize one or more phi nodes in a common
7040/// successor block with only two different constant values, try to replace the
7041/// switch with a select. Returns true if the fold was made.
7043 DomTreeUpdater *DTU, const DataLayout &DL) {
7044 Value *const Cond = SI->getCondition();
7045 PHINode *PHI = nullptr;
7046 BasicBlock *CommonDest = nullptr;
7047 Constant *DefaultResult;
7048 SwitchCaseResultVectorTy UniqueResults;
7049 // Collect all the cases that will deliver the same value from the switch.
7050 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
7051 DL, /*MaxUniqueResults*/ 2))
7052 return false;
7053
7054 assert(PHI != nullptr && "PHI for value select not found");
7055 Builder.SetInsertPoint(SI);
7056 SmallVector<uint32_t, 4> BranchWeights;
7057 [[maybe_unused]] auto HasWeights =
7059 assert(!HasWeights == (BranchWeights.empty()));
7060 assert(BranchWeights.empty() ||
7061 (BranchWeights.size() >=
7062 UniqueResults.size() + (DefaultResult != nullptr)));
7063
7064 Value *SelectValue = foldSwitchToSelect(UniqueResults, DefaultResult, Cond,
7065 Builder, DL, BranchWeights);
7066 if (!SelectValue)
7067 return false;
7068
7069 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
7070 return true;
7071}
7072
7073namespace {
7074
7075/// This class finds alternatives for switches to ultimately
7076/// replace the switch.
7077class SwitchReplacement {
7078public:
7079 /// Create a helper for optimizations to use as a switch replacement.
7080 /// Find a better representation for the content of Values,
7081 /// using DefaultValue to fill any holes in the table.
7082 /// If no representation is possible, isValid() returns false.
7083 SwitchReplacement(
7084 Module &M, uint64_t TableSize, ConstantInt *Offset,
7085 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7086 Constant *DefaultValue, const DataLayout &DL,
7087 const TargetTransformInfo &TTI, const StringRef &FuncName);
7088
7089 /// Build instructions with Builder to retrieve values using Index
7090 /// and replace the switch.
7091 Value *replaceSwitch(Value *Index, IRBuilder<> &Builder, const DataLayout &DL,
7092 Function *Func);
7093
7094 /// Return true if a table with TableSize elements of
7095 /// type ElementType would fit in a target-legal register.
7096 static bool wouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
7097 Type *ElementType);
7098
7099 /// Return the default value of the switch.
7100 Constant *getDefaultValue();
7101
7102 /// Return true if the replacement is a lookup table.
7103 bool isLookupTable();
7104
7105 /// Return true if the replacement is a bit map.
7106 bool isBitMap();
7107
7108 /// Return true if a suitable switch replacement was found.
7109 bool isValid() const { return Kind != InvalidKind; }
7110
7111private:
7112 // Depending on the switch, there are different alternatives.
7113 enum {
7114 // No suitable replacement was found.
7115 InvalidKind,
7116
7117 // For switches where each case contains the same value, we just have to
7118 // store that single value and return it for each lookup.
7119 SingleValueKind,
7120
7121 // For switches where there is a linear relationship between table index
7122 // and values. We calculate the result with a simple multiplication
7123 // and addition instead of a table lookup.
7124 LinearMapKind,
7125
7126 // For small tables with integer elements, we can pack them into a bitmap
7127 // that fits into a target-legal register. Values are retrieved by
7128 // shift and mask operations.
7129 BitMapKind,
7130
7131 // The table is stored as an array of values. Values are retrieved by load
7132 // instructions from the table.
7133 LookupTableKind
7134 } Kind;
7135
7136 // The default value of the switch.
7137 Constant *DefaultValue;
7138
7139 // The type of the output values.
7140 Type *ValueType;
7141
7142 // For SingleValueKind, this is the single value.
7143 Constant *SingleValue = nullptr;
7144
7145 // For BitMapKind, this is the bitmap.
7146 ConstantInt *BitMap = nullptr;
7147 IntegerType *BitMapElementTy = nullptr;
7148
7149 // For LinearMapKind, these are the constants used to derive the value.
7150 ConstantInt *LinearOffset = nullptr;
7151 ConstantInt *LinearMultiplier = nullptr;
7152 bool LinearMapValWrapped = false;
7153
7154 // For LookupTableKind, this is the table.
7155 Constant *Initializer = nullptr;
7156};
7157
7158} // end anonymous namespace
7159
7160SwitchReplacement::SwitchReplacement(
7161 Module &M, uint64_t TableSize, ConstantInt *Offset,
7162 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7163 Constant *DefaultValue, const DataLayout &DL,
7164 const TargetTransformInfo &TTI, const StringRef &FuncName)
7165 : DefaultValue(DefaultValue) {
7166 assert(Values.size() && "Can't build lookup table without values!");
7167 assert(TableSize >= Values.size() && "Can't fit values in table!");
7168
7169 // If all values in the table are equal, this is that value.
7170 SingleValue = Values.begin()->second;
7171
7172 ValueType = Values.begin()->second->getType();
7173
7174 // Build up the table contents.
7175 SmallVector<Constant *, 64> TableContents(TableSize);
7176 for (const auto &[CaseVal, CaseRes] : Values) {
7177 assert(CaseRes->getType() == ValueType);
7178
7179 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
7180 TableContents[Idx] = CaseRes;
7181
7182 if (SingleValue && !isa<PoisonValue>(CaseRes) && CaseRes != SingleValue)
7183 SingleValue = isa<PoisonValue>(SingleValue) ? CaseRes : nullptr;
7184 }
7185
7186 // Fill in any holes in the table with the default result.
7187 if (Values.size() < TableSize) {
7188 assert(DefaultValue &&
7189 "Need a default value to fill the lookup table holes.");
7190 assert(DefaultValue->getType() == ValueType);
7191 for (uint64_t I = 0; I < TableSize; ++I) {
7192 if (!TableContents[I])
7193 TableContents[I] = DefaultValue;
7194 }
7195
7196 // If the default value is poison, all the holes are poison.
7197 bool DefaultValueIsPoison = isa<PoisonValue>(DefaultValue);
7198
7199 if (DefaultValue != SingleValue && !DefaultValueIsPoison)
7200 SingleValue = nullptr;
7201 }
7202
7203 // If each element in the table contains the same value, we only need to store
7204 // that single value.
7205 if (SingleValue) {
7206 Kind = SingleValueKind;
7207 return;
7208 }
7209
7210 // Check if we can derive the value with a linear transformation from the
7211 // table index.
7213 bool LinearMappingPossible = true;
7214 APInt PrevVal;
7215 APInt DistToPrev;
7216 // When linear map is monotonic and signed overflow doesn't happen on
7217 // maximum index, we can attach nsw on Add and Mul.
7218 bool NonMonotonic = false;
7219 assert(TableSize >= 2 && "Should be a SingleValue table.");
7220 // Check if there is the same distance between two consecutive values.
7221 for (uint64_t I = 0; I < TableSize; ++I) {
7222 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
7223
7224 if (!ConstVal && isa<PoisonValue>(TableContents[I])) {
7225 // This is an poison, so it's (probably) a lookup table hole.
7226 // To prevent any regressions from before we switched to using poison as
7227 // the default value, holes will fall back to using the first value.
7228 // This can be removed once we add proper handling for poisons in lookup
7229 // tables.
7230 ConstVal = dyn_cast<ConstantInt>(Values[0].second);
7231 }
7232
7233 if (!ConstVal) {
7234 // We only handle literal integers when checking for a linear mapping.
7235 LinearMappingPossible = false;
7236 break;
7237 }
7238 const APInt &Val = ConstVal->getValue();
7239 if (I != 0) {
7240 APInt Dist = Val - PrevVal;
7241 if (I == 1) {
7242 DistToPrev = Dist;
7243 } else if (Dist != DistToPrev) {
7244 LinearMappingPossible = false;
7245 break;
7246 }
7247 NonMonotonic |=
7248 Dist.isStrictlyPositive() ? Val.sle(PrevVal) : Val.sgt(PrevVal);
7249 }
7250 PrevVal = Val;
7251 }
7252 if (LinearMappingPossible) {
7253 LinearOffset = cast<ConstantInt>(TableContents[0]);
7254 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
7255 APInt M = LinearMultiplier->getValue();
7256 bool MayWrap = true;
7257 if (isIntN(M.getBitWidth(), TableSize - 1))
7258 (void)M.smul_ov(APInt(M.getBitWidth(), TableSize - 1), MayWrap);
7259 LinearMapValWrapped = NonMonotonic || MayWrap;
7260 Kind = LinearMapKind;
7261 return;
7262 }
7263 }
7264
7265 // If the values are integer constants and the table fits in a register,
7266 // build a bitmap.
7267 if (wouldFitInRegister(DL, TableSize, ValueType) &&
7268 all_of(TableContents, IsaPred<ConstantInt, UndefValue>)) {
7270 APInt TableInt(TableSize * IT->getBitWidth(), 0);
7271 for (uint64_t I = TableSize; I > 0; --I) {
7272 TableInt <<= IT->getBitWidth();
7273 // Insert values into the bitmap. Undef values are set to zero.
7274 if (!isa<UndefValue>(TableContents[I - 1])) {
7275 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
7276 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
7277 }
7278 }
7279 BitMap = ConstantInt::get(M.getContext(), TableInt);
7280 BitMapElementTy = IT;
7281 Kind = BitMapKind;
7282 return;
7283 }
7284
7285 // The remaining representation needs a global initializer.
7286 if (!all_of(TableContents,
7287 [&](Constant *C) { return validLookupTableConstant(C, TTI); })) {
7288 Kind = InvalidKind;
7289 return;
7290 }
7291
7292 if (auto *IT = dyn_cast<IntegerType>(ValueType)) {
7293 ConstantRange Range(IT->getBitWidth(), false);
7294 for (Constant *Value : TableContents)
7295 if (!isa<UndefValue>(Value))
7296 Range = Range.unionWith(cast<ConstantInt>(Value)->getValue());
7297 // TODO: handle sign extension as well?
7298 unsigned NeededBitWidth =
7299 std::max(TTI.getMinimumLookupTableEntryBitWidth(),
7300 unsigned(PowerOf2Ceil(Range.getActiveBits())));
7301 if (NeededBitWidth < IT->getBitWidth()) {
7302 IntegerType *DstTy = IntegerType::get(IT->getContext(), NeededBitWidth);
7303 for (Constant *&Value : TableContents)
7304 Value = ConstantFoldCastInstruction(Instruction::Trunc, Value, DstTy);
7305 }
7306 }
7307
7308 // Store the table in an array.
7309 auto *TableTy = ArrayType::get(TableContents[0]->getType(), TableSize);
7310 Initializer = ConstantArray::get(TableTy, TableContents);
7311
7312 Kind = LookupTableKind;
7313}
7314
7315Value *SwitchReplacement::replaceSwitch(Value *Index, IRBuilder<> &Builder,
7316 const DataLayout &DL, Function *Func) {
7317 switch (Kind) {
7318 case InvalidKind:
7319 llvm_unreachable("Cannot use an invalid switch replacement");
7320 case SingleValueKind:
7321 return SingleValue;
7322 case LinearMapKind: {
7323 ++NumLinearMaps;
7324 // Derive the result value from the input value.
7325 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
7326 false, "switch.idx.cast");
7327 if (!LinearMultiplier->isOne())
7328 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult",
7329 /*HasNUW = */ false,
7330 /*HasNSW = */ !LinearMapValWrapped);
7331
7332 if (!LinearOffset->isZero())
7333 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset",
7334 /*HasNUW = */ false,
7335 /*HasNSW = */ !LinearMapValWrapped);
7336 return Result;
7337 }
7338 case BitMapKind: {
7339 ++NumBitMaps;
7340 // Type of the bitmap (e.g. i59).
7341 IntegerType *MapTy = BitMap->getIntegerType();
7342
7343 // Cast Index to the same type as the bitmap.
7344 // Note: The Index is <= the number of elements in the table, so
7345 // truncating it to the width of the bitmask is safe.
7346 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
7347
7348 // Multiply the shift amount by the element width. NUW/NSW can always be
7349 // set, because wouldFitInRegister guarantees Index * ShiftAmt is in
7350 // BitMap's bit width.
7351 ShiftAmt = Builder.CreateMul(
7352 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
7353 "switch.shiftamt",/*HasNUW =*/true,/*HasNSW =*/true);
7354
7355 // Shift down.
7356 Value *DownShifted =
7357 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
7358 // Mask off.
7359 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
7360 }
7361 case LookupTableKind: {
7362 ++NumLookupTables;
7363 auto *Table =
7364 new GlobalVariable(*Func->getParent(), Initializer->getType(),
7365 /*isConstant=*/true, GlobalVariable::PrivateLinkage,
7366 Initializer, "switch.table." + Func->getName());
7367 Table->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7368 // Set the alignment to that of an array items. We will be only loading one
7369 // value out of it.
7370 Table->setAlignment(DL.getPrefTypeAlign(ValueType));
7371 Type *IndexTy = DL.getIndexType(Table->getType());
7372 auto *ArrayTy = cast<ArrayType>(Table->getValueType());
7373
7374 if (Index->getType() != IndexTy) {
7375 unsigned OldBitWidth = Index->getType()->getIntegerBitWidth();
7376 Index = Builder.CreateZExtOrTrunc(Index, IndexTy);
7377 if (auto *Zext = dyn_cast<ZExtInst>(Index))
7378 Zext->setNonNeg(
7379 isUIntN(OldBitWidth - 1, ArrayTy->getNumElements() - 1));
7380 }
7381
7382 Value *GEPIndices[] = {ConstantInt::get(IndexTy, 0), Index};
7383 Value *GEP =
7384 Builder.CreateInBoundsGEP(ArrayTy, Table, GEPIndices, "switch.gep");
7385 Value *Load =
7386 Builder.CreateLoad(ArrayTy->getElementType(), GEP, "switch.load");
7387 if (Load->getType() == ValueType)
7388 return Load;
7389 return Builder.CreateZExt(Load, ValueType, "switch.ext");
7390 }
7391 }
7392 llvm_unreachable("Unknown helper kind!");
7393}
7394
7395bool SwitchReplacement::wouldFitInRegister(const DataLayout &DL,
7396 uint64_t TableSize,
7397 Type *ElementType) {
7398 auto *IT = dyn_cast<IntegerType>(ElementType);
7399 if (!IT)
7400 return false;
7401 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
7402 // are <= 15, we could try to narrow the type.
7403
7404 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
7405 if (TableSize >= UINT_MAX / IT->getBitWidth())
7406 return false;
7407 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
7408}
7409
7411 const DataLayout &DL) {
7412 // Allow any legal type.
7413 if (TTI.isTypeLegal(Ty))
7414 return true;
7415
7416 auto *IT = dyn_cast<IntegerType>(Ty);
7417 if (!IT)
7418 return false;
7419
7420 // Also allow power of 2 integer types that have at least 8 bits and fit in
7421 // a register. These types are common in frontend languages and targets
7422 // usually support loads of these types.
7423 // TODO: We could relax this to any integer that fits in a register and rely
7424 // on ABI alignment and padding in the table to allow the load to be widened.
7425 // Or we could widen the constants and truncate the load.
7426 unsigned BitWidth = IT->getBitWidth();
7427 return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
7428 DL.fitsInLegalInteger(IT->getBitWidth());
7429}
7430
7431Constant *SwitchReplacement::getDefaultValue() { return DefaultValue; }
7432
7433bool SwitchReplacement::isLookupTable() { return Kind == LookupTableKind; }
7434
7435bool SwitchReplacement::isBitMap() { return Kind == BitMapKind; }
7436
7437static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize) {
7438 // 40% is the default density for building a jump table in optsize/minsize
7439 // mode, 10% is the default density for jump tables. See also
7440 // TargetLoweringBase::isSuitableForJumpTable(), which this function was based
7441 // on.
7442 const uint64_t MinDensity = OptSize ? 40 : 10;
7443
7444 if (CaseRange >= UINT64_MAX / 100)
7445 return false; // Avoid multiplication overflows below.
7446
7447 return NumCases * 100 >= CaseRange * MinDensity;
7448}
7449
7450static bool isSwitchDense(ArrayRef<int64_t> Values, bool OptSize) {
7451 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
7452 uint64_t Range = Diff + 1;
7453 if (Range < Diff)
7454 return false; // Overflow.
7455
7456 return isSwitchDense(Values.size(), Range, OptSize);
7457}
7458
7459static std::optional<unsigned>
7461 bool OptSize) {
7462 assert(Values.size() > 1 && "expected multiple switch cases");
7463 if (!llvm::all_of(Values, [Base](int64_t V) { return V >= Base; }))
7464 return std::nullopt;
7465
7466 // First, transform the values by subtracting Base.
7467 SmallVector<int64_t, 4> ReducedValues(Values);
7468 uint64_t ReducedValuesOr = 0;
7469 for (auto &V : ReducedValues) {
7470 uint64_t Reduced = (uint64_t)V - (uint64_t)Base;
7471 ReducedValuesOr |= Reduced;
7472 V = (int64_t)Reduced;
7473 }
7474
7475 // Conceptually, the reduced values are non-negative distances from Base.
7476 // Since the rest of the transform is bitwise only, treat them as unsigned
7477 // bit patterns from here.
7478
7479 // countr_zero(0) returns 64. As Values is guaranteed to have more than
7480 // one element and LLVM disallows duplicate cases, ReducedValuesOr will
7481 // have at least one bit set, so Shift will be less than 64.
7482 unsigned Shift = llvm::countr_zero(ReducedValuesOr);
7483 assert(Shift < 64);
7484 if (Shift > 0)
7485 for (auto &V : ReducedValues)
7486 V = (int64_t)((uint64_t)V >> Shift);
7487
7488 if (!isSwitchDense(ReducedValues, OptSize))
7489 return std::nullopt;
7490
7491 return Shift;
7492}
7493
7494/// Determine whether a lookup table should be built for this switch, based on
7495/// the number of cases, size of the table, and the types of the results.
7496// TODO: We could support larger than legal types by limiting based on the
7497// number of loads required and/or table size. If the constants are small we
7498// could use smaller table entries and extend after the load.
7500 const TargetTransformInfo &TTI,
7501 const DataLayout &DL,
7502 const SmallVector<Type *> &ResultTypes) {
7503 if (SI->getNumCases() > TableSize)
7504 return false; // TableSize overflowed.
7505
7506 bool AllTablesFitInRegister = true;
7507 bool HasIllegalType = false;
7508 for (const auto &Ty : ResultTypes) {
7509 // Saturate this flag to true.
7510 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
7511
7512 // Saturate this flag to false.
7513 AllTablesFitInRegister =
7514 AllTablesFitInRegister &&
7515 SwitchReplacement::wouldFitInRegister(DL, TableSize, Ty);
7516
7517 // If both flags saturate, we're done. NOTE: This *only* works with
7518 // saturating flags, and all flags have to saturate first due to the
7519 // non-deterministic behavior of iterating over a dense map.
7520 if (HasIllegalType && !AllTablesFitInRegister)
7521 break;
7522 }
7523
7524 // If each table would fit in a register, we should build it anyway.
7525 if (AllTablesFitInRegister)
7526 return true;
7527
7528 // Don't build a table that doesn't fit in-register if it has illegal types.
7529 if (HasIllegalType)
7530 return false;
7531
7532 return isSwitchDense(SI->getNumCases(), TableSize,
7533 SI->getFunction()->hasOptSize());
7534}
7535
7537 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
7538 bool HasDefaultResults, const SmallVector<Type *> &ResultTypes,
7539 const DataLayout &DL, const TargetTransformInfo &TTI) {
7540 if (MinCaseVal.isNullValue())
7541 return true;
7542 if (MinCaseVal.isNegative() ||
7543 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
7544 !HasDefaultResults)
7545 return false;
7546 return all_of(ResultTypes, [&](const auto &ResultType) {
7547 return SwitchReplacement::wouldFitInRegister(
7548 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */, ResultType);
7549 });
7550}
7551
7552/// Try to reuse the switch table index compare. Following pattern:
7553/// \code
7554/// if (idx < tablesize)
7555/// r = table[idx]; // table does not contain default_value
7556/// else
7557/// r = default_value;
7558/// if (r != default_value)
7559/// ...
7560/// \endcode
7561/// Is optimized to:
7562/// \code
7563/// cond = idx < tablesize;
7564/// if (cond)
7565/// r = table[idx];
7566/// else
7567/// r = default_value;
7568/// if (cond)
7569/// ...
7570/// \endcode
7571/// Jump threading will then eliminate the second if(cond).
7573 User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
7574 Constant *DefaultValue,
7575 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
7577 if (!CmpInst)
7578 return;
7579
7580 // We require that the compare is in the same block as the phi so that jump
7581 // threading can do its work afterwards.
7582 if (CmpInst->getParent() != PhiBlock)
7583 return;
7584
7586 if (!CmpOp1)
7587 return;
7588
7589 Value *RangeCmp = RangeCheckBranch->getCondition();
7590 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
7591 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
7592
7593 // Check if the compare with the default value is constant true or false.
7594 const DataLayout &DL = PhiBlock->getDataLayout();
7596 CmpInst->getPredicate(), DefaultValue, CmpOp1, DL);
7597 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
7598 return;
7599
7600 // Check if the compare with the case values is distinct from the default
7601 // compare result.
7602 for (auto ValuePair : Values) {
7604 CmpInst->getPredicate(), ValuePair.second, CmpOp1, DL);
7605 if (!CaseConst || CaseConst == DefaultConst ||
7606 (CaseConst != TrueConst && CaseConst != FalseConst))
7607 return;
7608 }
7609
7610 // Check if the branch instruction dominates the phi node. It's a simple
7611 // dominance check, but sufficient for our needs.
7612 // Although this check is invariant in the calling loops, it's better to do it
7613 // at this late stage. Practically we do it at most once for a switch.
7614 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
7615 for (BasicBlock *Pred : predecessors(PhiBlock)) {
7616 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
7617 return;
7618 }
7619
7620 if (DefaultConst == FalseConst) {
7621 // The compare yields the same result. We can replace it.
7622 CmpInst->replaceAllUsesWith(RangeCmp);
7623 ++NumTableCmpReuses;
7624 } else {
7625 // The compare yields the same result, just inverted. We can replace it.
7626 Value *InvertedTableCmp = BinaryOperator::CreateXor(
7627 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
7628 RangeCheckBranch->getIterator());
7629 CmpInst->replaceAllUsesWith(InvertedTableCmp);
7630 ++NumTableCmpReuses;
7631 }
7632}
7633
7634/// If the switch is only used to initialize one or more phi nodes in a common
7635/// successor block with different constant values, replace the switch with
7636/// lookup tables.
7638 DomTreeUpdater *DTU, const DataLayout &DL,
7639 const TargetTransformInfo &TTI,
7640 bool ConvertSwitchToLookupTable) {
7641 assert(SI->getNumCases() > 1 && "Degenerate switch?");
7642
7643 BasicBlock *BB = SI->getParent();
7644 Function *Fn = BB->getParent();
7645
7646 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
7647 // split off a dense part and build a lookup table for that.
7648
7649 // FIXME: This creates arrays of GEPs to constant strings, which means each
7650 // GEP needs a runtime relocation in PIC code. We should just build one big
7651 // string and lookup indices into that.
7652
7653 // Ignore switches with less than three cases. Lookup tables will not make
7654 // them faster, so we don't analyze them.
7655 if (SI->getNumCases() < 3)
7656 return false;
7657
7658 // Figure out the corresponding result for each case value and phi node in the
7659 // common destination, as well as the min and max case values.
7660 assert(!SI->cases().empty());
7661 SwitchInst::CaseIt CI = SI->case_begin();
7662 ConstantInt *MinCaseVal = CI->getCaseValue();
7663 ConstantInt *MaxCaseVal = CI->getCaseValue();
7664
7665 BasicBlock *CommonDest = nullptr;
7666
7667 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
7669
7671 SmallVector<Type *> ResultTypes;
7673
7674 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
7675 ConstantInt *CaseVal = CI->getCaseValue();
7676 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
7677 MinCaseVal = CaseVal;
7678 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
7679 MaxCaseVal = CaseVal;
7680
7681 // Resulting value at phi nodes for this case value.
7683 ResultsTy Results;
7684 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
7685 Results, DL))
7686 return false;
7687
7688 // Append the result and result types from this case to the list for each
7689 // phi.
7690 for (const auto &I : Results) {
7691 PHINode *PHI = I.first;
7692 Constant *Value = I.second;
7693 auto [It, Inserted] = ResultLists.try_emplace(PHI);
7694 if (Inserted)
7695 PHIs.push_back(PHI);
7696 It->second.push_back(std::make_pair(CaseVal, Value));
7697 ResultTypes.push_back(PHI->getType());
7698 }
7699 }
7700
7701 // If the table has holes, we need a constant result for the default case
7702 // or a bitmask that fits in a register.
7703 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
7704 bool HasDefaultResults = getCaseResults(SI, nullptr, SI->getDefaultDest(),
7705 &CommonDest, DefaultResultsList, DL);
7706 for (const auto &I : DefaultResultsList) {
7707 PHINode *PHI = I.first;
7708 Constant *Result = I.second;
7709 DefaultResults[PHI] = Result;
7710 }
7711
7712 bool UseSwitchConditionAsTableIndex = shouldUseSwitchConditionAsTableIndex(
7713 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
7714 uint64_t TableSize;
7715 ConstantInt *TableIndexOffset;
7716 if (UseSwitchConditionAsTableIndex) {
7717 TableSize = MaxCaseVal->getLimitedValue() + 1;
7718 TableIndexOffset = ConstantInt::get(MaxCaseVal->getIntegerType(), 0);
7719 } else {
7720 TableSize =
7721 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
7722
7723 TableIndexOffset = MinCaseVal;
7724 }
7725
7726 // If the default destination is unreachable, or if the lookup table covers
7727 // all values of the conditional variable, branch directly to the lookup table
7728 // BB. Otherwise, check that the condition is within the case range.
7729 uint64_t NumResults = ResultLists[PHIs[0]].size();
7730 bool DefaultIsReachable = !SI->defaultDestUnreachable();
7731
7732 bool TableHasHoles = (NumResults < TableSize);
7733
7734 // If the table has holes but the default destination doesn't produce any
7735 // constant results, the lookup table entries corresponding to the holes will
7736 // contain poison.
7737 bool AllHolesArePoison = TableHasHoles && !HasDefaultResults;
7738
7739 // If the default destination doesn't produce a constant result but is still
7740 // reachable, and the lookup table has holes, we need to use a mask to
7741 // determine if the current index should load from the lookup table or jump
7742 // to the default case.
7743 // The mask is unnecessary if the table has holes but the default destination
7744 // is unreachable, as in that case the holes must also be unreachable.
7745 bool NeedMask = AllHolesArePoison && DefaultIsReachable;
7746 if (NeedMask) {
7747 // As an extra penalty for the validity test we require more cases.
7748 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
7749 return false;
7750 if (!DL.fitsInLegalInteger(TableSize))
7751 return false;
7752 }
7753
7754 if (!shouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
7755 return false;
7756
7757 // Compute the table index value.
7758 Value *TableIndex;
7759 if (UseSwitchConditionAsTableIndex) {
7760 TableIndex = SI->getCondition();
7761 if (HasDefaultResults) {
7762 // Grow the table to cover all possible index values to avoid the range
7763 // check. It will use the default result to fill in the table hole later,
7764 // so make sure it exist.
7765 ConstantRange CR = computeConstantRange(TableIndex, /*ForSigned=*/false,
7766 SimplifyQuery(DL));
7767 // Grow the table shouldn't have any size impact by checking
7768 // wouldFitInRegister.
7769 // TODO: Consider growing the table also when it doesn't fit in a register
7770 // if no optsize is specified.
7771 const uint64_t UpperBound = CR.getUpper().getLimitedValue();
7772 if (!CR.isUpperWrapped() &&
7773 all_of(ResultTypes, [&](const auto &ResultType) {
7774 return SwitchReplacement::wouldFitInRegister(DL, UpperBound,
7775 ResultType);
7776 })) {
7777 // There may be some case index larger than the UpperBound (unreachable
7778 // case), so make sure the table size does not get smaller.
7779 TableSize = std::max(UpperBound, TableSize);
7780 // The default branch is unreachable after we enlarge the lookup table.
7781 // Adjust DefaultIsReachable to reuse code path.
7782 DefaultIsReachable = false;
7783 }
7784 }
7785 }
7786
7787 // Keep track of the switch replacement for each phi
7789 for (PHINode *PHI : PHIs) {
7790 const auto &ResultList = ResultLists[PHI];
7791
7792 Type *ResultType = ResultList.begin()->second->getType();
7793 // Use any value to fill the lookup table holes.
7794 Constant *DefaultVal =
7795 AllHolesArePoison ? PoisonValue::get(ResultType) : DefaultResults[PHI];
7796 StringRef FuncName = Fn->getName();
7797 SwitchReplacement Replacement(*Fn->getParent(), TableSize, TableIndexOffset,
7798 ResultList, DefaultVal, DL, TTI, FuncName);
7799 if (!Replacement.isValid())
7800 return false;
7801 PhiToReplacementMap.insert({PHI, Replacement});
7802 }
7803
7804 bool AnyLookupTables = any_of(
7805 PhiToReplacementMap, [](auto &KV) { return KV.second.isLookupTable(); });
7806 bool AnyBitMaps = any_of(PhiToReplacementMap,
7807 [](auto &KV) { return KV.second.isBitMap(); });
7808
7809 // A few conditions prevent the generation of lookup tables:
7810 // 1. The target does not support lookup tables.
7811 // 2. The "no-jump-tables" function attribute is set.
7812 // However, these objections do not apply to other switch replacements, like
7813 // the bitmap, so we only stop here if any of these conditions are met and we
7814 // want to create a LUT. Otherwise, continue with the switch replacement.
7815 if (AnyLookupTables &&
7816 (!TTI.shouldBuildLookupTables() ||
7817 Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
7818 return false;
7819
7820 // In the early optimization pipeline, disable formation of lookup tables,
7821 // bit maps and mask checks, as they may inhibit further optimization.
7822 if (!ConvertSwitchToLookupTable &&
7823 (AnyLookupTables || AnyBitMaps || NeedMask))
7824 return false;
7825
7826 Builder.SetInsertPoint(SI);
7827 // TableIndex is the switch condition - TableIndexOffset if we don't
7828 // use the condition directly
7829 if (!UseSwitchConditionAsTableIndex) {
7830 // If the default is unreachable, all case values are s>= MinCaseVal. Then
7831 // we can try to attach nsw.
7832 bool MayWrap = true;
7833 if (!DefaultIsReachable) {
7834 APInt Res =
7835 MaxCaseVal->getValue().ssub_ov(MinCaseVal->getValue(), MayWrap);
7836 (void)Res;
7837 }
7838 TableIndex = Builder.CreateSub(SI->getCondition(), TableIndexOffset,
7839 "switch.tableidx", /*HasNUW =*/false,
7840 /*HasNSW =*/!MayWrap);
7841 }
7842
7843 std::vector<DominatorTree::UpdateType> Updates;
7844
7845 // Compute the maximum table size representable by the integer type we are
7846 // switching upon.
7847 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
7848 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
7849 assert(MaxTableSize >= TableSize &&
7850 "It is impossible for a switch to have more entries than the max "
7851 "representable value of its input integer type's size.");
7852
7853 // Create the BB that does the lookups.
7854 Module &Mod = *CommonDest->getParent()->getParent();
7855 BasicBlock *LookupBB = BasicBlock::Create(
7856 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
7857
7858 CondBrInst *RangeCheckBranch = nullptr;
7859 CondBrInst *CondBranch = nullptr;
7860
7861 Builder.SetInsertPoint(SI);
7862 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
7863 const bool IsFullyCoveredLookupTable =
7864 !DefaultIsReachable || GeneratingCoveredLookupTable;
7865 if (IsFullyCoveredLookupTable) {
7866 Builder.CreateBr(LookupBB);
7867 if (DTU)
7868 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7869 // Note: We call removeProdecessor later since we need to be able to get the
7870 // PHI value for the default case in case we're using a bit mask.
7871 } else {
7872 Value *Cmp = Builder.CreateICmpULT(
7873 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
7874 RangeCheckBranch =
7875 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
7876 CondBranch = RangeCheckBranch;
7877 if (DTU)
7878 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7879 }
7880
7881 // Populate the BB that does the lookups.
7882 Builder.SetInsertPoint(LookupBB);
7883
7884 if (NeedMask) {
7885 // Before doing the lookup, we do the hole check. The LookupBB is therefore
7886 // re-purposed to do the hole check, and we create a new LookupBB.
7887 BasicBlock *MaskBB = LookupBB;
7888 MaskBB->setName("switch.hole_check");
7889 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
7890 CommonDest->getParent(), CommonDest);
7891
7892 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
7893 // unnecessary illegal types.
7894 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
7895 APInt MaskInt(TableSizePowOf2, 0);
7896 APInt One(TableSizePowOf2, 1);
7897 // Build bitmask; fill in a 1 bit for every case.
7898 const ResultListTy &ResultList = ResultLists[PHIs[0]];
7899 for (const auto &Result : ResultList) {
7900 uint64_t Idx = (Result.first->getValue() - TableIndexOffset->getValue())
7901 .getLimitedValue();
7902 MaskInt |= One << Idx;
7903 }
7904 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
7905
7906 // Get the TableIndex'th bit of the bitmask.
7907 // If this bit is 0 (meaning hole) jump to the default destination,
7908 // else continue with table lookup.
7909 IntegerType *MapTy = TableMask->getIntegerType();
7910 Value *MaskIndex =
7911 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
7912 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
7913 Value *LoBit = Builder.CreateTrunc(
7914 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
7915 if (!IsFullyCoveredLookupTable)
7917 CondBranch = Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
7918 if (DTU) {
7919 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
7920 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
7921 }
7922 Builder.SetInsertPoint(LookupBB);
7923 addPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
7924 }
7925
7926 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7927 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
7928 // do not delete PHINodes here.
7929 SI->getDefaultDest()->removePredecessor(BB,
7930 /*KeepOneInputPHIs=*/true);
7931 if (DTU)
7932 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
7933 }
7934
7935 for (PHINode *PHI : PHIs) {
7936 const ResultListTy &ResultList = ResultLists[PHI];
7937 auto Replacement = PhiToReplacementMap.at(PHI);
7938 auto *Result = Replacement.replaceSwitch(TableIndex, Builder, DL, Fn);
7939 // Do a small peephole optimization: re-use the switch table compare if
7940 // possible.
7941 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
7942 BasicBlock *PhiBlock = PHI->getParent();
7943 // Search for compare instructions which use the phi.
7944 for (auto *User : PHI->users()) {
7945 reuseTableCompare(User, PhiBlock, RangeCheckBranch,
7946 Replacement.getDefaultValue(), ResultList);
7947 }
7948 }
7949
7950 PHI->addIncoming(Result, LookupBB);
7951 }
7952
7953 Builder.CreateBr(CommonDest);
7954 if (DTU)
7955 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
7956
7957 SmallVector<uint32_t> BranchWeights;
7958 const bool HasBranchWeights =
7959 CondBranch && extractBranchWeights(*SI, BranchWeights);
7960 uint64_t ToLookupWeight = 0;
7961 uint64_t ToDefaultWeight = 0;
7962
7963 // Remove the switch.
7964 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
7965 for (unsigned I = 0, E = SI->getNumSuccessors(); I < E; ++I) {
7966 BasicBlock *Succ = SI->getSuccessor(I);
7967
7968 if (Succ == SI->getDefaultDest()) {
7969 if (HasBranchWeights)
7970 ToDefaultWeight += BranchWeights[I];
7971 continue;
7972 }
7973 Succ->removePredecessor(BB);
7974 if (DTU && RemovedSuccessors.insert(Succ).second)
7975 Updates.push_back({DominatorTree::Delete, BB, Succ});
7976 if (HasBranchWeights)
7977 ToLookupWeight += BranchWeights[I];
7978 }
7979 SI->eraseFromParent();
7980 // In the case where we do not have a fully covered lookup table (i.e., we
7981 // need a range check), and we need a mask check, we split the default case
7982 // into two different cases for which we cannot infer branch weights.
7983 // Otherwise we have a single branch for which we can infer branch weights.
7984 if ((NeedMask && !IsFullyCoveredLookupTable) &&
7987 else if (HasBranchWeights)
7988 setFittedBranchWeights(*CondBranch, {ToLookupWeight, ToDefaultWeight},
7989 /*IsExpected=*/false);
7990 if (DTU)
7991 DTU->applyUpdates(Updates);
7992
7993 if (NeedMask)
7994 ++NumLookupTablesHoles;
7995 return true;
7996}
7997
7998/// Try to transform a switch that has "holes" in it to a contiguous sequence
7999/// of cases.
8000///
8001/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
8002/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
8003///
8004/// This converts a sparse switch into a dense switch which allows better
8005/// lowering and could also allow transforming into a lookup table.
8007 const DataLayout &DL,
8008 const TargetTransformInfo &TTI) {
8009 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
8010 if (CondTy->getIntegerBitWidth() > 64 ||
8011 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8012 return false;
8013 // Only bother with this optimization if there are more than 3 switch cases;
8014 // SDAG will only bother creating jump tables for 4 or more cases.
8015 if (SI->getNumCases() < 4)
8016 return false;
8017
8018 // This transform is agnostic to the signedness of the input or case values. We
8019 // can treat the case values as signed or unsigned. We can optimize more common
8020 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
8021 // as signed.
8023 for (const auto &C : SI->cases())
8024 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
8026
8027 // If the switch is already dense, there's nothing useful to do here.
8028 bool OptSize = SI->getFunction()->hasOptSize();
8029 if (isSwitchDense(Values, OptSize))
8030 return false;
8031
8032 // Find a Base and corresponding Shift that results in a dense switch range.
8033 // Values[0] is the local minimum.
8034 int64_t Base = Values[0];
8035 std::optional<unsigned> Shift;
8036 // Prefer Base=0 when shifting out common low zero bits still produces a dense
8037 // range, as this avoids an unnecessary `(condition - local_min)` expression.
8038 // However, avoiding the subtract can leave a wider reduced range than using
8039 // the local minimum, so require Base=0 to satisfy the stricter optsize
8040 // density threshold before falling back to the normal density policy for
8041 // local-min.
8042 if ((Shift = getDenseSwitchRangeReductionShift(Values, /*Base=*/0,
8043 /*OptSize=*/true)))
8044 Base = 0;
8045 else if (Base != 0)
8047
8048 if (!Shift)
8049 return false;
8050
8051 // The obvious transform is to shift the switch condition right and emit a
8052 // check that the condition actually cleanly divided by GCD, i.e.
8053 // C & (1 << Shift - 1) == 0
8054 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
8055 //
8056 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
8057 // shift and puts the shifted-off bits in the uppermost bits. If any of these
8058 // are nonzero then the switch condition will be very large and will hit the
8059 // default case.
8060 //
8061 // This transform can be done speculatively because it is so cheap - it
8062 // results in a single rotate operation being inserted.
8063
8064 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
8065 Builder.SetInsertPoint(SI);
8066 Value *Sub = SI->getCondition();
8067 if (Base != 0)
8068 Sub = Builder.CreateSub(Sub, ConstantInt::getSigned(Ty, Base));
8069 Value *Rot = Builder.CreateIntrinsic(
8070 Ty, Intrinsic::fshl,
8071 {Sub, Sub, ConstantInt::get(Ty, Ty->getBitWidth() - *Shift)});
8072 SI->replaceUsesOfWith(SI->getCondition(), Rot);
8073
8074 for (auto Case : SI->cases()) {
8075 auto *Orig = Case.getCaseValue();
8076 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base, true);
8077 Case.setValue(cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(*Shift))));
8078 }
8079 return true;
8080}
8081
8082/// Tries to transform the switch when the condition is umin with a constant.
8083/// In that case, the default branch can be replaced by the constant's branch.
8084/// This method also removes dead cases when the simplification cannot replace
8085/// the default branch.
8086///
8087/// For example:
8088/// switch(umin(a, 3)) {
8089/// case 0:
8090/// case 1:
8091/// case 2:
8092/// case 3:
8093/// case 4:
8094/// // ...
8095/// default:
8096/// unreachable
8097/// }
8098///
8099/// Transforms into:
8100///
8101/// switch(a) {
8102/// case 0:
8103/// case 1:
8104/// case 2:
8105/// default:
8106/// // This is case 3
8107/// }
8109 Value *A;
8111
8112 if (!match(SI->getCondition(), m_UMin(m_Value(A), m_ConstantInt(Constant))))
8113 return false;
8114
8117 BasicBlock *BB = SIW->getParent();
8118
8119 // Dead cases are removed even when the simplification fails.
8120 // A case is dead when its value is higher than the Constant.
8121 for (auto I = SI->case_begin(), E = SI->case_end(); I != E;) {
8122 if (!I->getCaseValue()->getValue().ugt(Constant->getValue())) {
8123 ++I;
8124 continue;
8125 }
8126 BasicBlock *DeadCaseBB = I->getCaseSuccessor();
8127 DeadCaseBB->removePredecessor(BB);
8128 I = SIW.removeCase(I);
8129 E = SIW->case_end();
8130 if (!is_contained(successors(BB), DeadCaseBB))
8131 Updates.push_back({DominatorTree::Delete, BB, DeadCaseBB});
8132 }
8133
8134 auto Case = SI->findCaseValue(Constant);
8135 // If the case value is not found, `findCaseValue` returns the default case.
8136 // In this scenario, since there is no explicit `case 3:`, the simplification
8137 // fails. The simplification also fails when the switch’s default destination
8138 // is reachable.
8139 if (!SI->defaultDestUnreachable() || Case == SI->case_default()) {
8140 if (DTU)
8141 DTU->applyUpdates(Updates);
8142 return !Updates.empty();
8143 }
8144
8145 BasicBlock *Unreachable = SI->getDefaultDest();
8146 SIW.replaceDefaultDest(Case);
8147 SIW.removeCase(Case);
8148 SIW->setCondition(A);
8149
8150 Updates.push_back({DominatorTree::Delete, BB, Unreachable});
8151
8152 if (DTU)
8153 DTU->applyUpdates(Updates);
8154
8155 return true;
8156}
8157
8159 const DataLayout &DL,
8160 AssumptionCache *AC) {
8161 assert(SI);
8162 if (SI->defaultDestUnreachable())
8163 return false;
8164
8165 // If it can be proved that the switch condition takes some concrete value
8166 // in the default block, we can make some nice simplifications to the
8167 // switch.
8168 BasicBlock *Default = SI->getDefaultDest();
8169 const Instruction *CtxI = &*Default->getFirstNonPHIIt();
8171 SI->getCondition(),
8172 SimplifyQuery(DL, /*DT=*/nullptr, AC, CtxI).allowEphemerals(true));
8173 if (!Known.isConstant())
8174 return false;
8175
8176 // At this point, we know that only one value can be mapped to the
8177 // default block. So, if a case doesn't exist for it already, we
8178 // can create one pointing to the default block.
8179 ConstantInt *CaseVal =
8180 ConstantInt::get(SI->getContext(), Known.getConstant());
8181 const llvm::SwitchInst::CaseIt CaseIt = SI->findCaseValue(CaseVal);
8182 if (CaseIt == SI->case_default()) {
8184 SIW.addCase(CaseVal, Default, SIW.getSuccessorWeight(0));
8185 SIW.setSuccessorWeight(0, 0);
8186 }
8187 // If there is a pre-existing case for the constant, the default branch
8188 // will be removed rather than being moved. Thus, we are removing an edge
8189 // in the CFG, and need to update any PHIs in the default block.
8190 createUnreachableSwitchDefault(SI, DTU, /*RemoveOrigDefaultBlock=*/CaseIt !=
8191 SI->case_default());
8192
8193 assert(SI->getNumCases() > 0 && "Switch should have at least one case");
8194 assert(SI->findCaseValue(CaseVal) != SI->case_default() &&
8195 "Proven value should have a dedicated case");
8196 assert(SI->defaultDestUnreachable());
8197 return true;
8198}
8199
8200/// Tries to transform switch of powers of two to reduce switch range.
8201/// For example, switch like:
8202/// switch (C) { case 1: case 2: case 64: case 128: }
8203/// will be transformed to:
8204/// switch (count_trailing_zeros(C)) { case 0: case 1: case 6: case 7: }
8205///
8206/// This transformation allows better lowering and may transform the switch
8207/// instruction into a sequence of bit manipulation and a smaller
8208/// log2(C)-indexed value table (instead of traditionally emitting a load of the
8209/// address of the jump target, and indirectly jump to it).
8211 DomTreeUpdater *DTU,
8212 const DataLayout &DL,
8213 const TargetTransformInfo &TTI) {
8214 Value *Condition = SI->getCondition();
8215 LLVMContext &Context = SI->getContext();
8216 auto *CondTy = cast<IntegerType>(Condition->getType());
8217
8218 if (CondTy->getIntegerBitWidth() > 64 ||
8219 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8220 return false;
8221
8222 // Ensure trailing zeroes count intrinsic emission is not too expensive.
8223 IntrinsicCostAttributes Attrs(Intrinsic::cttz, CondTy,
8224 {Condition, ConstantInt::getTrue(Context)});
8225 if (TTI.getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) >
8226 TTI::TCC_Basic * 2)
8227 return false;
8228
8229 // Only bother with this optimization if there are more than 3 switch cases.
8230 // SDAG will start emitting jump tables for 4 or more cases.
8231 if (SI->getNumCases() < 4)
8232 return false;
8233
8234 // Check that switch cases are powers of two.
8236 for (const auto &Case : SI->cases()) {
8237 uint64_t CaseValue = Case.getCaseValue()->getValue().getZExtValue();
8238 if (llvm::has_single_bit(CaseValue))
8239 Values.push_back(CaseValue);
8240 else
8241 return false;
8242 }
8243
8244 // isSwichDense requires case values to be sorted.
8246 if (!isSwitchDense(Values.size(),
8247 llvm::countr_zero(Values.back()) -
8248 llvm::countr_zero(Values.front()) + 1,
8249 SI->getFunction()->hasOptSize()))
8250 // Transform is unable to generate dense switch.
8251 return false;
8252
8253 Builder.SetInsertPoint(SI);
8254
8255 if (!SI->defaultDestUnreachable()) {
8256 // Let non-power-of-two inputs jump to the default case, when the latter is
8257 // reachable.
8258 auto *PopC = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Condition);
8259 auto *IsPow2 = Builder.CreateICmpEQ(PopC, ConstantInt::get(CondTy, 1));
8260
8261 auto *OrigBB = SI->getParent();
8262 auto *DefaultCaseBB = SI->getDefaultDest();
8263 BasicBlock *SplitBB = SplitBlock(OrigBB, SI, DTU);
8264 auto It = OrigBB->getTerminator()->getIterator();
8265 SmallVector<uint32_t> Weights;
8266 auto HasWeights = extractBranchWeights(*SI, Weights);
8267 auto *BI = CondBrInst::Create(IsPow2, SplitBB, DefaultCaseBB, It);
8268 if (HasWeights && any_of(Weights, not_equal_to(0))) {
8269 // IsPow2 covers a subset of the cases in which we'd go to the default
8270 // label. The other is those powers of 2 that don't appear in the case
8271 // statement. We don't know the distribution of the values coming in, so
8272 // the safest is to split 50-50 the original probability to `default`.
8273 uint64_t OrigDenominator =
8275 SmallVector<uint64_t> NewWeights(2);
8276 NewWeights[1] = Weights[0] / 2;
8277 NewWeights[0] = OrigDenominator - NewWeights[1];
8278 setFittedBranchWeights(*BI, NewWeights, /*IsExpected=*/false);
8279 // The probability of executing the default block stays constant. It was
8280 // p_d = Weights[0] / OrigDenominator
8281 // we rewrite as W/D
8282 // We want to find the probability of the default branch of the switch
8283 // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
8284 // i.e. the original probability is the probability we go to the default
8285 // branch from the BI branch, or we take the default branch on the SI.
8286 // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
8287 // This matches using W/2 for the default branch probability numerator and
8288 // D-W/2 as the denominator.
8289 Weights[0] = NewWeights[1];
8290 uint64_t CasesDenominator = OrigDenominator - Weights[0];
8291 for (auto &W : drop_begin(Weights))
8292 W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
8293
8294 setBranchWeights(*SI, Weights, /*IsExpected=*/false);
8295 }
8296 // BI is handling the default case for SI, and so should share its DebugLoc.
8297 BI->setDebugLoc(SI->getDebugLoc());
8298 It->eraseFromParent();
8299
8300 addPredecessorToBlock(DefaultCaseBB, OrigBB, SplitBB);
8301 if (DTU)
8302 DTU->applyUpdates({{DominatorTree::Insert, OrigBB, DefaultCaseBB}});
8303 }
8304
8305 // Replace each case with its trailing zeros number.
8306 for (auto &Case : SI->cases()) {
8307 auto *OrigValue = Case.getCaseValue();
8308 Case.setValue(ConstantInt::get(OrigValue->getIntegerType(),
8309 OrigValue->getValue().countr_zero()));
8310 }
8311
8312 // Replace condition with its trailing zeros number.
8313 auto *ConditionTrailingZeros = Builder.CreateIntrinsic(
8314 Intrinsic::cttz, {CondTy}, {Condition, ConstantInt::getTrue(Context)});
8315
8316 SI->setCondition(ConditionTrailingZeros);
8317
8318 return true;
8319}
8320
8321/// Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have
8322/// the same destination.
8324 DomTreeUpdater *DTU) {
8325 auto *Cmp = dyn_cast<CmpIntrinsic>(SI->getCondition());
8326 if (!Cmp || !Cmp->hasOneUse())
8327 return false;
8328
8330 bool HasWeights = extractBranchWeights(getBranchWeightMDNode(*SI), Weights);
8331 if (!HasWeights)
8332 Weights.resize(4); // Avoid checking HasWeights everywhere.
8333
8334 // Normalize to [us]cmp == Res ? Succ : OtherSucc.
8335 int64_t Res;
8336 BasicBlock *Succ, *OtherSucc;
8337 uint32_t SuccWeight = 0, OtherSuccWeight = 0;
8338 BasicBlock *Unreachable = nullptr;
8339
8340 if (SI->getNumCases() == 2) {
8341 // Find which of 1, 0 or -1 is missing (handled by default dest).
8342 SmallSet<int64_t, 3> Missing;
8343 Missing.insert(1);
8344 Missing.insert(0);
8345 Missing.insert(-1);
8346
8347 Succ = SI->getDefaultDest();
8348 SuccWeight = Weights[0];
8349 OtherSucc = nullptr;
8350 for (auto &Case : SI->cases()) {
8351 std::optional<int64_t> Val =
8352 Case.getCaseValue()->getValue().trySExtValue();
8353 if (!Val)
8354 return false;
8355 if (!Missing.erase(*Val))
8356 return false;
8357 if (OtherSucc && OtherSucc != Case.getCaseSuccessor())
8358 return false;
8359 OtherSucc = Case.getCaseSuccessor();
8360 OtherSuccWeight += Weights[Case.getSuccessorIndex()];
8361 }
8362
8363 assert(Missing.size() == 1 && "Should have one case left");
8364 Res = *Missing.begin();
8365 } else if (SI->getNumCases() == 3 && SI->defaultDestUnreachable()) {
8366 // Normalize so that Succ is taken once and OtherSucc twice.
8367 Unreachable = SI->getDefaultDest();
8368 Succ = OtherSucc = nullptr;
8369 for (auto &Case : SI->cases()) {
8370 BasicBlock *NewSucc = Case.getCaseSuccessor();
8371 uint32_t Weight = Weights[Case.getSuccessorIndex()];
8372 if (!OtherSucc || OtherSucc == NewSucc) {
8373 OtherSucc = NewSucc;
8374 OtherSuccWeight += Weight;
8375 } else if (!Succ) {
8376 Succ = NewSucc;
8377 SuccWeight = Weight;
8378 } else if (Succ == NewSucc) {
8379 std::swap(Succ, OtherSucc);
8380 std::swap(SuccWeight, OtherSuccWeight);
8381 } else
8382 return false;
8383 }
8384 for (auto &Case : SI->cases()) {
8385 std::optional<int64_t> Val =
8386 Case.getCaseValue()->getValue().trySExtValue();
8387 if (!Val || (Val != 1 && Val != 0 && Val != -1))
8388 return false;
8389 if (Case.getCaseSuccessor() == Succ) {
8390 Res = *Val;
8391 break;
8392 }
8393 }
8394 } else {
8395 return false;
8396 }
8397
8398 // Determine predicate for the missing case.
8400 switch (Res) {
8401 case 1:
8402 Pred = ICmpInst::ICMP_UGT;
8403 break;
8404 case 0:
8405 Pred = ICmpInst::ICMP_EQ;
8406 break;
8407 case -1:
8408 Pred = ICmpInst::ICMP_ULT;
8409 break;
8410 }
8411 if (Cmp->isSigned())
8412 Pred = ICmpInst::getSignedPredicate(Pred);
8413
8414 MDNode *NewWeights = nullptr;
8415 if (HasWeights)
8416 NewWeights = MDBuilder(SI->getContext())
8417 .createBranchWeights(SuccWeight, OtherSuccWeight);
8418
8419 BasicBlock *BB = SI->getParent();
8420 Builder.SetInsertPoint(SI->getIterator());
8421 Value *ICmp = Builder.CreateICmp(Pred, Cmp->getLHS(), Cmp->getRHS());
8422 Builder.CreateCondBr(ICmp, Succ, OtherSucc, NewWeights,
8423 SI->getMetadata(LLVMContext::MD_unpredictable));
8424 OtherSucc->removePredecessor(BB);
8425 if (Unreachable)
8426 Unreachable->removePredecessor(BB);
8427 SI->eraseFromParent();
8428 Cmp->eraseFromParent();
8429 if (DTU && Unreachable)
8430 DTU->applyUpdates({{DominatorTree::Delete, BB, Unreachable}});
8431 return true;
8432}
8433
8434/// Checking whether two BBs are equal depends on the contents of the
8435/// BasicBlock and the incoming values of their successor PHINodes.
8436/// PHINode::getIncomingValueForBlock is O(|Preds|), so we'd like to avoid
8437/// calling this function on each BasicBlock every time isEqual is called,
8438/// especially since the same BasicBlock may be passed as an argument multiple
8439/// times. To do this, we can precompute a map of PHINode -> Pred BasicBlock ->
8440/// IncomingValue and add it in the Wrapper so isEqual can do O(1) checking
8441/// of the incoming values.
8444
8445 // One Phi usually has < 8 incoming values.
8449
8450 // We only merge the identical non-entry BBs with
8451 // - terminator unconditional br to Succ (pending relaxation),
8452 // - does not have address taken / weird control.
8453 static bool canBeMerged(const BasicBlock *BB) {
8454 assert(BB && "Expected non-null BB");
8455 // Entry block cannot be eliminated or have predecessors.
8456 if (BB->isEntryBlock())
8457 return false;
8458
8459 // Single successor and must be Succ.
8460 // FIXME: Relax that the terminator is a BranchInst by checking for equality
8461 // on other kinds of terminators. We decide to only support unconditional
8462 // branches for now for compile time reasons.
8463 auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
8464 if (!BI)
8465 return false;
8466
8467 // Avoid blocks that are "address-taken" (blockaddress) or have unusual
8468 // uses.
8469 if (BB->hasAddressTaken() || BB->isEHPad())
8470 return false;
8471
8472 // TODO: relax this condition to merge equal blocks with >1 instructions?
8473 // Here, we use a O(1) form of the O(n) comparison of `size() != 1`.
8474 if (&BB->front() != &BB->back())
8475 return false;
8476
8477 // The BB must have at least one predecessor.
8478 if (pred_empty(BB))
8479 return false;
8480
8481 return true;
8482 }
8483};
8484
8486 static unsigned getHashValue(const EqualBBWrapper *EBW) {
8487 BasicBlock *BB = EBW->BB;
8489 assert(BB->size() == 1 && "Expected just a single branch in the BB");
8490
8491 // Since we assume the BB is just a single UncondBrInst with a single
8492 // successor, we hash as the BB and the incoming Values of its successor
8493 // PHIs. Initially, we tried to just use the successor BB as the hash, but
8494 // including the incoming PHI values leads to better performance.
8495 // We also tried to build a map from BB -> Succs.IncomingValues ahead of
8496 // time and passing it in EqualBBWrapper, but this slowed down the average
8497 // compile time without having any impact on the worst case compile time.
8498 BasicBlock *Succ = BI->getSuccessor();
8499 auto PhiValsForBB = map_range(Succ->phis(), [&](PHINode &Phi) {
8500 return (*EBW->PhiPredIVs)[&Phi][BB];
8501 });
8502 return hash_combine(Succ, hash_combine_range(PhiValsForBB));
8503 }
8504 static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS) {
8505 BasicBlock *A = LHS->BB;
8506 BasicBlock *B = RHS->BB;
8507
8508 // FIXME: we checked that the size of A and B are both 1 in
8509 // mergeIdenticalUncondBBs to make the Case list smaller to
8510 // improve performance. If we decide to support BasicBlocks with more
8511 // than just a single instruction, we need to check that A.size() ==
8512 // B.size() here, and we need to check more than just the BranchInsts
8513 // for equality.
8514
8515 UncondBrInst *ABI = cast<UncondBrInst>(A->getTerminator());
8516 UncondBrInst *BBI = cast<UncondBrInst>(B->getTerminator());
8517 if (ABI->getSuccessor() != BBI->getSuccessor())
8518 return false;
8519
8520 // Need to check that PHIs in successor have matching values.
8521 BasicBlock *Succ = ABI->getSuccessor();
8522 auto IfPhiIVMatch = [&](PHINode &Phi) {
8523 // Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
8524 // query.
8525 auto &PredIVs = (*LHS->PhiPredIVs)[&Phi];
8526 return PredIVs[A] == PredIVs[B];
8527 };
8528 return all_of(Succ->phis(), IfPhiIVMatch);
8529 }
8530};
8531
8532// Merge identical BBs into one of them.
8534 DomTreeUpdater *DTU) {
8535 if (Candidates.size() < 2)
8536 return false;
8537
8538 // Build Cases. Skip BBs that are not candidates for simplification. Mark
8539 // PHINodes which need to be processed into PhiPredIVs. We decide to process
8540 // an entire PHI at once after the loop, opposed to calling
8541 // getIncomingValueForBlock inside this loop, since each call to
8542 // getIncomingValueForBlock is O(|Preds|).
8543 EqualBBWrapper::Phi2IVsMap PhiPredIVs;
8545 BBs2Merge.reserve(Candidates.size());
8547
8548 for (BasicBlock *BB : Candidates) {
8549 BasicBlock *Succ = BB->getSingleSuccessor();
8550 assert(Succ && "Expected unconditional BB");
8551 BBs2Merge.emplace_back(EqualBBWrapper{BB, &PhiPredIVs});
8552 Phis.insert_range(make_pointer_range(Succ->phis()));
8553 }
8554
8555 // Precompute a data structure to improve performance of isEqual for
8556 // EqualBBWrapper.
8557 PhiPredIVs.reserve(Phis.size());
8558 for (PHINode *Phi : Phis) {
8559 auto &IVs =
8560 PhiPredIVs.try_emplace(Phi, Phi->getNumIncomingValues()).first->second;
8561 // Pre-fill all incoming for O(1) lookup as Phi.getIncomingValueForBlock is
8562 // O(|Pred|).
8563 for (auto &IV : Phi->incoming_values())
8564 IVs.insert({Phi->getIncomingBlock(IV), IV.get()});
8565 }
8566
8567 // Group duplicates using DenseSet with custom equality/hashing.
8568 // Build a set such that if the EqualBBWrapper exists in the set and another
8569 // EqualBBWrapper isEqual, then the equivalent EqualBBWrapper which is not in
8570 // the set should be replaced with the one in the set. If the EqualBBWrapper
8571 // is not in the set, then it should be added to the set so other
8572 // EqualBBWrapper can check against it in the same manner. We use
8573 // EqualBBWrapper instead of just BasicBlock because we'd like to pass around
8574 // information to isEquality, getHashValue, and when doing the replacement
8575 // with better performance.
8577 Keep.reserve(BBs2Merge.size());
8578
8580 Updates.reserve(BBs2Merge.size() * 2);
8581
8582 bool MadeChange = false;
8583
8584 // Helper: redirect all edges X -> DeadPred to X -> LivePred.
8585 auto RedirectIncomingEdges = [&](BasicBlock *Dead, BasicBlock *Live) {
8588 if (DTU) {
8589 // All predecessors of DeadPred (except the common predecessor) will be
8590 // moved to LivePred.
8591 Updates.reserve(Updates.size() + DeadPreds.size() * 2);
8593 predecessors(Live));
8594 for (BasicBlock *PredOfDead : DeadPreds) {
8595 // Do not modify those common predecessors of DeadPred and LivePred.
8596 if (!LivePreds.contains(PredOfDead))
8597 Updates.push_back({DominatorTree::Insert, PredOfDead, Live});
8598 Updates.push_back({DominatorTree::Delete, PredOfDead, Dead});
8599 }
8600 }
8601 LLVM_DEBUG(dbgs() << "Replacing duplicate pred BB ";
8602 Dead->printAsOperand(dbgs()); dbgs() << " with pred ";
8603 Live->printAsOperand(dbgs()); dbgs() << " for ";
8604 Live->getSingleSuccessor()->printAsOperand(dbgs());
8605 dbgs() << "\n");
8606 // Replace successors in all predecessors of DeadPred.
8607 for (BasicBlock *PredOfDead : DeadPreds) {
8608 Instruction *T = PredOfDead->getTerminator();
8609 T->replaceSuccessorWith(Dead, Live);
8610 }
8611 };
8612
8613 // Try to eliminate duplicate predecessors.
8614 for (const auto &EBW : BBs2Merge) {
8615 // EBW is a candidate for simplification. If we find a duplicate BB,
8616 // replace it.
8617 const auto &[It, Inserted] = Keep.insert(&EBW);
8618 if (Inserted)
8619 continue;
8620
8621 // Found duplicate: merge P into canonical predecessor It->Pred.
8622 BasicBlock *KeepBB = (*It)->BB;
8623 BasicBlock *DeadBB = EBW.BB;
8624
8625 // Avoid merging a BB with itself.
8626 if (KeepBB == DeadBB)
8627 continue;
8628
8629 // Redirect all edges into DeadPred to KeepPred.
8630 RedirectIncomingEdges(DeadBB, KeepBB);
8631
8632 // Now DeadBB should become unreachable; leave DCE to later,
8633 // but we can try to simplify it if it only branches to Succ.
8634 // (We won't erase here to keep the routine simple and DT-safe.)
8635 assert(pred_empty(DeadBB) && "DeadBB should be unreachable.");
8636 MadeChange = true;
8637 }
8638
8639 if (DTU && !Updates.empty())
8640 DTU->applyUpdates(Updates);
8641
8642 return MadeChange;
8643}
8644
8645bool SimplifyCFGOpt::simplifyDuplicateSwitchArms(SwitchInst *SI,
8646 DomTreeUpdater *DTU) {
8647 // Collect candidate switch-arms top-down.
8648 SmallSetVector<BasicBlock *, 16> FilteredArms(
8651 return mergeIdenticalBBs(FilteredArms.getArrayRef(), DTU);
8652}
8653
8654bool SimplifyCFGOpt::simplifyDuplicatePredecessors(BasicBlock *BB,
8655 DomTreeUpdater *DTU) {
8656 // Need at least 2 predecessors to do anything.
8657 if (!BB || !BB->hasNPredecessorsOrMore(2))
8658 return false;
8659
8660 // Compilation time consideration: retain the canonical loop, otherwise, we
8661 // require more time in the later loop canonicalization.
8662 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BB))
8663 return false;
8664
8665 // Collect candidate predecessors bottom-up.
8666 SmallSetVector<BasicBlock *, 8> FilteredPreds(
8669 return mergeIdenticalBBs(FilteredPreds.getArrayRef(), DTU);
8670}
8671
8672bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
8673 BasicBlock *BB = SI->getParent();
8674
8675 if (isValueEqualityComparison(SI)) {
8676 // If we only have one predecessor, and if it is a branch on this value,
8677 // see if that predecessor totally determines the outcome of this switch.
8678 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8679 if (simplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
8680 return requestResimplify();
8681
8682 Value *Cond = SI->getCondition();
8683 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
8684 if (simplifySwitchOnSelect(SI, Select))
8685 return requestResimplify();
8686
8687 // If the block only contains the switch, see if we can fold the block
8688 // away into any preds.
8689 if (SI == &*BB->begin())
8690 if (foldValueComparisonIntoPredecessors(SI, Builder))
8691 return requestResimplify();
8692 }
8693
8694 // Try to transform the switch into an icmp and a branch.
8695 // The conversion from switch to comparison may lose information on
8696 // impossible switch values, so disable it early in the pipeline.
8697 if (Options.ConvertSwitchRangeToICmp && turnSwitchRangeIntoICmp(SI, Builder))
8698 return requestResimplify();
8699
8700 // Remove unreachable cases.
8701 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
8702 return requestResimplify();
8703
8704 if (simplifySwitchOfCmpIntrinsic(SI, Builder, DTU))
8705 return requestResimplify();
8706
8707 if (trySwitchToSelect(SI, Builder, DTU, DL))
8708 return requestResimplify();
8709
8710 if (Options.ForwardSwitchCondToPhi && forwardSwitchConditionToPHI(SI))
8711 return requestResimplify();
8712
8713 // The conversion of switches to arithmetic or lookup table is disabled in
8714 // the early optimization pipeline, as it may lose information or make the
8715 // resulting code harder to analyze.
8716 if (Options.ConvertSwitchToArithmetic || Options.ConvertSwitchToLookupTable)
8717 if (simplifySwitchLookup(SI, Builder, DTU, DL, TTI,
8718 Options.ConvertSwitchToLookupTable))
8719 return requestResimplify();
8720
8721 if (simplifySwitchOfPowersOfTwo(SI, Builder, DTU, DL, TTI))
8722 return requestResimplify();
8723
8724 if (reduceSwitchRange(SI, Builder, DL, TTI))
8725 return requestResimplify();
8726
8727 if (HoistCommon &&
8728 hoistCommonCodeFromSuccessors(SI, !Options.HoistCommonInsts))
8729 return requestResimplify();
8730
8731 // We can merge identical switch arms early to enhance more aggressive
8732 // optimization on switch.
8733 if (simplifyDuplicateSwitchArms(SI, DTU))
8734 return requestResimplify();
8735
8736 if (simplifySwitchWhenUMin(SI, DTU))
8737 return requestResimplify();
8738
8739 if (simplifySwitchDefaultBranch(SI, DTU, DL, Options.AC))
8740 return requestResimplify();
8741
8742 return false;
8743}
8744
8745bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
8746 BasicBlock *BB = IBI->getParent();
8747 bool Changed = false;
8748 SmallVector<uint32_t> BranchWeights;
8749 const bool HasBranchWeights = extractBranchWeights(*IBI, BranchWeights);
8750
8751 DenseMap<const BasicBlock *, uint64_t> TargetWeight;
8752 if (HasBranchWeights)
8753 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8754 TargetWeight[IBI->getDestination(I)] += BranchWeights[I];
8755
8756 // Eliminate redundant destinations.
8757 SmallPtrSet<Value *, 8> Succs;
8758 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
8759 for (unsigned I = 0, E = IBI->getNumDestinations(); I != E; ++I) {
8760 BasicBlock *Dest = IBI->getDestination(I);
8761 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
8762 if (!Dest->hasAddressTaken())
8763 RemovedSuccs.insert(Dest);
8764 Dest->removePredecessor(BB);
8765 IBI->removeDestination(I);
8766 --I;
8767 --E;
8768 Changed = true;
8769 }
8770 }
8771
8772 if (DTU) {
8773 std::vector<DominatorTree::UpdateType> Updates;
8774 Updates.reserve(RemovedSuccs.size());
8775 for (auto *RemovedSucc : RemovedSuccs)
8776 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
8777 DTU->applyUpdates(Updates);
8778 }
8779
8780 if (IBI->getNumDestinations() == 0) {
8781 // If the indirectbr has no successors, change it to unreachable.
8782 new UnreachableInst(IBI->getContext(), IBI->getIterator());
8784 return true;
8785 }
8786
8787 if (IBI->getNumDestinations() == 1) {
8788 // If the indirectbr has one successor, change it to a direct branch.
8791 return true;
8792 }
8793 if (HasBranchWeights) {
8794 SmallVector<uint64_t> NewBranchWeights(IBI->getNumDestinations());
8795 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8796 NewBranchWeights[I] += TargetWeight.find(IBI->getDestination(I))->second;
8797 setFittedBranchWeights(*IBI, NewBranchWeights, /*IsExpected=*/false);
8798 }
8799 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
8800 if (simplifyIndirectBrOnSelect(IBI, SI))
8801 return requestResimplify();
8802 }
8803 return Changed;
8804}
8805
8806/// Given an block with only a single landing pad and a unconditional branch
8807/// try to find another basic block which this one can be merged with. This
8808/// handles cases where we have multiple invokes with unique landing pads, but
8809/// a shared handler.
8810///
8811/// We specifically choose to not worry about merging non-empty blocks
8812/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
8813/// practice, the optimizer produces empty landing pad blocks quite frequently
8814/// when dealing with exception dense code. (see: instcombine, gvn, if-else
8815/// sinking in this file)
8816///
8817/// This is primarily a code size optimization. We need to avoid performing
8818/// any transform which might inhibit optimization (such as our ability to
8819/// specialize a particular handler via tail commoning). We do this by not
8820/// merging any blocks which require us to introduce a phi. Since the same
8821/// values are flowing through both blocks, we don't lose any ability to
8822/// specialize. If anything, we make such specialization more likely.
8823///
8824/// Phis in the successor are allowed if both blocks pass the same value, or
8825/// each passes its own landing pad value and that is its only use: the merged
8826/// block's landing pad then carries the value for both edges.
8828 BasicBlock *BB, DomTreeUpdater *DTU) {
8829 auto Succ = BB->getUniqueSuccessor();
8830 assert(Succ);
8831
8832 for (BasicBlock *OtherPred : predecessors(Succ)) {
8833 if (BB == OtherPred)
8834 continue;
8835 BasicBlock::iterator I = OtherPred->begin();
8837 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
8838 continue;
8839 ++I;
8841 if (!BI2 || !BI2->isIdenticalTo(BI))
8842 continue;
8843
8844 // Merging must not require a new phi in the merged landing pad block.
8845 if (!all_of(Succ->phis(), [&](PHINode &PN) {
8846 Value *V = PN.getIncomingValueForBlock(BB);
8847 Value *V2 = PN.getIncomingValueForBlock(OtherPred);
8848 return V == V2 || (V == LPad && V2 == LPad2);
8849 }))
8850 continue;
8851
8852 // Those phis must be the only uses of the landing pads. Otherwise, with a
8853 // loop through Succ, a use would be clobbered when the merged pad is
8854 // re-entered.
8855 unsigned NumLPadPhis = count_if(Succ->phis(), [&](PHINode &PN) {
8856 return PN.getIncomingValueForBlock(BB) == LPad;
8857 });
8858 if (!LPad->hasNUses(NumLPadPhis) || !LPad2->hasNUses(NumLPadPhis))
8859 continue;
8860
8861 std::vector<DominatorTree::UpdateType> Updates;
8862
8863 // We've found an identical block. Update our predecessors to take that
8864 // path instead and make ourselves dead.
8866 for (BasicBlock *Pred : UniquePreds) {
8867 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
8868 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
8869 "unexpected successor");
8870 II->setUnwindDest(OtherPred);
8871 if (DTU) {
8872 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
8873 Updates.push_back({DominatorTree::Delete, Pred, BB});
8874 }
8875 }
8876
8878 for (BasicBlock *Succ : UniqueSuccs) {
8879 Succ->removePredecessor(BB);
8880 if (DTU)
8881 Updates.push_back({DominatorTree::Delete, BB, Succ});
8882 }
8883
8884 IRBuilder<> Builder(BI);
8885 Builder.CreateUnreachable();
8886 BI->eraseFromParent();
8887 if (DTU)
8888 DTU->applyUpdates(Updates);
8889 return true;
8890 }
8891 return false;
8892}
8893
8894bool SimplifyCFGOpt::simplifyUncondBranch(UncondBrInst *BI,
8895 IRBuilder<> &Builder) {
8896 BasicBlock *BB = BI->getParent();
8897 BasicBlock *Succ = BI->getSuccessor(0);
8898
8899 // If the Terminator is the only non-phi instruction, simplify the block.
8900 // If LoopHeader is provided, check if the block or its successor is a loop
8901 // header. (This is for early invocations before loop simplify and
8902 // vectorization to keep canonical loop forms for nested loops. These blocks
8903 // can be eliminated when the pass is invoked later in the back-end.)
8904 // Note that if BB has only one predecessor then we do not introduce new
8905 // backedge, so we can eliminate BB.
8906 bool NeedCanonicalLoop =
8907 Options.NeedCanonicalLoop &&
8908 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
8909 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
8911 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
8912 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
8913 return true;
8914
8915 // If the only instruction in the block is a seteq/setne comparison against a
8916 // constant, try to simplify the block.
8917 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
8918 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
8919 ++I;
8920 if (I->isTerminator() &&
8921 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
8922 return true;
8923 if (isa<SelectInst>(I) && I->getNextNode()->isTerminator() &&
8924 tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, cast<SelectInst>(I),
8925 Builder))
8926 return true;
8927 }
8928 }
8929
8930 // See if we can merge an empty landing pad block with another which is
8931 // equivalent.
8932 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
8933 ++I;
8934 if (I->isTerminator() && tryToMergeLandingPad(LPad, BI, BB, DTU))
8935 return true;
8936 }
8937
8938 return false;
8939}
8940
8942 BasicBlock *PredPred = nullptr;
8943 for (auto *P : predecessors(BB)) {
8944 BasicBlock *PPred = P->getSinglePredecessor();
8945 if (!PPred || (PredPred && PredPred != PPred))
8946 return nullptr;
8947 PredPred = PPred;
8948 }
8949 return PredPred;
8950}
8951
8952/// Fold the following pattern:
8953/// bb0:
8954/// br i1 %cond1, label %bb1, label %bb2
8955/// bb1:
8956/// br i1 %cond2, label %bb3, label %bb4
8957/// bb2:
8958/// br i1 %cond2, label %bb4, label %bb3
8959/// bb3:
8960/// ...
8961/// bb4:
8962/// ...
8963/// into
8964/// bb0:
8965/// %cond = xor i1 %cond1, %cond2
8966/// br i1 %cond, label %bb4, label %bb3
8967/// bb3:
8968/// ...
8969/// bb4:
8970/// ...
8971/// NOTE: %cond2 always dominates the terminator of bb0.
8973 BasicBlock *BB = BI->getParent();
8974 BasicBlock *BB1 = BI->getSuccessor(0);
8975 BasicBlock *BB2 = BI->getSuccessor(1);
8976 auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
8977 if (Succ == BB)
8978 return false;
8979 if (&Succ->front() != Succ->getTerminator())
8980 return false;
8981 SuccBI = dyn_cast<CondBrInst>(Succ->getTerminator());
8982 if (!SuccBI)
8983 return false;
8984 BasicBlock *Succ1 = SuccBI->getSuccessor(0);
8985 BasicBlock *Succ2 = SuccBI->getSuccessor(1);
8986 return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
8987 !isa<PHINode>(Succ1->front()) && !isa<PHINode>(Succ2->front());
8988 };
8989 CondBrInst *BB1BI, *BB2BI;
8990 if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
8991 return false;
8992
8993 if (BB1BI->getCondition() != BB2BI->getCondition() ||
8994 BB1BI->getSuccessor(0) != BB2BI->getSuccessor(1) ||
8995 BB1BI->getSuccessor(1) != BB2BI->getSuccessor(0))
8996 return false;
8997
8998 BasicBlock *BB3 = BB1BI->getSuccessor(0);
8999 BasicBlock *BB4 = BB1BI->getSuccessor(1);
9000 // Bail out on trivial cases to avoid bothering to handle the special case in
9001 // the code below.
9002 if (BB3 == BB4)
9003 return false;
9004 IRBuilder<> Builder(BI);
9005 BI->setCondition(
9006 Builder.CreateXor(BI->getCondition(), BB1BI->getCondition()));
9007 BB1->removePredecessor(BB);
9008 BI->setSuccessor(0, BB4);
9009 BB2->removePredecessor(BB);
9010 BI->setSuccessor(1, BB3);
9011 if (DTU) {
9013 Updates.push_back({DominatorTree::Delete, BB, BB1});
9014 Updates.push_back({DominatorTree::Insert, BB, BB4});
9015 Updates.push_back({DominatorTree::Delete, BB, BB2});
9016 Updates.push_back({DominatorTree::Insert, BB, BB3});
9017
9018 DTU->applyUpdates(Updates);
9019 }
9020 bool HasWeight = false;
9021 uint64_t BBTWeight, BBFWeight;
9022 if (extractBranchWeights(*BI, BBTWeight, BBFWeight))
9023 HasWeight = true;
9024 else
9025 BBTWeight = BBFWeight = 1;
9026 uint64_t BB1TWeight, BB1FWeight;
9027 if (extractBranchWeights(*BB1BI, BB1TWeight, BB1FWeight))
9028 HasWeight = true;
9029 else
9030 BB1TWeight = BB1FWeight = 1;
9031 uint64_t BB2TWeight, BB2FWeight;
9032 if (extractBranchWeights(*BB2BI, BB2TWeight, BB2FWeight))
9033 HasWeight = true;
9034 else
9035 BB2TWeight = BB2FWeight = 1;
9036 if (HasWeight) {
9037 uint64_t Weights[2] = {BBTWeight * BB1FWeight + BBFWeight * BB2TWeight,
9038 BBTWeight * BB1TWeight + BBFWeight * BB2FWeight};
9039 setFittedBranchWeights(*BI, Weights, /*IsExpected=*/false,
9040 /*ElideAllZero=*/true);
9041 }
9042 return true;
9043}
9044
9045bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
9046 assert(
9048 BI->getSuccessor(0) != BI->getSuccessor(1) &&
9049 "Tautological conditional branch should have been eliminated already.");
9050
9051 BasicBlock *BB = BI->getParent();
9052 if (!Options.SimplifyCondBranch ||
9053 BI->getFunction()->hasFnAttribute(Attribute::OptForFuzzing))
9054 return false;
9055
9056 // Conditional branch
9057 if (isValueEqualityComparison(BI)) {
9058 // If we only have one predecessor, and if it is a branch on this value,
9059 // see if that predecessor totally determines the outcome of this
9060 // switch.
9061 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
9062 if (simplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
9063 return requestResimplify();
9064
9065 // This block must be empty, except for the setcond inst, if it exists.
9066 // Ignore pseudo intrinsics.
9067 for (auto &I : *BB) {
9068 if (isa<PseudoProbeInst>(I) ||
9069 &I == cast<Instruction>(BI->getCondition()))
9070 continue;
9071 if (&I == BI)
9072 if (foldValueComparisonIntoPredecessors(BI, Builder))
9073 return requestResimplify();
9074 break;
9075 }
9076 }
9077
9078 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
9079 if (simplifyBranchOnICmpChain(BI, Builder, DL))
9080 return true;
9081
9082 // If this basic block has dominating predecessor blocks and the dominating
9083 // blocks' conditions imply BI's condition, we know the direction of BI.
9084 std::optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
9085 if (Imp) {
9086 // Turn this into a branch on constant.
9087 auto *OldCond = BI->getCondition();
9088 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
9089 : ConstantInt::getFalse(BB->getContext());
9090 BI->setCondition(TorF);
9092 return requestResimplify();
9093 }
9094
9095 // If this basic block is ONLY a compare and a branch, and if a predecessor
9096 // branches to us and one of our successors, fold the comparison into the
9097 // predecessor and use logical operations to pick the right destination.
9098 if (Options.SpeculateBlocks &&
9099 foldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, Options.AC,
9100 Options.BonusInstThreshold))
9101 return requestResimplify();
9102
9103 // We have a conditional branch to two blocks that are only reachable
9104 // from BI. We know that the condbr dominates the two blocks, so see if
9105 // there is any identical code in the "then" and "else" blocks. If so, we
9106 // can hoist it up to the branching block.
9107 if (BI->getSuccessor(0)->getSinglePredecessor()) {
9108 if (BI->getSuccessor(1)->getSinglePredecessor()) {
9109 if (HoistCommon &&
9110 hoistCommonCodeFromSuccessors(BI, !Options.HoistCommonInsts))
9111 return requestResimplify();
9112
9113 if (BI && Options.HoistLoadsStoresWithCondFaulting &&
9114 isProfitableToSpeculate(BI, std::nullopt, TTI)) {
9115 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
9116 auto CanSpeculateConditionalLoadsStores = [&]() {
9117 for (auto *Succ : successors(BB)) {
9118 for (Instruction &I : *Succ) {
9119 if (I.isTerminator()) {
9120 if (I.getNumSuccessors() > 1)
9121 return false;
9122 continue;
9123 } else if (!isSafeCheapLoadStore(&I, TTI) ||
9124 SpeculatedConditionalLoadsStores.size() ==
9126 return false;
9127 }
9128 SpeculatedConditionalLoadsStores.push_back(&I);
9129 }
9130 }
9131 return !SpeculatedConditionalLoadsStores.empty();
9132 };
9133
9134 if (CanSpeculateConditionalLoadsStores()) {
9135 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores,
9136 std::nullopt, nullptr);
9137 return requestResimplify();
9138 }
9139 }
9140 } else {
9141 // If Successor #1 has multiple preds, we may be able to conditionally
9142 // execute Successor #0 if it branches to Successor #1.
9143 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
9144 if (Succ0TI->getNumSuccessors() == 1 &&
9145 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
9146 if (speculativelyExecuteBB(BI, BI->getSuccessor(0)))
9147 return requestResimplify();
9148 }
9149 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
9150 // If Successor #0 has multiple preds, we may be able to conditionally
9151 // execute Successor #1 if it branches to Successor #0.
9152 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
9153 if (Succ1TI->getNumSuccessors() == 1 &&
9154 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
9155 if (speculativelyExecuteBB(BI, BI->getSuccessor(1)))
9156 return requestResimplify();
9157 }
9158
9159 // If this is a branch on something for which we know the constant value in
9160 // predecessors (e.g. a phi node in the current block), thread control
9161 // through this block.
9162 if (foldCondBranchOnValueKnownInPredecessor(BI))
9163 return requestResimplify();
9164
9165 // Scan predecessor blocks for conditional branches.
9166 for (BasicBlock *Pred : predecessors(BB))
9167 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator()))
9168 if (PBI != BI)
9169 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
9170 return requestResimplify();
9171
9172 // Look for diamond patterns.
9173 if (MergeCondStores)
9174 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
9175 if (CondBrInst *PBI = dyn_cast<CondBrInst>(PrevBB->getTerminator()))
9176 if (PBI != BI)
9177 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
9178 return requestResimplify();
9179
9180 // Look for nested conditional branches.
9181 if (mergeNestedCondBranch(BI, DTU))
9182 return requestResimplify();
9183
9184 return false;
9185}
9186
9187/// Check if passing a value to an instruction will cause undefined behavior.
9188static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
9189 assert(V->getType() == I->getType() && "Mismatched types");
9191 if (!C)
9192 return false;
9193
9194 if (I->use_empty())
9195 return false;
9196
9197 if (C->isNullValue() || isa<UndefValue>(C)) {
9198 // Find the first same-block use with a UB-triggering opcode, skipping
9199 // cross-block or before-I uses.
9200 auto FindUse = llvm::find_if(I->uses(), [I](auto &U) {
9201 auto *Use = cast<Instruction>(U.getUser());
9202 // Only same-block uses after I can witness UB at I's program point.
9203 // Self-uses and before-I uses can occur when I is a PHI node.
9204 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
9205 return false;
9206 // Change this list when we want to add new instructions.
9207 switch (Use->getOpcode()) {
9208 default:
9209 return false;
9210 case Instruction::GetElementPtr:
9211 case Instruction::Ret:
9212 case Instruction::BitCast:
9213 case Instruction::Load:
9214 case Instruction::Store:
9215 case Instruction::Call:
9216 case Instruction::CallBr:
9217 case Instruction::Invoke:
9218 case Instruction::UDiv:
9219 case Instruction::URem:
9220 // Note: signed div/rem of INT_MIN / -1 is also immediate UB, not
9221 // implemented to avoid code complexity as it is unclear how useful such
9222 // logic is.
9223 case Instruction::SDiv:
9224 case Instruction::SRem:
9225 return true;
9226 }
9227 });
9228 if (FindUse == I->use_end())
9229 return false;
9230 auto &Use = *FindUse;
9231 auto *User = cast<Instruction>(Use.getUser());
9232
9233 // Now make sure that there are no instructions in between that can alter
9234 // control flow (eg. calls)
9235 auto InstrRange =
9236 make_range(std::next(I->getIterator()), User->getIterator());
9237 if (any_of(InstrRange, [](Instruction &I) {
9239 }))
9240 return false;
9241
9242 // Look through GEPs. A load from a GEP derived from NULL is still undefined
9244 if (GEP->getPointerOperand() == I) {
9245 // The type of GEP may differ from the type of base pointer.
9246 // Bail out on vector GEPs, as they are not handled by other checks.
9247 if (GEP->getType()->isVectorTy())
9248 return false;
9249 // The current base address is null, there are four cases to consider:
9250 // getelementptr (TY, null, 0) -> null
9251 // getelementptr (TY, null, not zero) -> may be modified
9252 // getelementptr inbounds (TY, null, 0) -> null
9253 // getelementptr inbounds (TY, null, not zero) -> poison iff null is
9254 // undefined?
9255 if (!GEP->hasAllZeroIndices() &&
9256 (!GEP->isInBounds() ||
9257 NullPointerIsDefined(GEP->getFunction(),
9258 GEP->getPointerAddressSpace())))
9259 PtrValueMayBeModified = true;
9260 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
9261 }
9262
9263 // Look through return.
9264 if (ReturnInst *Ret = dyn_cast<ReturnInst>(User)) {
9265 bool HasNoUndefAttr =
9266 Ret->getFunction()->hasRetAttribute(Attribute::NoUndef);
9267 // Return undefined to a noundef return value is undefined.
9268 if (isa<UndefValue>(C) && HasNoUndefAttr)
9269 return true;
9270 // Return null to a nonnull+noundef return value is undefined.
9271 if (C->isNullValue() && HasNoUndefAttr &&
9272 Ret->getFunction()->hasRetAttribute(Attribute::NonNull)) {
9273 return !PtrValueMayBeModified;
9274 }
9275 }
9276
9277 // Load from null is undefined.
9278 if (LoadInst *LI = dyn_cast<LoadInst>(User))
9279 if (!LI->isVolatile())
9280 return !NullPointerIsDefined(LI->getFunction(),
9281 LI->getPointerAddressSpace());
9282
9283 // Store to null is undefined.
9285 if (!SI->isVolatile())
9286 return (!NullPointerIsDefined(SI->getFunction(),
9287 SI->getPointerAddressSpace())) &&
9288 SI->getPointerOperand() == I;
9289
9290 // llvm.assume(false/undef) always triggers immediate UB.
9291 if (auto *Assume = dyn_cast<AssumeInst>(User)) {
9292 // Ignore assume operand bundles.
9293 if (I == Assume->getArgOperand(0))
9294 return true;
9295 }
9296
9297 if (auto *CB = dyn_cast<CallBase>(User)) {
9298 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
9299 return false;
9300 // A call to null is undefined.
9301 if (CB->getCalledOperand() == I)
9302 return true;
9303
9304 if (CB->isArgOperand(&Use)) {
9305 unsigned ArgIdx = CB->getArgOperandNo(&Use);
9306 // Passing null to a nonnnull+noundef argument is undefined.
9307 if (isa<ConstantPointerNull>(C) && C->getType()->isPointerTy() &&
9308 CB->paramHasNonNullAttr(ArgIdx, /*AllowUndefOrPoison=*/false))
9309 return !PtrValueMayBeModified;
9310 // Passing undef to a noundef argument is undefined.
9311 if (isa<UndefValue>(C) && CB->isPassingUndefUB(ArgIdx))
9312 return true;
9313 }
9314 }
9315 // Div/Rem by zero is immediate UB
9316 if (match(User, m_BinOp(m_Value(), m_Specific(I))) && User->isIntDivRem())
9317 return true;
9318 }
9319 return false;
9320}
9321
9322/// If BB has an incoming value that will always trigger undefined behavior
9323/// (eg. null pointer dereference), remove the branch leading here.
9325 DomTreeUpdater *DTU,
9326 AssumptionCache *AC) {
9327 for (PHINode &PHI : BB->phis())
9328 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
9329 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
9330 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
9331 Instruction *T = Predecessor->getTerminator();
9332 IRBuilder<> Builder(T);
9333 if (isa<UncondBrInst>(T)) {
9334 BB->removePredecessor(Predecessor);
9335 // Turn unconditional branches into unreachables.
9336 Builder.CreateUnreachable();
9337 T->eraseFromParent();
9338 if (DTU)
9339 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9340 return true;
9341 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(T)) {
9342 BB->removePredecessor(Predecessor);
9343 // Handle degenerate conditional branches.
9344 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
9345 // The only difference from the UncondBrInst path above is that it
9346 // has two edges in CFG.
9347 BB->removePredecessor(Predecessor);
9348 // Turn unconditional branches into unreachables.
9349 Builder.CreateUnreachable();
9350 } else {
9351 // Preserve guarding condition in assume, because it might not be
9352 // inferrable from any dominating condition.
9353 Value *Cond = BI->getCondition();
9354 CallInst *Assumption;
9355 if (BI->getSuccessor(0) == BB)
9356 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
9357 else
9358 Assumption = Builder.CreateAssumption(Cond);
9359 if (AC)
9360 AC->registerAssumption(cast<AssumeInst>(Assumption));
9361 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
9362 : BI->getSuccessor(0));
9363 }
9364 BI->eraseFromParent();
9365 if (DTU)
9366 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9367 return true;
9368 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
9369 // Redirect all branches leading to UB into
9370 // a newly created unreachable block.
9371 BasicBlock *Unreachable = BasicBlock::Create(
9372 Predecessor->getContext(), "unreachable", BB->getParent(), BB);
9373 Builder.SetInsertPoint(Unreachable);
9374 // The new block contains only one instruction: Unreachable
9375 Builder.CreateUnreachable();
9376 for (const auto &Case : SI->cases())
9377 if (Case.getCaseSuccessor() == BB) {
9378 BB->removePredecessor(Predecessor);
9379 Case.setSuccessor(Unreachable);
9380 }
9381 if (SI->getDefaultDest() == BB) {
9382 BB->removePredecessor(Predecessor);
9383 SI->setDefaultDest(Unreachable);
9384 }
9385
9386 if (DTU)
9387 DTU->applyUpdates(
9388 { { DominatorTree::Insert, Predecessor, Unreachable },
9389 { DominatorTree::Delete, Predecessor, BB } });
9390 return true;
9391 }
9392 }
9393
9394 return false;
9395}
9396
9397bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
9398 bool Changed = false;
9399
9400 assert(BB && BB->getParent() && "Block not embedded in function!");
9401 assert(BB->hasTerminator() && "Degenerate basic block encountered!");
9402
9403 // Remove basic blocks that have no predecessors (except the entry block)...
9404 // or that just have themself as a predecessor. These are unreachable.
9405 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
9406 BB->getSinglePredecessor() == BB) {
9407 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
9408 DeleteDeadBlock(BB, DTU);
9409 return true;
9410 }
9411
9412 // Check to see if we can constant propagate this terminator instruction
9413 // away...
9414 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
9415 /*TLI=*/nullptr, DTU);
9416
9417 // Check for and eliminate duplicate PHI nodes in this block.
9419
9420 // Check for and remove branches that will always cause undefined behavior.
9422 return requestResimplify();
9423
9424 // Merge basic blocks into their predecessor if there is only one distinct
9425 // pred, and if there is only one distinct successor of the predecessor, and
9426 // if there are no PHI nodes.
9427 if (MergeBlockIntoPredecessor(BB, DTU))
9428 return true;
9429
9430 if (SinkCommon && Options.SinkCommonInsts) {
9431 if (sinkCommonCodeFromPredecessors(BB, DTU) ||
9432 mergeCompatibleInvokes(BB, DTU)) {
9433 // sinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
9434 // so we may now have duplicate PHI's.
9435 // Let's rerun EliminateDuplicatePHINodes() first,
9436 // before foldTwoEntryPHINode() potentially converts them into select's,
9437 // after which we'd need a whole EarlyCSE pass run to cleanup them.
9438 return true;
9439 }
9440 // Merge identical predecessors of this block.
9441 if (simplifyDuplicatePredecessors(BB, DTU))
9442 return true;
9443 }
9444
9445 if (Options.SpeculateBlocks &&
9446 !BB->getParent()->hasFnAttribute(Attribute::OptForFuzzing)) {
9447 // If there is a trivial two-entry PHI node in this basic block, and we can
9448 // eliminate it, do so now.
9449 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
9450 if (PN->getNumIncomingValues() == 2)
9451 if (foldTwoEntryPHINode(PN, TTI, DTU, Options.AC, DL,
9452 Options.SpeculateUnpredictables))
9453 return true;
9454 }
9455
9456 IRBuilder<> Builder(BB);
9458 Builder.SetInsertPoint(Terminator);
9459 switch (Terminator->getOpcode()) {
9460 case Instruction::UncondBr:
9461 Changed |= simplifyUncondBranch(cast<UncondBrInst>(Terminator), Builder);
9462 break;
9463 case Instruction::CondBr:
9464 Changed |= simplifyCondBranch(cast<CondBrInst>(Terminator), Builder);
9465 break;
9466 case Instruction::Resume:
9467 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
9468 break;
9469 case Instruction::CleanupRet:
9470 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
9471 break;
9472 case Instruction::Switch:
9473 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
9474 break;
9475 case Instruction::Unreachable:
9476 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
9477 break;
9478 case Instruction::IndirectBr:
9479 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
9480 break;
9481 }
9482
9483 return Changed;
9484}
9485
9486bool SimplifyCFGOpt::run(BasicBlock *BB) {
9487 bool Changed = false;
9488
9489 // Repeated simplify BB as long as resimplification is requested.
9490 do {
9491 Resimplify = false;
9492
9493 // Perform one round of simplifcation. Resimplify flag will be set if
9494 // another iteration is requested.
9495 Changed |= simplifyOnce(BB);
9496 } while (Resimplify);
9497
9498 return Changed;
9499}
9500
9503 ArrayRef<WeakVH> LoopHeaders) {
9504 return SimplifyCFGOpt(TTI, DTU, BB->getDataLayout(), LoopHeaders,
9505 Options)
9506 .run(BB);
9507}
#define Fail
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
static MachineBasicBlock * OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
@ Default
#define DEBUG_TYPE
Hexagon Common GEP
static bool IsIndirectCall(const MachineInstr *MI)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
This file contains the declarations for profiling metadata utility functions.
static cl::opt< uint32_t > SelectFalseWeight("profcheck-default-select-false-weight", cl::init(3U), cl::desc("When annotating `select` instructions, this value will be used " "for the second ('false') case."))
static cl::opt< uint32_t > SelectTrueWeight("profcheck-default-select-true-weight", cl::init(2U), cl::desc("When annotating `select` instructions, this value will be used " "for the first ('true') case."))
SmallVector< MachineOperand, 4 > Cond
int64_t C1
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:480
Provides some synthesis utilities to produce sequences of values.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
static std::optional< ContiguousCasesResult > findContiguousCases(Value *Condition, SmallVectorImpl< ConstantInt * > &Cases, SmallVectorImpl< ConstantInt * > &OtherCases, BasicBlock *Dest, BasicBlock *OtherDest)
static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, BasicBlock *ExistPred, MemorySSAUpdater *MSSAU=nullptr)
Update PHI nodes in Succ to indicate that there will now be entries in it from the 'NewPred' block.
static bool validLookupTableConstant(Constant *C, const TargetTransformInfo &TTI)
Return true if the backend will be able to handle initializing an array of constants like C.
static StoreInst * findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2)
static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize)
static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB, BasicBlock *EndBB, unsigned &SpeculatedInstructions, InstructionCost &Cost, const TargetTransformInfo &TTI)
Estimate the cost of the insertion(s) and check that the PHI nodes can be converted to selects.
static bool simplifySwitchLookup(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI, bool ConvertSwitchToLookupTable)
If the switch is only used to initialize one or more phi nodes in a common successor block with diffe...
static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI, Value *SelectValue, IRBuilder<> &Builder, DomTreeUpdater *DTU)
static bool valuesOverlap(std::vector< ValueEqualityComparisonCase > &C1, std::vector< ValueEqualityComparisonCase > &C2)
Return true if there are any keys in C1 that exist in C2 as well.
static bool isProfitableToSpeculate(const CondBrInst *BI, std::optional< bool > Invert, const TargetTransformInfo &TTI)
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeCleanupPad(CleanupReturnInst *RI)
static bool isVectorOp(Instruction &I)
Return if an instruction's type or any of its operands' types are a vector type.
static BasicBlock * allPredecessorsComeFromSameSource(BasicBlock *BB)
static void cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap)
static int constantIntSortPredicate(ConstantInt *const *P1, ConstantInt *const *P2)
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified=false)
Check if passing a value to an instruction will cause undefined behavior.
static std::optional< std::tuple< BasicBlock *, Instruction::BinaryOps, bool > > shouldFoldCondBranchesToCommonDestination(CondBrInst *BI, CondBrInst *PBI, const TargetTransformInfo *TTI)
Determine if the two branches share a common destination and deduce a glue that joins the branches' c...
static bool isSafeToHoistInstr(Instruction *I, unsigned Flags)
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
static ConstantInt * getConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
static bool simplifySwitchOfCmpIntrinsic(SwitchInst *SI, IRBuilderBase &Builder, DomTreeUpdater *DTU)
Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have the same destination.
static bool shouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, const TargetTransformInfo &TTI, const DataLayout &DL, const SmallVector< Type * > &ResultTypes)
Determine whether a lookup table should be built for this switch, based on the number of cases,...
static Constant * constantFold(Instruction *I, const DataLayout &DL, const SmallDenseMap< Value *, Constant * > &ConstantPool)
Try to fold instruction I into a constant.
static bool getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant * > > &Res, const DataLayout &DL)
Try to determine the resulting constant values in phi nodes at the common destination basic block,...
static bool areIdenticalUpToCommutativity(const Instruction *I1, const Instruction *I2)
static bool forwardSwitchConditionToPHI(SwitchInst *SI)
Try to forward the condition of a switch instruction to a phi node dominated by the switch,...
static PHINode * findPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
If BB would be eligible for simplification by TryToSimplifyUncondBranchFromEmptyBlock (i....
static bool reachesUncontrolledConvergentCallBeforeBlock(BasicBlock *From, BasicBlock *StopBB)
static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
Tries to transform switch of powers of two to reduce switch range.
static bool isCleanupBlockEmpty(iterator_range< BasicBlock::iterator > R)
static bool isSafeToThreadThroughLoopHeader(BasicBlock *Header, ArrayRef< BasicBlock * > PredBBs, BasicBlock *RealDest)
Return true if threading PredBBs through Header to RealDest eliminates the loop's single backedge.
static Value * ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, Value *AlternativeV=nullptr)
static Value * createLogicalOp(IRBuilderBase &Builder, Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="")
static void hoistConditionalLoadsStores(CondBrInst *BI, SmallVectorImpl< Instruction * > &SpeculatedConditionalLoadsStores, std::optional< bool > Invert, Instruction *Sel)
If the target supports conditional faulting, we look for the following pattern:
static bool shouldHoistCommonInstructions(Instruction *I1, Instruction *I2, const TargetTransformInfo &TTI)
Helper function for hoistCommonCodeFromSuccessors.
static bool reduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to transform a switch that has "holes" in it to a contiguous sequence of cases.
static bool safeToMergeTerminators(Instruction *SI1, Instruction *SI2, SmallSetVector< BasicBlock *, 4 > *FailBlocks=nullptr)
Return true if it is safe to merge these two terminator instructions together.
SkipFlags
@ SkipReadMem
@ SkipSideEffect
@ SkipImplicitControlFlow
static bool simplifySwitchDefaultBranch(SwitchInst *SI, DomTreeUpdater *DTU, const DataLayout &DL, AssumptionCache *AC)
static bool incomingValuesAreCompatible(BasicBlock *BB, ArrayRef< BasicBlock * > IncomingBlocks, SmallPtrSetImpl< Value * > *EquivalenceSet=nullptr)
Return true if all the PHI nodes in the basic block BB receive compatible (identical) incoming values...
static void createUnreachableSwitchDefault(SwitchInst *Switch, DomTreeUpdater *DTU, bool RemoveOrigDefaultBlock=true)
static Value * foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector, Constant *DefaultResult, Value *Condition, IRBuilder<> &Builder, const DataLayout &DL, ArrayRef< uint32_t > BranchWeights)
static bool sinkCommonCodeFromPredecessors(BasicBlock *BB, DomTreeUpdater *DTU)
Check whether BB's predecessors end with unconditional branches.
static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI, const DataLayout &DL)
static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL)
Compute masked bits for the condition of a switch and use it to remove dead cases.
static bool blockIsSimpleEnoughToThreadThrough(BasicBlock *BB, BlocksSet &NonLocalUseBlocks)
Return true if we can thread a branch across this block.
static bool foldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL, bool SpeculateUnpredictables)
Given a BB that starts with the specified two-entry PHI node, see if we can eliminate it.
static bool findReaching(BasicBlock *BB, BasicBlock *DefBB, BlocksSet &ReachesNonLocalUses)
static bool extractPredSuccWeights(CondBrInst *PBI, CondBrInst *BI, uint64_t &PredTrueWeight, uint64_t &PredFalseWeight, uint64_t &SuccTrueWeight, uint64_t &SuccFalseWeight)
Return true if either PBI or BI has branch weight available, and store the weights in {Pred|Succ}...
static bool shouldUseSwitchConditionAsTableIndex(ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal, bool HasDefaultResults, const SmallVector< Type * > &ResultTypes, const DataLayout &DL, const TargetTransformInfo &TTI)
static InstructionCost computeSpeculationCost(const User *I, const TargetTransformInfo &TTI)
Compute an abstract "cost" of speculating the given instruction, which is assumed to be safe to specu...
static bool performBranchToCommonDestFolding(CondBrInst *BI, CondBrInst *PBI, DomTreeUpdater *DTU, MemorySSAUpdater *MSSAU, const TargetTransformInfo *TTI)
static std::optional< unsigned > getDenseSwitchRangeReductionShift(ArrayRef< int64_t > Values, int64_t Base, bool OptSize)
SmallPtrSet< BasicBlock *, 8 > BlocksSet
static unsigned skippedInstrFlags(Instruction *I)
static bool mergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU)
If this block is a landingpad exception handling block, categorize all the predecessor invokes into s...
static bool replacingOperandWithVariableIsCheap(const Instruction *I, int OpIdx)
static void eraseTerminatorAndDCECond(Instruction *TI, MemorySSAUpdater *MSSAU=nullptr)
static void eliminateBlockCases(BasicBlock *BB, std::vector< ValueEqualityComparisonCase > &Cases)
Given a vector of bb/value pairs, remove any entries in the list that match the specified block.
static bool mergeConditionalStores(CondBrInst *PBI, CondBrInst *QBI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeNestedCondBranch(CondBrInst *BI, DomTreeUpdater *DTU)
Fold the following pattern: bb0: br i1 cond1, label bb1, label bb2 bb1: br i1 cond2,...
static void sinkLastInstruction(ArrayRef< BasicBlock * > Blocks)
static size_t mapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
static bool tryWidenCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU)
If the previous block ended with a widenable branch, determine if reusing the target block is profita...
static void mergeCompatibleInvokesImpl(ArrayRef< InvokeInst * > Invokes, DomTreeUpdater *DTU)
static bool mergeIdenticalBBs(ArrayRef< BasicBlock * > Candidates, DomTreeUpdater *DTU)
static void getBranchWeights(Instruction *TI, SmallVectorImpl< uint64_t > &Weights)
Get Weights of a given terminator, the default weight is at the front of the vector.
static bool tryToMergeLandingPad(LandingPadInst *LPad, UncondBrInst *BI, BasicBlock *BB, DomTreeUpdater *DTU)
Given an block with only a single landing pad and a unconditional branch try to find another basic bl...
static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, uintptr_t MaxUniqueResults)
static Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB, Instruction *&PreviousAccess)
Determine if we can hoist sink a sole store instruction out of a conditional block.
static Constant * lookupConstant(Value *V, const SmallDenseMap< Value *, Constant * > &ConstantPool)
If V is a Constant, return it.
static bool SimplifyCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
If we have a conditional branch as a predecessor of another block, this function tries to simplify it...
static bool canSinkInstructions(ArrayRef< Instruction * > Insts, DenseMap< const Use *, SmallVector< Value *, 4 > > &PHIOperands)
static void hoistLockstepIdenticalDbgVariableRecords(Instruction *TI, Instruction *I1, SmallVectorImpl< Instruction * > &OtherInsts)
Hoists DbgVariableRecords from I1 and OtherInstrs that are identical in lock-step to TI.
static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU)
static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL)
If a switch is only used to initialize one or more phi nodes in a common successor block with only tw...
static bool removeUndefIntroducingPredecessor(BasicBlock *BB, DomTreeUpdater *DTU, AssumptionCache *AC)
If BB has an incoming value that will always trigger undefined behavior (eg.
static bool isUncontrolledConvergentCall(CallBase *CB)
static bool simplifySwitchWhenUMin(SwitchInst *SI, DomTreeUpdater *DTU)
Tries to transform the switch when the condition is umin with a constant.
static bool isSafeCheapLoadStore(const Instruction *I, const TargetTransformInfo &TTI)
static ConstantInt * getKnownValueOnEdge(Value *V, BasicBlock *From, BasicBlock *To)
static std::optional< bool > foldCondBranchOnValueKnownInPredecessorImpl(CondBrInst *BI, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL, bool KeepCanonicalLoop)
If we have a conditional branch on something for which we know the constant value in predecessors (e....
static bool dominatesMergePoint(Value *V, BasicBlock *BB, Instruction *InsertPt, SmallPtrSetImpl< Instruction * > &AggressiveInsts, InstructionCost &Cost, InstructionCost Budget, const TargetTransformInfo &TTI, AssumptionCache *AC, SmallPtrSetImpl< Instruction * > &ZeroCostInstructions, unsigned Depth=0)
If we have a merge point of an "if condition" as accepted above, return true if the specified value d...
static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch, Constant *DefaultValue, const SmallVectorImpl< std::pair< ConstantInt *, Constant * > > &Values)
Try to reuse the switch table index compare.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1594
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:463
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:461
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:638
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
BranchProbability getCompl() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void addRangeRetAttr(const ConstantRange &CR)
adds the range attribute to the list of attributes.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
bool isConvergent() const
Determine if the invoke is convergent.
Value * getConvergenceControlToken() const
Return the convergence control token for this call, if it exists.
bool isDataOperand(const Use *U) const
bool tryIntersectAttributes(const CallBase *Other)
Try to intersect the attributes from 'this' CallBase and the 'Other' CallBase.
This class represents a function call, abstracting a target machine's calling convention.
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
CleanupPadInst * getCleanupPad() const
Convenience accessor.
BasicBlock * getUnwindDest() const
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
ConstantFolder - Create constants with minimum, target independent, folding.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isNegative() const
Definition Constants.h:214
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
IntegerType * getIntegerType() const
Variant of the getType() method to always return an IntegerType, which reduces the amount of casting ...
Definition Constants.h:198
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A constant pointer value that points to null.
Definition Constants.h:716
This class represents a range of values.
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool isUpperWrapped() const
Return true if the exclusive upper bound wraps around the unsigned domain.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:83
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
simple_ilist< DbgRecord >::iterator self_iterator
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
bool isSameSourceLocation(const DebugLoc &Other) const
Return true if the source locations match, ignoring isImplicitCode and source atom info.
Definition DebugLoc.h:250
static DebugLoc getTemporary()
Definition DebugLoc.h:152
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:186
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:173
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2398
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1212
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:445
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:176
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2735
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:228
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1528
LLVM_ABI CallInst * CreateAssumption(Value *Cond)
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1206
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1850
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Definition IRBuilder.h:1235
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2382
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1907
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2121
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1418
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:450
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2107
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2323
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2492
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1452
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
Indirect Branch Instruction.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
LLVM_ABI void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
LLVM_ABI void dropLocation()
Drop the instruction's debug location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY
Return true if there are any uses of this instruction in blocks other than the specified block.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
@ CompareUsingIntersectedAttrs
Check for equivalence with intersected callbase attrs.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
LLVM_ABI void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Invoke instruction.
void setNormalDest(BasicBlock *B)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
The landingpad instruction holds all of the information necessary to generate correct exception handl...
An instruction for reading from memory.
static unsigned getPointerOperandIndex()
Iterates through instructions in a set of blocks in reverse order from the first non-terminator.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1081
Helper class to manipulate !mmra metadata nodes.
bool empty() const
Definition MapVector.h:79
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
size_type size() const
Definition MapVector.h:58
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getValue() const
Convenience accessor.
Return a value (possibly void), from a function.
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Align getAlign() const
bool isSimple() const
Value * getValueOperand()
bool isUnordered() const
static unsigned getPointerOperandIndex()
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
Value * getPointerOperand()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
LLVM_ABI void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
LLVM_ABI CaseWeightOpt getSuccessorWeight(unsigned idx)
LLVM_ABI void replaceDefaultDest(SwitchInst::CaseIt I)
Replace the default destination by given case.
std::optional< uint32_t > CaseWeightOpt
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
Multiway switch.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
BasicBlock * getSuccessor(unsigned idx) const
void setCondition(Value *V)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
CaseIteratorImpl< CaseHandle > CaseIt
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
unsigned getNumSuccessors() const
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
void setSuccessor(BasicBlock *NewSucc)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static constexpr uint64_t MaximumAlignment
Definition Value.h:801
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:50
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:143
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Represents an op.with.overflow intrinsic.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A range adaptor for a pair of iterators.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
LLVM_ABI bool foldBranchToCommonDest(CondBrInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=nullptr, AssumptionCache *AC=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
static cl::opt< unsigned > MaxLoopHeaderThreadingSearchBlocks("simplifycfg-max-loop-header-threading-search", cl::Hidden, cl::init(1024), cl::desc("Limit number of blocks searched to prove that threading through " "a loop header keeps the loop canonical"))
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
static cl::opt< unsigned > MaxSwitchCasesPerResult("max-switch-cases-per-result", cl::Hidden, cl::init(16), cl::desc("Limit cases to analyze when converting a switch to select"))
InstructionCost Cost
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
static cl::opt< bool > SpeculateOneExpensiveInst("speculate-one-expensive-inst", cl::Hidden, cl::init(true), cl::desc("Allow exactly one expensive instruction to be speculatively " "executed"))
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
auto pred_end(const MachineBasicBlock *BB)
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
auto accumulate(R &&Range, E &&Init)
Wrapper for std::accumulate.
Definition STLExtras.h:1718
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
static cl::opt< unsigned > MaxSpeculationDepth("max-speculation-depth", cl::Hidden, cl::init(10), cl::desc("Limit maximum recursion depth when calculating costs of " "speculatively executed instructions"))
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
static cl::opt< unsigned > PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), cl::desc("Control the amount of phi node folding to perform (default = 2)"))
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
static cl::opt< bool > MergeCondStoresAggressively("simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), cl::desc("When merging conditional stores, do so even if the resultant " "basic blocks are unlikely to be if-converted as a result"))
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
static cl::opt< unsigned > BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden, cl::init(2), cl::desc("Maximum cost of combining conditions when " "folding branches"))
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
static cl::opt< bool > SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), cl::desc("Sink common instructions down to the end block"))
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
static cl::opt< bool > HoistStoresWithCondFaulting("simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist stores if the target supports conditional faulting"))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr detail::StaticCastFunc< To > StaticCastTo
Function objects corresponding to the Cast types defined above.
Definition Casting.h:882
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI CondBrInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition Local.cpp:1147
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
LLVM_ABI void InvertBranch(CondBrInst *PBI, IRBuilderBase &Builder)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
static cl::opt< bool > EnableMergeCompatibleInvokes("simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true), cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"))
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition Local.cpp:2876
auto succ_size(const MachineBasicBlock *BB)
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static cl::opt< unsigned > MaxJumpThreadingLiveBlocks("max-jump-threading-live-blocks", cl::Hidden, cl::init(24), cl::desc("Limit number of blocks a define in a threaded block is allowed " "to be live in"))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3129
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
static cl::opt< int > MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden, cl::init(10), cl::desc("Max size of a block which is still considered " "small enough to thread through"))
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
LLVM_ABI bool isWidenableBranch(const User *U)
Returns true iff U is a widenable branch (that is, extractWidenableCondition returns widenable condit...
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
static cl::opt< unsigned > HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden, cl::init(20), cl::desc("Allow reordering across at most this many " "instructions when hoisting"))
LLVM_ABI cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
static cl::opt< bool > MergeCondStores("simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores even if an unconditional store does not " "precede - hoist multiple conditional stores into a single " "predicated store"))
static cl::opt< unsigned > BranchFoldToCommonDestVectorMultiplier("simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden, cl::init(2), cl::desc("Multiplier to apply to threshold when determining whether or not " "to fold branch to common destination when vector operations are " "present"))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
Definition Local.cpp:3409
@ Sub
Subtraction of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
IntPtrTy
Definition InstrProf.h:82
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3915
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
void RemapDbgRecord(Module *M, DbgRecord *DR, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecord DR using the value map VM.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
static cl::opt< bool > HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores if an unconditional store precedes"))
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
static cl::opt< unsigned > HoistLoadsStoresWithCondFaultingThreshold("hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6), cl::desc("Control the maximal conditional load/store that we are willing " "to speculatively execute to eliminate conditional branch " "(default = 6)"))
static cl::opt< bool > HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true), cl::desc("Hoist common instructions up to the parent block"))
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static cl::opt< unsigned > TwoEntryPHINodeFoldingThreshold("two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4), cl::desc("Control the maximal total instruction cost that we are willing " "to speculatively execute to fold a 2-entry PHI node into a " "select (default = 4)"))
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
SmallVector< uint64_t, 2 > getDisjunctionWeights(const SmallVector< T1, 2 > &B1, const SmallVector< T2, 2 > &B2)
Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2 are 2 booleans that are t...
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:266
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
static cl::opt< bool > HoistLoadsWithCondFaulting("simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist loads if the target supports conditional faulting"))
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1503
@ Keep
No function return thunk.
Definition CodeGen.h:370
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
SmallVectorImpl< ConstantInt * > * Cases
SmallVectorImpl< ConstantInt * > * OtherCases
Checking whether two BBs are equal depends on the contents of the BasicBlock and the incoming values ...
SmallDenseMap< BasicBlock *, Value *, 8 > BB2ValueMap
Phi2IVsMap * PhiPredIVs
DenseMap< PHINode *, BB2ValueMap > Phi2IVsMap
static bool canBeMerged(const BasicBlock *BB)
BasicBlock * BB
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS)
static unsigned getHashValue(const EqualBBWrapper *EBW)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342