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 <cmath>
84#include <cstddef>
85#include <cstdint>
86#include <iterator>
87#include <map>
88#include <optional>
89#include <set>
90#include <tuple>
91#include <utility>
92#include <vector>
93
94using namespace llvm;
95using namespace PatternMatch;
96
97#define DEBUG_TYPE "simplifycfg"
98
99namespace llvm {
100
102 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
103
104 cl::desc(
105 "Temporary development switch used to gradually uplift SimplifyCFG "
106 "into preserving DomTree,"));
107
108// Chosen as 2 so as to be cheap, but still to have enough power to fold
109// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
110// To catch this, we need to fold a compare and a select, hence '2' being the
111// minimum reasonable default.
113 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
114 cl::desc(
115 "Control the amount of phi node folding to perform (default = 2)"));
116
118 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
119 cl::desc("Control the maximal total instruction cost that we are willing "
120 "to speculatively execute to fold a 2-entry PHI node into a "
121 "select (default = 4)"));
122
123static cl::opt<bool>
124 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
125 cl::desc("Hoist common instructions up to the parent block"));
126
128 "simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true),
129 cl::desc("Hoist loads if the target supports conditional faulting"));
130
132 "simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true),
133 cl::desc("Hoist stores if the target supports conditional faulting"));
134
136 "hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6),
137 cl::desc("Control the maximal conditional load/store that we are willing "
138 "to speculatively execute to eliminate conditional branch "
139 "(default = 6)"));
140
142 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
143 cl::init(20),
144 cl::desc("Allow reordering across at most this many "
145 "instructions when hoisting"));
146
147static cl::opt<bool>
148 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
149 cl::desc("Sink common instructions down to the end block"));
150
152 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
153 cl::desc("Hoist conditional stores if an unconditional store precedes"));
154
156 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
157 cl::desc("Hoist conditional stores even if an unconditional store does not "
158 "precede - hoist multiple conditional stores into a single "
159 "predicated store"));
160
162 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
163 cl::desc("When merging conditional stores, do so even if the resultant "
164 "basic blocks are unlikely to be if-converted as a result"));
165
167 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
168 cl::desc("Allow exactly one expensive instruction to be speculatively "
169 "executed"));
170
172 "max-speculation-depth", cl::Hidden, cl::init(10),
173 cl::desc("Limit maximum recursion depth when calculating costs of "
174 "speculatively executed instructions"));
175
176static cl::opt<int>
177 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
178 cl::init(10),
179 cl::desc("Max size of a block which is still considered "
180 "small enough to thread through"));
181
182// Two is chosen to allow one negation and a logical combine.
184 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
185 cl::init(2),
186 cl::desc("Maximum cost of combining conditions when "
187 "folding branches"));
188
190 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
191 cl::init(2),
192 cl::desc("Multiplier to apply to threshold when determining whether or not "
193 "to fold branch to common destination when vector operations are "
194 "present"));
195
197 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
198 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
199
201 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
202 cl::desc("Limit cases to analyze when converting a switch to select"));
203
205 "max-jump-threading-live-blocks", cl::Hidden, cl::init(24),
206 cl::desc("Limit number of blocks a define in a threaded block is allowed "
207 "to be live in"));
208
210
211} // end namespace llvm
212
213STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
214STATISTIC(NumLinearMaps,
215 "Number of switch instructions turned into linear mapping");
216STATISTIC(NumLookupTables,
217 "Number of switch instructions turned into lookup tables");
219 NumLookupTablesHoles,
220 "Number of switch instructions turned into lookup tables (holes checked)");
221STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
222STATISTIC(NumFoldValueComparisonIntoPredecessors,
223 "Number of value comparisons folded into predecessor basic blocks");
224STATISTIC(NumFoldBranchToCommonDest,
225 "Number of branches folded into predecessor basic block");
227 NumHoistCommonCode,
228 "Number of common instruction 'blocks' hoisted up to the begin block");
229STATISTIC(NumHoistCommonInstrs,
230 "Number of common instructions hoisted up to the begin block");
231STATISTIC(NumSinkCommonCode,
232 "Number of common instruction 'blocks' sunk down to the end block");
233STATISTIC(NumSinkCommonInstrs,
234 "Number of common instructions sunk down to the end block");
235STATISTIC(NumSpeculations, "Number of speculative executed instructions");
236STATISTIC(NumInvokes,
237 "Number of invokes with empty resume blocks simplified into calls");
238STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
239STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
240
241namespace {
242
243// The first field contains the value that the switch produces when a certain
244// case group is selected, and the second field is a vector containing the
245// cases composing the case group.
246using SwitchCaseResultVectorTy =
248
249// The first field contains the phi node that generates a result of the switch
250// and the second field contains the value generated for a certain case in the
251// switch for that PHI.
252using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
253
254/// ValueEqualityComparisonCase - Represents a case of a switch.
255struct ValueEqualityComparisonCase {
257 BasicBlock *Dest;
258
259 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
260 : Value(Value), Dest(Dest) {}
261
262 bool operator<(ValueEqualityComparisonCase RHS) const {
263 // Comparing pointers is ok as we only rely on the order for uniquing.
264 return Value < RHS.Value;
265 }
266
267 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
268};
269
270class SimplifyCFGOpt {
271 const TargetTransformInfo &TTI;
272 DomTreeUpdater *DTU;
273 const DataLayout &DL;
274 ArrayRef<WeakVH> LoopHeaders;
275 const SimplifyCFGOptions &Options;
276 bool Resimplify;
277
278 Value *isValueEqualityComparison(Instruction *TI);
279 BasicBlock *getValueEqualityComparisonCases(
280 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
281 bool simplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
282 BasicBlock *Pred,
283 IRBuilder<> &Builder);
284 bool performValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
285 Instruction *PTI,
286 IRBuilder<> &Builder);
287 bool foldValueComparisonIntoPredecessors(Instruction *TI,
288 IRBuilder<> &Builder);
289
290 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
291 bool simplifySingleResume(ResumeInst *RI);
292 bool simplifyCommonResume(ResumeInst *RI);
293 bool simplifyCleanupReturn(CleanupReturnInst *RI);
294 bool simplifyUnreachable(UnreachableInst *UI);
295 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
296 bool simplifyDuplicateSwitchArms(SwitchInst *SI, DomTreeUpdater *DTU);
297 bool simplifyIndirectBr(IndirectBrInst *IBI);
298 bool simplifyUncondBranch(UncondBrInst *BI, IRBuilder<> &Builder);
299 bool simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder);
300 bool foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI);
301
302 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
303 IRBuilder<> &Builder);
304 bool tryToSimplifyUncondBranchWithICmpSelectInIt(ICmpInst *ICI,
305 SelectInst *Select,
306 IRBuilder<> &Builder);
307 bool hoistCommonCodeFromSuccessors(Instruction *TI, bool AllInstsEqOnly);
308 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
309 Instruction *TI, Instruction *I1,
310 SmallVectorImpl<Instruction *> &OtherSuccTIs,
311 ArrayRef<BasicBlock *> UniqueSuccessors);
312 bool speculativelyExecuteBB(CondBrInst *BI, BasicBlock *ThenBB);
313 bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
314 BasicBlock *TrueBB, BasicBlock *FalseBB,
315 uint32_t TrueWeight, uint32_t FalseWeight);
316 bool simplifyBranchOnICmpChain(CondBrInst *BI, IRBuilder<> &Builder,
317 const DataLayout &DL);
318 bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
319 bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
320 bool turnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
321 bool simplifyDuplicatePredecessors(BasicBlock *Succ, DomTreeUpdater *DTU);
322
323public:
324 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
325 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
326 const SimplifyCFGOptions &Opts)
327 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
328 assert((!DTU || !DTU->hasPostDomTree()) &&
329 "SimplifyCFG is not yet capable of maintaining validity of a "
330 "PostDomTree, so don't ask for it.");
331 }
332
333 bool simplifyOnce(BasicBlock *BB);
334 bool run(BasicBlock *BB);
335
336 // Helper to set Resimplify and return change indication.
337 bool requestResimplify() {
338 Resimplify = true;
339 return true;
340 }
341};
342
343// we synthesize a || b as select a, true, b
344// we synthesize a && b as select a, b, false
345// this function determines if SI is playing one of those roles.
346[[maybe_unused]] bool
347isSelectInRoleOfConjunctionOrDisjunction(const SelectInst *SI) {
348 return ((isa<ConstantInt>(SI->getTrueValue()) &&
349 (dyn_cast<ConstantInt>(SI->getTrueValue())->isOne())) ||
350 (isa<ConstantInt>(SI->getFalseValue()) &&
351 (dyn_cast<ConstantInt>(SI->getFalseValue())->isNullValue())));
352}
353
354} // end anonymous namespace
355
356/// Return true if all the PHI nodes in the basic block \p BB
357/// receive compatible (identical) incoming values when coming from
358/// all of the predecessor blocks that are specified in \p IncomingBlocks.
359///
360/// Note that if the values aren't exactly identical, but \p EquivalenceSet
361/// is provided, and *both* of the values are present in the set,
362/// then they are considered equal.
364 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
365 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
366 assert(IncomingBlocks.size() == 2 &&
367 "Only for a pair of incoming blocks at the time!");
368
369 // FIXME: it is okay if one of the incoming values is an `undef` value,
370 // iff the other incoming value is guaranteed to be a non-poison value.
371 // FIXME: it is okay if one of the incoming values is a `poison` value.
372 return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
373 Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
374 Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
375 if (IV0 == IV1)
376 return true;
377 if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
378 EquivalenceSet->contains(IV1))
379 return true;
380 return false;
381 });
382}
383
384/// Return true if it is safe to merge these two
385/// terminator instructions together.
386static bool
388 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
389 if (SI1 == SI2)
390 return false; // Can't merge with self!
391
392 // It is not safe to merge these two switch instructions if they have a common
393 // successor, and if that successor has a PHI node, and if *that* PHI node has
394 // conflicting incoming values from the two switch blocks.
395 BasicBlock *SI1BB = SI1->getParent();
396 BasicBlock *SI2BB = SI2->getParent();
397
399 bool Fail = false;
400 for (BasicBlock *Succ : successors(SI2BB)) {
401 if (!SI1Succs.count(Succ))
402 continue;
403 if (incomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
404 continue;
405 Fail = true;
406 if (FailBlocks)
407 FailBlocks->insert(Succ);
408 else
409 break;
410 }
411
412 return !Fail;
413}
414
415/// Update PHI nodes in Succ to indicate that there will now be entries in it
416/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
417/// will be the same as those coming in from ExistPred, an existing predecessor
418/// of Succ.
419static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
420 BasicBlock *ExistPred,
421 MemorySSAUpdater *MSSAU = nullptr) {
422 for (PHINode &PN : Succ->phis())
423 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
424 if (MSSAU)
425 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
426 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
427}
428
429/// Compute an abstract "cost" of speculating the given instruction,
430/// which is assumed to be safe to speculate. TCC_Free means cheap,
431/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
432/// expensive.
434 const TargetTransformInfo &TTI) {
435 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
436}
437
438/// If we have a merge point of an "if condition" as accepted above,
439/// return true if the specified value dominates the block. We don't handle
440/// the true generality of domination here, just a special case which works
441/// well enough for us.
442///
443/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
444/// see if V (which must be an instruction) and its recursive operands
445/// that do not dominate BB have a combined cost lower than Budget and
446/// are non-trapping. If both are true, the instruction is inserted into the
447/// set and true is returned.
448///
449/// The cost for most non-trapping instructions is defined as 1 except for
450/// Select whose cost is 2.
451///
452/// After this function returns, Cost is increased by the cost of
453/// V plus its non-dominating operands. If that cost is greater than
454/// Budget, false is returned and Cost is undefined.
456 Value *V, BasicBlock *BB, Instruction *InsertPt,
457 SmallPtrSetImpl<Instruction *> &AggressiveInsts, InstructionCost &Cost,
459 SmallPtrSetImpl<Instruction *> &ZeroCostInstructions, unsigned Depth = 0) {
460 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
461 // so limit the recursion depth.
462 // TODO: While this recursion limit does prevent pathological behavior, it
463 // would be better to track visited instructions to avoid cycles.
465 return false;
466
468 if (!I) {
469 // Non-instructions dominate all instructions and can be executed
470 // unconditionally.
471 return true;
472 }
473 BasicBlock *PBB = I->getParent();
474
475 // We don't want to allow weird loops that might have the "if condition" in
476 // the bottom of this block.
477 if (PBB == BB)
478 return false;
479
480 // If this instruction is defined in a block that contains an unconditional
481 // branch to BB, then it must be in the 'conditional' part of the "if
482 // statement". If not, it definitely dominates the region.
484 if (!BI || BI->getSuccessor() != BB)
485 return true;
486
487 // If we have seen this instruction before, don't count it again.
488 if (AggressiveInsts.count(I))
489 return true;
490
491 // Okay, it looks like the instruction IS in the "condition". Check to
492 // see if it's a cheap instruction to unconditionally compute, and if it
493 // only uses stuff defined outside of the condition. If so, hoist it out.
494 if (!isSafeToSpeculativelyExecute(I, InsertPt, AC))
495 return false;
496
497 // Overflow arithmetic instruction plus extract value are usually generated
498 // when a division is being replaced. But, in this case, the zero check may
499 // still be kept in the code. In that case it would be worth to hoist these
500 // two instruction out of the basic block. Let's treat this pattern as one
501 // single cheap instruction here!
502 WithOverflowInst *OverflowInst;
503 if (match(I, m_ExtractValue<1>(m_OneUse(m_WithOverflowInst(OverflowInst))))) {
504 ZeroCostInstructions.insert(OverflowInst);
505 Cost += 1;
506 } else if (!ZeroCostInstructions.contains(I))
507 Cost += computeSpeculationCost(I, TTI);
508
509 // Allow exactly one instruction to be speculated regardless of its cost
510 // (as long as it is safe to do so).
511 // This is intended to flatten the CFG even if the instruction is a division
512 // or other expensive operation. The speculation of an expensive instruction
513 // is expected to be undone in CodeGenPrepare if the speculation has not
514 // enabled further IR optimizations.
515 if (Cost > Budget &&
516 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
517 !Cost.isValid()))
518 return false;
519
520 // Okay, we can only really hoist these out if their operands do
521 // not take us over the cost threshold.
522 for (Use &Op : I->operands())
523 if (!dominatesMergePoint(Op, BB, InsertPt, AggressiveInsts, Cost, Budget,
524 TTI, AC, ZeroCostInstructions, Depth + 1))
525 return false;
526 // Okay, it's safe to do this! Remember this instruction.
527 AggressiveInsts.insert(I);
528 return true;
529}
530
531/// Extract ConstantInt from value, looking through IntToPtr
532/// and PointerNullValue. Return NULL if value is not a constant int.
534 // Normal constant int.
536 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
537 return CI;
538
539 // It is not safe to look through inttoptr or ptrtoint when using unstable
540 // pointer types.
541 if (DL.hasUnstableRepresentation(V->getType()))
542 return nullptr;
543
544 // This is some kind of pointer constant. Turn it into a pointer-sized
545 // ConstantInt if possible.
546 IntegerType *IntPtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
547
548 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
550 return ConstantInt::get(IntPtrTy, 0);
551
552 // IntToPtr const int, we can look through this if the semantics of
553 // inttoptr for this address space are a simple (truncating) bitcast.
555 if (CE->getOpcode() == Instruction::IntToPtr)
556 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
557 // The constant is very likely to have the right type already.
558 if (CI->getType() == IntPtrTy)
559 return CI;
560 else
561 return cast<ConstantInt>(
562 ConstantFoldIntegerCast(CI, IntPtrTy, /*isSigned=*/false, DL));
563 }
564 return nullptr;
565}
566
567namespace {
568
569/// Given a chain of or (||) or and (&&) comparison of a value against a
570/// constant, this will try to recover the information required for a switch
571/// structure.
572/// It will depth-first traverse the chain of comparison, seeking for patterns
573/// like %a == 12 or %a < 4 and combine them to produce a set of integer
574/// representing the different cases for the switch.
575/// Note that if the chain is composed of '||' it will build the set of elements
576/// that matches the comparisons (i.e. any of this value validate the chain)
577/// while for a chain of '&&' it will build the set elements that make the test
578/// fail.
579struct ConstantComparesGatherer {
580 const DataLayout &DL;
581
582 /// Value found for the switch comparison
583 Value *CompValue = nullptr;
584
585 /// Extra clause to be checked before the switch
586 Value *Extra = nullptr;
587
588 /// Set of integers to match in switch
590
591 /// Number of comparisons matched in the and/or chain
592 unsigned UsedICmps = 0;
593
594 /// If the elements in Vals matches the comparisons
595 bool IsEq = false;
596
597 // Used to check if the first matched CompValue shall be the Extra check.
598 bool IgnoreFirstMatch = false;
599 bool MultipleMatches = false;
600
601 /// Construct and compute the result for the comparison instruction Cond
602 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
603 gather(Cond);
604 if (CompValue || !MultipleMatches)
605 return;
606 Extra = nullptr;
607 Vals.clear();
608 UsedICmps = 0;
609 IgnoreFirstMatch = true;
610 gather(Cond);
611 }
612
613 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
614 ConstantComparesGatherer &
615 operator=(const ConstantComparesGatherer &) = delete;
616
617private:
618 /// Try to set the current value used for the comparison, it succeeds only if
619 /// it wasn't set before or if the new value is the same as the old one
620 bool setValueOnce(Value *NewVal) {
621 if (IgnoreFirstMatch) {
622 IgnoreFirstMatch = false;
623 return false;
624 }
625 if (CompValue && CompValue != NewVal) {
626 MultipleMatches = true;
627 return false;
628 }
629 CompValue = NewVal;
630 return true;
631 }
632
633 /// Try to match Instruction "I" as a comparison against a constant and
634 /// populates the array Vals with the set of values that match (or do not
635 /// match depending on isEQ).
636 /// Return false on failure. On success, the Value the comparison matched
637 /// against is placed in CompValue.
638 /// If CompValue is already set, the function is expected to fail if a match
639 /// is found but the value compared to is different.
640 bool matchInstruction(Instruction *I, bool isEQ) {
641 if (match(I, m_Not(m_Instruction(I))))
642 isEQ = !isEQ;
643
644 Value *Val;
645 if (match(I, m_NUWTrunc(m_Value(Val)))) {
646 // If we already have a value for the switch, it has to match!
647 if (!setValueOnce(Val))
648 return false;
649 UsedICmps++;
650 Vals.push_back(ConstantInt::get(cast<IntegerType>(Val->getType()), isEQ));
651 return true;
652 }
653 // If this is an icmp against a constant, handle this as one of the cases.
654 ICmpInst *ICI;
655 ConstantInt *C;
656 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
657 (C = getConstantInt(I->getOperand(1), DL)))) {
658 return false;
659 }
660
661 Value *RHSVal;
662 const APInt *RHSC;
663
664 // Pattern match a special case
665 // (x & ~2^z) == y --> x == y || x == y|2^z
666 // This undoes a transformation done by instcombine to fuse 2 compares.
667 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
668 // It's a little bit hard to see why the following transformations are
669 // correct. Here is a CVC3 program to verify them for 64-bit values:
670
671 /*
672 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
673 x : BITVECTOR(64);
674 y : BITVECTOR(64);
675 z : BITVECTOR(64);
676 mask : BITVECTOR(64) = BVSHL(ONE, z);
677 QUERY( (y & ~mask = y) =>
678 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
679 );
680 QUERY( (y | mask = y) =>
681 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
682 );
683 */
684
685 // Please note that each pattern must be a dual implication (<--> or
686 // iff). One directional implication can create spurious matches. If the
687 // implication is only one-way, an unsatisfiable condition on the left
688 // side can imply a satisfiable condition on the right side. Dual
689 // implication ensures that satisfiable conditions are transformed to
690 // other satisfiable conditions and unsatisfiable conditions are
691 // transformed to other unsatisfiable conditions.
692
693 // Here is a concrete example of a unsatisfiable condition on the left
694 // implying a satisfiable condition on the right:
695 //
696 // mask = (1 << z)
697 // (x & ~mask) == y --> (x == y || x == (y | mask))
698 //
699 // Substituting y = 3, z = 0 yields:
700 // (x & -2) == 3 --> (x == 3 || x == 2)
701
702 // Pattern match a special case:
703 /*
704 QUERY( (y & ~mask = y) =>
705 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
706 );
707 */
708 if (match(ICI->getOperand(0),
709 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
710 APInt Mask = ~*RHSC;
711 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
712 // If we already have a value for the switch, it has to match!
713 if (!setValueOnce(RHSVal))
714 return false;
715
716 Vals.push_back(C);
717 Vals.push_back(
718 ConstantInt::get(C->getContext(),
719 C->getValue() | Mask));
720 UsedICmps++;
721 return true;
722 }
723 }
724
725 // Pattern match a special case:
726 /*
727 QUERY( (y | mask = y) =>
728 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
729 );
730 */
731 if (match(ICI->getOperand(0),
732 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
733 APInt Mask = *RHSC;
734 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
735 // If we already have a value for the switch, it has to match!
736 if (!setValueOnce(RHSVal))
737 return false;
738
739 Vals.push_back(C);
740 Vals.push_back(ConstantInt::get(C->getContext(),
741 C->getValue() & ~Mask));
742 UsedICmps++;
743 return true;
744 }
745 }
746
747 // If we already have a value for the switch, it has to match!
748 if (!setValueOnce(ICI->getOperand(0)))
749 return false;
750
751 UsedICmps++;
752 Vals.push_back(C);
753 return true;
754 }
755
756 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
757 ConstantRange Span =
759
760 // Shift the range if the compare is fed by an add. This is the range
761 // compare idiom as emitted by instcombine.
762 Value *CandidateVal = I->getOperand(0);
763 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
764 Span = Span.subtract(*RHSC);
765 CandidateVal = RHSVal;
766 }
767
768 // If this is an and/!= check, then we are looking to build the set of
769 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
770 // x != 0 && x != 1.
771 if (!isEQ)
772 Span = Span.inverse();
773
774 // If there are a ton of values, we don't want to make a ginormous switch.
775 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
776 return false;
777 }
778
779 // If we already have a value for the switch, it has to match!
780 if (!setValueOnce(CandidateVal))
781 return false;
782
783 // Add all values from the range to the set
784 APInt Tmp = Span.getLower();
785 do
786 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
787 while (++Tmp != Span.getUpper());
788
789 UsedICmps++;
790 return true;
791 }
792
793 /// Given a potentially 'or'd or 'and'd together collection of icmp
794 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
795 /// the value being compared, and stick the list constants into the Vals
796 /// vector.
797 /// One "Extra" case is allowed to differ from the other.
798 void gather(Value *V) {
799 Value *Op0, *Op1;
800 if (match(V, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
801 IsEq = true;
802 else if (match(V, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
803 IsEq = false;
804 else
805 return;
806 // Keep a stack (SmallVector for efficiency) for depth-first traversal
807 SmallVector<Value *, 8> DFT{Op0, Op1};
808 SmallPtrSet<Value *, 8> Visited{V, Op0, Op1};
809
810 while (!DFT.empty()) {
811 V = DFT.pop_back_val();
812
813 if (Instruction *I = dyn_cast<Instruction>(V)) {
814 // If it is a || (or && depending on isEQ), process the operands.
815 if (IsEq ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
816 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
817 if (Visited.insert(Op1).second)
818 DFT.push_back(Op1);
819 if (Visited.insert(Op0).second)
820 DFT.push_back(Op0);
821
822 continue;
823 }
824
825 // Try to match the current instruction
826 if (matchInstruction(I, IsEq))
827 // Match succeed, continue the loop
828 continue;
829 }
830
831 // One element of the sequence of || (or &&) could not be match as a
832 // comparison against the same value as the others.
833 // We allow only one "Extra" case to be checked before the switch
834 if (!Extra) {
835 Extra = V;
836 continue;
837 }
838 // Failed to parse a proper sequence, abort now
839 CompValue = nullptr;
840 break;
841 }
842 }
843};
844
845} // end anonymous namespace
846
848 MemorySSAUpdater *MSSAU = nullptr) {
849 Instruction *Cond = nullptr;
851 Cond = dyn_cast<Instruction>(SI->getCondition());
852 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
853 Cond = dyn_cast<Instruction>(BI->getCondition());
854 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
855 Cond = dyn_cast<Instruction>(IBI->getAddress());
856 }
857
858 TI->eraseFromParent();
859 if (Cond)
861}
862
863/// Return true if the specified terminator checks
864/// to see if a value is equal to constant integer value.
865Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
866 Value *CV = nullptr;
867 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
868 // Do not permit merging of large switch instructions into their
869 // predecessors unless there is only one predecessor.
870 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
871 CV = SI->getCondition();
872 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI))
873 if (BI->getCondition()->hasOneUse()) {
874 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
875 if (ICI->isEquality() && getConstantInt(ICI->getOperand(1), DL))
876 CV = ICI->getOperand(0);
877 } else if (auto *Trunc = dyn_cast<TruncInst>(BI->getCondition())) {
878 if (Trunc->hasNoUnsignedWrap())
879 CV = Trunc->getOperand(0);
880 }
881 }
882
883 // Unwrap any lossless ptrtoint cast (except for unstable pointers).
884 if (CV) {
885 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
886 Value *Ptr = PTII->getPointerOperand();
887 if (DL.hasUnstableRepresentation(Ptr->getType()))
888 return CV;
889 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
890 CV = Ptr;
891 }
892 }
893 return CV;
894}
895
896/// Given a value comparison instruction,
897/// decode all of the 'cases' that it represents and return the 'default' block.
898BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
899 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
900 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
901 Cases.reserve(SI->getNumCases());
902 for (auto Case : SI->cases())
903 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
904 Case.getCaseSuccessor()));
905 return SI->getDefaultDest();
906 }
907
908 CondBrInst *BI = cast<CondBrInst>(TI);
909 Value *Cond = BI->getCondition();
910 ICmpInst::Predicate Pred;
911 ConstantInt *C;
912 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
913 Pred = ICI->getPredicate();
914 C = getConstantInt(ICI->getOperand(1), DL);
915 } else {
916 Pred = ICmpInst::ICMP_NE;
917 auto *Trunc = cast<TruncInst>(Cond);
918 C = ConstantInt::get(cast<IntegerType>(Trunc->getOperand(0)->getType()), 0);
919 }
920 BasicBlock *Succ = BI->getSuccessor(Pred == ICmpInst::ICMP_NE);
921 Cases.push_back(ValueEqualityComparisonCase(C, Succ));
922 return BI->getSuccessor(Pred == ICmpInst::ICMP_EQ);
923}
924
925/// Given a vector of bb/value pairs, remove any entries
926/// in the list that match the specified block.
927static void
929 std::vector<ValueEqualityComparisonCase> &Cases) {
930 llvm::erase(Cases, BB);
931}
932
933/// Return true if there are any keys in C1 that exist in C2 as well.
934static bool valuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
935 std::vector<ValueEqualityComparisonCase> &C2) {
936 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
937
938 // Make V1 be smaller than V2.
939 if (V1->size() > V2->size())
940 std::swap(V1, V2);
941
942 if (V1->empty())
943 return false;
944 if (V1->size() == 1) {
945 // Just scan V2.
946 ConstantInt *TheVal = (*V1)[0].Value;
947 for (const ValueEqualityComparisonCase &VECC : *V2)
948 if (TheVal == VECC.Value)
949 return true;
950 }
951
952 // Otherwise, just sort both lists and compare element by element.
953 array_pod_sort(V1->begin(), V1->end());
954 array_pod_sort(V2->begin(), V2->end());
955 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
956 while (i1 != e1 && i2 != e2) {
957 if ((*V1)[i1].Value == (*V2)[i2].Value)
958 return true;
959 if ((*V1)[i1].Value < (*V2)[i2].Value)
960 ++i1;
961 else
962 ++i2;
963 }
964 return false;
965}
966
967/// If TI is known to be a terminator instruction and its block is known to
968/// only have a single predecessor block, check to see if that predecessor is
969/// also a value comparison with the same value, and if that comparison
970/// determines the outcome of this comparison. If so, simplify TI. This does a
971/// very limited form of jump threading.
972bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
973 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
974 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
975 if (!PredVal)
976 return false; // Not a value comparison in predecessor.
977
978 Value *ThisVal = isValueEqualityComparison(TI);
979 assert(ThisVal && "This isn't a value comparison!!");
980 if (ThisVal != PredVal)
981 return false; // Different predicates.
982
983 // TODO: Preserve branch weight metadata, similarly to how
984 // foldValueComparisonIntoPredecessors preserves it.
985
986 // Find out information about when control will move from Pred to TI's block.
987 std::vector<ValueEqualityComparisonCase> PredCases;
988 BasicBlock *PredDef =
989 getValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
990 eliminateBlockCases(PredDef, PredCases); // Remove default from cases.
991
992 // Find information about how control leaves this block.
993 std::vector<ValueEqualityComparisonCase> ThisCases;
994 BasicBlock *ThisDef = getValueEqualityComparisonCases(TI, ThisCases);
995 eliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
996
997 // If TI's block is the default block from Pred's comparison, potentially
998 // simplify TI based on this knowledge.
999 if (PredDef == TI->getParent()) {
1000 // If we are here, we know that the value is none of those cases listed in
1001 // PredCases. If there are any cases in ThisCases that are in PredCases, we
1002 // can simplify TI.
1003 if (!valuesOverlap(PredCases, ThisCases))
1004 return false;
1005
1006 if (isa<CondBrInst>(TI)) {
1007 // Okay, one of the successors of this condbr is dead. Convert it to a
1008 // uncond br.
1009 assert(ThisCases.size() == 1 && "Branch can only have one case!");
1010 // Insert the new branch.
1011 Instruction *NI = Builder.CreateBr(ThisDef);
1012 (void)NI;
1013
1014 // Remove PHI node entries for the dead edge.
1015 ThisCases[0].Dest->removePredecessor(PredDef);
1016
1017 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1018 << "Through successor TI: " << *TI << "Leaving: " << *NI
1019 << "\n");
1020
1022
1023 if (DTU)
1024 DTU->applyUpdates(
1025 {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
1026
1027 return true;
1028 }
1029
1030 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
1031 // Okay, TI has cases that are statically dead, prune them away.
1032 SmallPtrSet<Constant *, 16> DeadCases;
1033 for (const ValueEqualityComparisonCase &Case : PredCases)
1034 DeadCases.insert(Case.Value);
1035
1036 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1037 << "Through successor TI: " << *TI);
1038
1039 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
1040 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
1041 --i;
1042 auto *Successor = i->getCaseSuccessor();
1043 if (DTU)
1044 ++NumPerSuccessorCases[Successor];
1045 if (DeadCases.count(i->getCaseValue())) {
1046 Successor->removePredecessor(PredDef);
1047 SI.removeCase(i);
1048 if (DTU)
1049 --NumPerSuccessorCases[Successor];
1050 }
1051 }
1052
1053 if (DTU) {
1054 std::vector<DominatorTree::UpdateType> Updates;
1055 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
1056 if (I.second == 0)
1057 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
1058 DTU->applyUpdates(Updates);
1059 }
1060
1061 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
1062 return true;
1063 }
1064
1065 // Otherwise, TI's block must correspond to some matched value. Find out
1066 // which value (or set of values) this is.
1067 ConstantInt *TIV = nullptr;
1068 BasicBlock *TIBB = TI->getParent();
1069 for (const auto &[Value, Dest] : PredCases)
1070 if (Dest == TIBB) {
1071 if (TIV)
1072 return false; // Cannot handle multiple values coming to this block.
1073 TIV = Value;
1074 }
1075 assert(TIV && "No edge from pred to succ?");
1076
1077 // Okay, we found the one constant that our value can be if we get into TI's
1078 // BB. Find out which successor will unconditionally be branched to.
1079 BasicBlock *TheRealDest = nullptr;
1080 for (const auto &[Value, Dest] : ThisCases)
1081 if (Value == TIV) {
1082 TheRealDest = Dest;
1083 break;
1084 }
1085
1086 // If not handled by any explicit cases, it is handled by the default case.
1087 if (!TheRealDest)
1088 TheRealDest = ThisDef;
1089
1090 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1091
1092 // Remove PHI node entries for dead edges.
1093 BasicBlock *CheckEdge = TheRealDest;
1094 for (BasicBlock *Succ : successors(TIBB))
1095 if (Succ != CheckEdge) {
1096 if (Succ != TheRealDest)
1097 RemovedSuccs.insert(Succ);
1098 Succ->removePredecessor(TIBB);
1099 } else
1100 CheckEdge = nullptr;
1101
1102 // Insert the new branch.
1103 Instruction *NI = Builder.CreateBr(TheRealDest);
1104 (void)NI;
1105
1106 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1107 << "Through successor TI: " << *TI << "Leaving: " << *NI
1108 << "\n");
1109
1111 if (DTU) {
1112 SmallVector<DominatorTree::UpdateType, 2> Updates;
1113 Updates.reserve(RemovedSuccs.size());
1114 for (auto *RemovedSucc : RemovedSuccs)
1115 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1116 DTU->applyUpdates(Updates);
1117 }
1118 return true;
1119}
1120
1121namespace {
1122
1123/// This class implements a stable ordering of constant
1124/// integers that does not depend on their address. This is important for
1125/// applications that sort ConstantInt's to ensure uniqueness.
1126struct ConstantIntOrdering {
1127 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1128 return LHS->getValue().ult(RHS->getValue());
1129 }
1130};
1131
1132} // end anonymous namespace
1133
1135 ConstantInt *const *P2) {
1136 const ConstantInt *LHS = *P1;
1137 const ConstantInt *RHS = *P2;
1138 if (LHS == RHS)
1139 return 0;
1140 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1141}
1142
1143/// Get Weights of a given terminator, the default weight is at the front
1144/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1145/// metadata.
1147 SmallVectorImpl<uint64_t> &Weights) {
1148 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1149 assert(MD && "Invalid branch-weight metadata");
1150 extractFromBranchWeightMD64(MD, Weights);
1151
1152 // If TI is a conditional eq, the default case is the false case,
1153 // and the corresponding branch-weight data is at index 2. We swap the
1154 // default weight to be the first entry.
1155 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
1156 assert(Weights.size() == 2);
1157 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
1158 if (!ICI)
1159 return;
1160
1161 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1162 std::swap(Weights.front(), Weights.back());
1163 }
1164}
1165
1167 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1168 Instruction *PTI = PredBlock->getTerminator();
1169
1170 // If we have bonus instructions, clone them into the predecessor block.
1171 // Note that there may be multiple predecessor blocks, so we cannot move
1172 // bonus instructions to a predecessor block.
1173 for (Instruction &BonusInst : *BB) {
1174 if (BonusInst.isTerminator())
1175 continue;
1176
1177 // Skip cloning pseudo probes into the predecessor, as it would overcount
1178 // otherwise.
1179 if (isa<PseudoProbeInst>(BonusInst))
1180 continue;
1181
1182 Instruction *NewBonusInst = BonusInst.clone();
1183
1184 if (!NewBonusInst->getDebugLoc().isSameSourceLocation(PTI->getDebugLoc())) {
1185 // Unless the instruction has the same !dbg location as the original
1186 // branch, drop it. When we fold the bonus instructions we want to make
1187 // sure we reset their debug locations in order to avoid stepping on
1188 // dead code caused by folding dead branches.
1189 NewBonusInst->setDebugLoc(DebugLoc::getDropped());
1190 } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
1191 mapAtomInstance(DL, VMap);
1192 }
1193
1194 RemapInstruction(NewBonusInst, VMap,
1196
1197 // If we speculated an instruction, we need to drop any metadata that may
1198 // result in undefined behavior, as the metadata might have been valid
1199 // only given the branch precondition.
1200 // Similarly strip attributes on call parameters that may cause UB in
1201 // location the call is moved to.
1202 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1203
1204 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1205 auto Range = NewBonusInst->cloneDebugInfoFrom(&BonusInst);
1206 RemapDbgRecordRange(NewBonusInst->getModule(), Range, VMap,
1208
1209 NewBonusInst->takeName(&BonusInst);
1210 BonusInst.setName(NewBonusInst->getName() + ".old");
1211 VMap[&BonusInst] = NewBonusInst;
1212
1213 // Update (liveout) uses of bonus instructions,
1214 // now that the bonus instruction has been cloned into predecessor.
1215 // Note that we expect to be in a block-closed SSA form for this to work!
1216 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1217 auto *UI = cast<Instruction>(U.getUser());
1218 auto *PN = dyn_cast<PHINode>(UI);
1219 if (!PN) {
1220 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1221 "If the user is not a PHI node, then it should be in the same "
1222 "block as, and come after, the original bonus instruction.");
1223 continue; // Keep using the original bonus instruction.
1224 }
1225 // Is this the block-closed SSA form PHI node?
1226 if (PN->getIncomingBlock(U) == BB)
1227 continue; // Great, keep using the original bonus instruction.
1228 // The only other alternative is an "use" when coming from
1229 // the predecessor block - here we should refer to the cloned bonus instr.
1230 assert(PN->getIncomingBlock(U) == PredBlock &&
1231 "Not in block-closed SSA form?");
1232 U.set(NewBonusInst);
1233 }
1234 }
1235
1236 // Key Instructions: We may have propagated atom info into the pred. If the
1237 // pred's terminator already has atom info do nothing as merging would drop
1238 // one atom group anyway. If it doesn't, propagte the remapped atom group
1239 // from BB's terminator.
1240 if (auto &PredDL = PTI->getDebugLoc()) {
1241 auto &DL = BB->getTerminator()->getDebugLoc();
1242 if (!PredDL->getAtomGroup() && DL && DL->getAtomGroup() &&
1243 PredDL.isSameSourceLocation(DL)) {
1244 PTI->setDebugLoc(DL);
1245 RemapSourceAtom(PTI, VMap);
1246 }
1247 }
1248}
1249
1250bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
1251 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1252 BasicBlock *BB = TI->getParent();
1253 BasicBlock *Pred = PTI->getParent();
1254
1256
1257 // Figure out which 'cases' to copy from SI to PSI.
1258 std::vector<ValueEqualityComparisonCase> BBCases;
1259 BasicBlock *BBDefault = getValueEqualityComparisonCases(TI, BBCases);
1260
1261 std::vector<ValueEqualityComparisonCase> PredCases;
1262 BasicBlock *PredDefault = getValueEqualityComparisonCases(PTI, PredCases);
1263
1264 // Based on whether the default edge from PTI goes to BB or not, fill in
1265 // PredCases and PredDefault with the new switch cases we would like to
1266 // build.
1267 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1268
1269 // Update the branch weight metadata along the way
1270 SmallVector<uint64_t, 8> Weights;
1271 bool PredHasWeights = hasBranchWeightMD(*PTI);
1272 bool SuccHasWeights = hasBranchWeightMD(*TI);
1273
1274 if (PredHasWeights) {
1275 getBranchWeights(PTI, Weights);
1276 // branch-weight metadata is inconsistent here.
1277 if (Weights.size() != 1 + PredCases.size())
1278 PredHasWeights = SuccHasWeights = false;
1279 } else if (SuccHasWeights)
1280 // If there are no predecessor weights but there are successor weights,
1281 // populate Weights with 1, which will later be scaled to the sum of
1282 // successor's weights
1283 Weights.assign(1 + PredCases.size(), 1);
1284
1285 SmallVector<uint64_t, 8> SuccWeights;
1286 if (SuccHasWeights) {
1287 getBranchWeights(TI, SuccWeights);
1288 // branch-weight metadata is inconsistent here.
1289 if (SuccWeights.size() != 1 + BBCases.size())
1290 PredHasWeights = SuccHasWeights = false;
1291 } else if (PredHasWeights)
1292 SuccWeights.assign(1 + BBCases.size(), 1);
1293
1294 if (PredDefault == BB) {
1295 // If this is the default destination from PTI, only the edges in TI
1296 // that don't occur in PTI, or that branch to BB will be activated.
1297 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1298 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1299 if (PredCases[i].Dest != BB)
1300 PTIHandled.insert(PredCases[i].Value);
1301 else {
1302 // The default destination is BB, we don't need explicit targets.
1303 std::swap(PredCases[i], PredCases.back());
1304
1305 if (PredHasWeights || SuccHasWeights) {
1306 // Increase weight for the default case.
1307 Weights[0] += Weights[i + 1];
1308 std::swap(Weights[i + 1], Weights.back());
1309 Weights.pop_back();
1310 }
1311
1312 PredCases.pop_back();
1313 --i;
1314 --e;
1315 }
1316
1317 // Reconstruct the new switch statement we will be building.
1318 if (PredDefault != BBDefault) {
1319 PredDefault->removePredecessor(Pred);
1320 if (DTU && PredDefault != BB)
1321 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1322 PredDefault = BBDefault;
1323 ++NewSuccessors[BBDefault];
1324 }
1325
1326 unsigned CasesFromPred = Weights.size();
1327 uint64_t ValidTotalSuccWeight = 0;
1328 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1329 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1330 PredCases.push_back(BBCases[i]);
1331 ++NewSuccessors[BBCases[i].Dest];
1332 if (SuccHasWeights || PredHasWeights) {
1333 // The default weight is at index 0, so weight for the ith case
1334 // should be at index i+1. Scale the cases from successor by
1335 // PredDefaultWeight (Weights[0]).
1336 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1337 ValidTotalSuccWeight += SuccWeights[i + 1];
1338 }
1339 }
1340
1341 if (SuccHasWeights || PredHasWeights) {
1342 ValidTotalSuccWeight += SuccWeights[0];
1343 // Scale the cases from predecessor by ValidTotalSuccWeight.
1344 for (unsigned i = 1; i < CasesFromPred; ++i)
1345 Weights[i] *= ValidTotalSuccWeight;
1346 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1347 Weights[0] *= SuccWeights[0];
1348 }
1349 } else {
1350 // If this is not the default destination from PSI, only the edges
1351 // in SI that occur in PSI with a destination of BB will be
1352 // activated.
1353 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1354 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1355 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1356 if (PredCases[i].Dest == BB) {
1357 PTIHandled.insert(PredCases[i].Value);
1358
1359 if (PredHasWeights || SuccHasWeights) {
1360 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1361 std::swap(Weights[i + 1], Weights.back());
1362 Weights.pop_back();
1363 }
1364
1365 std::swap(PredCases[i], PredCases.back());
1366 PredCases.pop_back();
1367 --i;
1368 --e;
1369 }
1370
1371 // Okay, now we know which constants were sent to BB from the
1372 // predecessor. Figure out where they will all go now.
1373 for (const ValueEqualityComparisonCase &Case : BBCases)
1374 if (PTIHandled.count(Case.Value)) {
1375 // If this is one we are capable of getting...
1376 if (PredHasWeights || SuccHasWeights)
1377 Weights.push_back(WeightsForHandled[Case.Value]);
1378 PredCases.push_back(Case);
1379 ++NewSuccessors[Case.Dest];
1380 PTIHandled.erase(Case.Value); // This constant is taken care of
1381 }
1382
1383 // If there are any constants vectored to BB that TI doesn't handle,
1384 // they must go to the default destination of TI.
1385 for (ConstantInt *I : PTIHandled) {
1386 if (PredHasWeights || SuccHasWeights)
1387 Weights.push_back(WeightsForHandled[I]);
1388 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1389 ++NewSuccessors[BBDefault];
1390 }
1391 }
1392
1393 // Okay, at this point, we know which new successor Pred will get. Make
1394 // sure we update the number of entries in the PHI nodes for these
1395 // successors.
1396 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1397 if (DTU) {
1398 SuccsOfPred = {llvm::from_range, successors(Pred)};
1399 Updates.reserve(Updates.size() + NewSuccessors.size());
1400 }
1401 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1402 NewSuccessors) {
1403 for (auto I : seq(NewSuccessor.second)) {
1404 (void)I;
1405 addPredecessorToBlock(NewSuccessor.first, Pred, BB);
1406 }
1407 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1408 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1409 }
1410
1411 Builder.SetInsertPoint(PTI);
1412 // Convert pointer to int before we switch.
1413 if (CV->getType()->isPointerTy()) {
1414 assert(!DL.hasUnstableRepresentation(CV->getType()) &&
1415 "Should not end up here with unstable pointers");
1416 CV =
1417 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1418 }
1419
1420 // Now that the successors are updated, create the new Switch instruction.
1421 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1422 NewSI->setDebugLoc(PTI->getDebugLoc());
1423 for (ValueEqualityComparisonCase &V : PredCases)
1424 NewSI->addCase(V.Value, V.Dest);
1425
1426 if (PredHasWeights || SuccHasWeights)
1427 setFittedBranchWeights(*NewSI, Weights, /*IsExpected=*/false,
1428 /*ElideAllZero=*/true);
1429
1431
1432 // Okay, last check. If BB is still a successor of PSI, then we must
1433 // have an infinite loop case. If so, add an infinitely looping block
1434 // to handle the case to preserve the behavior of the code.
1435 BasicBlock *InfLoopBlock = nullptr;
1436 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1437 if (NewSI->getSuccessor(i) == BB) {
1438 if (!InfLoopBlock) {
1439 // Insert it at the end of the function, because it's either code,
1440 // or it won't matter if it's hot. :)
1441 InfLoopBlock =
1442 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1443 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
1444 if (DTU)
1445 Updates.push_back(
1446 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1447 }
1448 NewSI->setSuccessor(i, InfLoopBlock);
1449 }
1450
1451 if (DTU) {
1452 if (InfLoopBlock)
1453 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1454
1455 Updates.push_back({DominatorTree::Delete, Pred, BB});
1456
1457 DTU->applyUpdates(Updates);
1458 }
1459
1460 ++NumFoldValueComparisonIntoPredecessors;
1461 return true;
1462}
1463
1464/// The specified terminator is a value equality comparison instruction
1465/// (either a switch or a branch on "X == c").
1466/// See if any of the predecessors of the terminator block are value comparisons
1467/// on the same value. If so, and if safe to do so, fold them together.
1468bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1469 IRBuilder<> &Builder) {
1470 BasicBlock *BB = TI->getParent();
1471 Value *CV = isValueEqualityComparison(TI); // CondVal
1472 assert(CV && "Not a comparison?");
1473
1474 bool Changed = false;
1475
1476 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1477 while (!Preds.empty()) {
1478 BasicBlock *Pred = Preds.pop_back_val();
1479 Instruction *PTI = Pred->getTerminator();
1480
1481 // Don't try to fold into itself.
1482 if (Pred == BB)
1483 continue;
1484
1485 // See if the predecessor is a comparison with the same value.
1486 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1487 if (PCV != CV)
1488 continue;
1489
1490 SmallSetVector<BasicBlock *, 4> FailBlocks;
1491 if (!safeToMergeTerminators(TI, PTI, &FailBlocks)) {
1492 for (auto *Succ : FailBlocks) {
1493 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1494 return false;
1495 }
1496 }
1497
1498 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1499 Changed = true;
1500 }
1501 return Changed;
1502}
1503
1504// If we would need to insert a select that uses the value of this invoke
1505// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1506// need to do this), we can't hoist the invoke, as there is nowhere to put the
1507// select in this case.
1509 Instruction *I1, Instruction *I2) {
1510 for (BasicBlock *Succ : successors(BB1)) {
1511 for (const PHINode &PN : Succ->phis()) {
1512 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1513 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1514 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1515 return false;
1516 }
1517 }
1518 }
1519 return true;
1520}
1521
1522// Get interesting characteristics of instructions that
1523// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1524// instructions can be reordered across.
1530
1532 // Pseudo probes don't constrain reordering of other instructions.
1534 return 0;
1535 unsigned Flags = 0;
1536 if (I->mayReadFromMemory())
1537 Flags |= SkipReadMem;
1538 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1539 // inalloca) across stacksave/stackrestore boundaries.
1540 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1541 Flags |= SkipSideEffect;
1543 Flags |= SkipImplicitControlFlow;
1544 return Flags;
1545}
1546
1547// Returns true if it is safe to reorder an instruction across preceding
1548// instructions in a basic block.
1549static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1550 // Don't reorder a store over a load.
1551 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1552 return false;
1553
1554 // If we have seen an instruction with side effects, it's unsafe to reorder an
1555 // instruction which reads memory or itself has side effects.
1556 if ((Flags & SkipSideEffect) &&
1557 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1558 return false;
1559
1560 // Reordering across an instruction which does not necessarily transfer
1561 // control to the next instruction is speculation.
1563 return false;
1564
1565 // Hoisting of llvm.deoptimize is only legal together with the next return
1566 // instruction, which this pass is not always able to do.
1567 if (auto *CB = dyn_cast<CallBase>(I))
1568 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1569 return false;
1570
1571 // It's also unsafe/illegal to hoist an instruction above its instruction
1572 // operands
1573 BasicBlock *BB = I->getParent();
1574 for (Value *Op : I->operands()) {
1575 if (auto *J = dyn_cast<Instruction>(Op))
1576 if (J->getParent() == BB)
1577 return false;
1578 }
1579
1580 return true;
1581}
1582
1583static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1584
1585/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1586/// instructions \p I1 and \p I2 can and should be hoisted.
1588 const TargetTransformInfo &TTI) {
1589 // If we're going to hoist a call, make sure that the two instructions
1590 // we're commoning/hoisting are both marked with musttail, or neither of
1591 // them is marked as such. Otherwise, we might end up in a situation where
1592 // we hoist from a block where the terminator is a `ret` to a block where
1593 // the terminator is a `br`, and `musttail` calls expect to be followed by
1594 // a return.
1595 auto *C1 = dyn_cast<CallInst>(I1);
1596 auto *C2 = dyn_cast<CallInst>(I2);
1597 if (C1 && C2)
1598 if (C1->isMustTailCall() != C2->isMustTailCall())
1599 return false;
1600
1601 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1602 return false;
1603
1604 // If any of the two call sites has nomerge or convergent attribute, stop
1605 // hoisting.
1606 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1607 if (CB1->cannotMerge() || CB1->isConvergent())
1608 return false;
1609 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1610 if (CB2->cannotMerge() || CB2->isConvergent())
1611 return false;
1612
1613 return true;
1614}
1615
1616/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1617/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1618/// hoistCommonCodeFromSuccessors. e.g. The input:
1619/// I1 DVRs: { x, z },
1620/// OtherInsts: { I2 DVRs: { x, y, z } }
1621/// would result in hoisting only DbgVariableRecord x.
1623 Instruction *TI, Instruction *I1,
1624 SmallVectorImpl<Instruction *> &OtherInsts) {
1625 if (!I1->hasDbgRecords())
1626 return;
1627 using CurrentAndEndIt =
1628 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1629 // Vector of {Current, End} iterators.
1631 Itrs.reserve(OtherInsts.size() + 1);
1632 // Helper lambdas for lock-step checks:
1633 // Return true if this Current == End.
1634 auto atEnd = [](const CurrentAndEndIt &Pair) {
1635 return Pair.first == Pair.second;
1636 };
1637 // Return true if all Current are identical.
1638 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1639 return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
1641 return Itrs[0].first->isIdenticalToWhenDefined(*I);
1642 });
1643 };
1644
1645 // Collect the iterators.
1646 Itrs.push_back(
1647 {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1648 for (Instruction *Other : OtherInsts) {
1649 if (!Other->hasDbgRecords())
1650 return;
1651 Itrs.push_back(
1652 {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1653 }
1654
1655 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1656 // the lock-step DbgRecord are identical, hoist all of them to TI.
1657 // This replicates the dbg.* intrinsic behaviour in
1658 // hoistCommonCodeFromSuccessors.
1659 while (none_of(Itrs, atEnd)) {
1660 bool HoistDVRs = allIdentical(Itrs);
1661 for (CurrentAndEndIt &Pair : Itrs) {
1662 // Increment Current iterator now as we may be about to move the
1663 // DbgRecord.
1664 DbgRecord &DR = *Pair.first++;
1665 if (HoistDVRs) {
1666 DR.removeFromParent();
1667 TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
1668 }
1669 }
1670 }
1671}
1672
1674 const Instruction *I2) {
1675 if (I1->isIdenticalToWhenDefined(I2, /*IntersectAttrs=*/true))
1676 return true;
1677
1678 if (auto *Cmp1 = dyn_cast<CmpInst>(I1))
1679 if (auto *Cmp2 = dyn_cast<CmpInst>(I2))
1680 return Cmp1->getPredicate() == Cmp2->getSwappedPredicate() &&
1681 Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
1682 Cmp1->getOperand(1) == Cmp2->getOperand(0);
1683
1684 if (I1->isCommutative() && I1->isSameOperationAs(I2)) {
1685 return I1->getOperand(0) == I2->getOperand(1) &&
1686 I1->getOperand(1) == I2->getOperand(0) &&
1687 equal(drop_begin(I1->operands(), 2), drop_begin(I2->operands(), 2));
1688 }
1689
1690 return false;
1691}
1692
1693/// If the target supports conditional faulting,
1694/// we look for the following pattern:
1695/// \code
1696/// BB:
1697/// ...
1698/// %cond = icmp ult %x, %y
1699/// br i1 %cond, label %TrueBB, label %FalseBB
1700/// FalseBB:
1701/// store i32 1, ptr %q, align 4
1702/// ...
1703/// TrueBB:
1704/// %maskedloadstore = load i32, ptr %b, align 4
1705/// store i32 %maskedloadstore, ptr %p, align 4
1706/// ...
1707/// \endcode
1708///
1709/// and transform it into:
1710///
1711/// \code
1712/// BB:
1713/// ...
1714/// %cond = icmp ult %x, %y
1715/// %maskedloadstore = cload i32, ptr %b, %cond
1716/// cstore i32 %maskedloadstore, ptr %p, %cond
1717/// cstore i32 1, ptr %q, ~%cond
1718/// br i1 %cond, label %TrueBB, label %FalseBB
1719/// FalseBB:
1720/// ...
1721/// TrueBB:
1722/// ...
1723/// \endcode
1724///
1725/// where cload/cstore are represented by llvm.masked.load/store intrinsics,
1726/// e.g.
1727///
1728/// \code
1729/// %vcond = bitcast i1 %cond to <1 x i1>
1730/// %v0 = call <1 x i32> @llvm.masked.load.v1i32.p0
1731/// (ptr %b, i32 4, <1 x i1> %vcond, <1 x i32> poison)
1732/// %maskedloadstore = bitcast <1 x i32> %v0 to i32
1733/// call void @llvm.masked.store.v1i32.p0
1734/// (<1 x i32> %v0, ptr %p, i32 4, <1 x i1> %vcond)
1735/// %cond.not = xor i1 %cond, true
1736/// %vcond.not = bitcast i1 %cond.not to <1 x i>
1737/// call void @llvm.masked.store.v1i32.p0
1738/// (<1 x i32> <i32 1>, ptr %q, i32 4, <1x i1> %vcond.not)
1739/// \endcode
1740///
1741/// So we need to turn hoisted load/store into cload/cstore.
1742///
1743/// \param BI The branch instruction.
1744/// \param SpeculatedConditionalLoadsStores The load/store instructions that
1745/// will be speculated.
1746/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
1748 CondBrInst *BI,
1749 SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
1750 std::optional<bool> Invert, Instruction *Sel) {
1751 auto &Context = BI->getParent()->getContext();
1752 auto *VCondTy = FixedVectorType::get(Type::getInt1Ty(Context), 1);
1753 auto *Cond = BI->getCondition();
1754 // Construct the condition if needed.
1755 BasicBlock *BB = BI->getParent();
1756 Value *Mask = nullptr;
1757 Value *MaskFalse = nullptr;
1758 Value *MaskTrue = nullptr;
1759 if (Invert.has_value()) {
1760 IRBuilder<> Builder(Sel ? Sel : SpeculatedConditionalLoadsStores.back());
1761 Mask = Builder.CreateBitCast(
1762 *Invert ? Builder.CreateXor(Cond, ConstantInt::getTrue(Context)) : Cond,
1763 VCondTy);
1764 } else {
1765 IRBuilder<> Builder(BI);
1766 MaskFalse = Builder.CreateBitCast(
1767 Builder.CreateXor(Cond, ConstantInt::getTrue(Context)), VCondTy);
1768 MaskTrue = Builder.CreateBitCast(Cond, VCondTy);
1769 }
1770 auto PeekThroughBitcasts = [](Value *V) {
1771 while (auto *BitCast = dyn_cast<BitCastInst>(V))
1772 V = BitCast->getOperand(0);
1773 return V;
1774 };
1775 for (auto *I : SpeculatedConditionalLoadsStores) {
1776 IRBuilder<> Builder(Invert.has_value() ? I : BI);
1777 if (!Invert.has_value())
1778 Mask = I->getParent() == BI->getSuccessor(0) ? MaskTrue : MaskFalse;
1779 // We currently assume conditional faulting load/store is supported for
1780 // scalar types only when creating new instructions. This can be easily
1781 // extended for vector types in the future.
1782 assert(!getLoadStoreType(I)->isVectorTy() && "not implemented");
1783 auto *Op0 = I->getOperand(0);
1784 CallInst *MaskedLoadStore = nullptr;
1785 if (auto *LI = dyn_cast<LoadInst>(I)) {
1786 // Handle Load.
1787 auto *Ty = I->getType();
1788 PHINode *PN = nullptr;
1789 Value *PassThru = nullptr;
1790 if (Invert.has_value())
1791 for (User *U : I->users()) {
1792 if ((PN = dyn_cast<PHINode>(U))) {
1793 PassThru = Builder.CreateBitCast(
1794 PeekThroughBitcasts(PN->getIncomingValueForBlock(BB)),
1795 FixedVectorType::get(Ty, 1));
1796 } else if (auto *Ins = cast<Instruction>(U);
1797 Sel && Ins->getParent() == BB) {
1798 // This happens when store or/and a speculative instruction between
1799 // load and store were hoisted to the BB. Make sure the masked load
1800 // inserted before its use.
1801 // We assume there's one of such use.
1802 Builder.SetInsertPoint(Ins);
1803 }
1804 }
1805 MaskedLoadStore = Builder.CreateMaskedLoad(
1806 FixedVectorType::get(Ty, 1), Op0, LI->getAlign(), Mask, PassThru);
1807 Value *NewLoadStore = Builder.CreateBitCast(MaskedLoadStore, Ty);
1808 if (PN)
1809 PN->setIncomingValue(PN->getBasicBlockIndex(BB), NewLoadStore);
1810 I->replaceAllUsesWith(NewLoadStore);
1811 } else {
1812 // Handle Store.
1813 auto *StoredVal = Builder.CreateBitCast(
1814 PeekThroughBitcasts(Op0), FixedVectorType::get(Op0->getType(), 1));
1815 MaskedLoadStore = Builder.CreateMaskedStore(
1816 StoredVal, I->getOperand(1), cast<StoreInst>(I)->getAlign(), Mask);
1817 }
1818 // For non-debug metadata, only !annotation, !range, !nonnull and !align are
1819 // kept when hoisting (see Instruction::dropUBImplyingAttrsAndMetadata).
1820 //
1821 // !nonnull, !align : Not support pointer type, no need to keep.
1822 // !range: Load type is changed from scalar to vector, but the metadata on
1823 // vector specifies a per-element range, so the semantics stay the
1824 // same. Keep it.
1825 // !annotation: Not impact semantics. Keep it.
1826 if (const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1827 MaskedLoadStore->addRangeRetAttr(getConstantRangeFromMetadata(*Ranges));
1828 I->dropUBImplyingAttrsAndUnknownMetadata({LLVMContext::MD_annotation});
1829 // FIXME: DIAssignID is not supported for masked store yet.
1830 // (Verifier::visitDIAssignIDMetadata)
1832 I->eraseMetadataIf([](unsigned MDKind, MDNode *Node) {
1833 return Node->getMetadataID() == Metadata::DIAssignIDKind;
1834 });
1835 MaskedLoadStore->copyMetadata(*I);
1836 I->eraseFromParent();
1837 }
1838}
1839
1841 const TargetTransformInfo &TTI) {
1842 // Not handle volatile or atomic.
1843 bool IsStore = false;
1844 if (auto *L = dyn_cast<LoadInst>(I)) {
1845 if (!L->isSimple() || !HoistLoadsWithCondFaulting)
1846 return false;
1847 } else if (auto *S = dyn_cast<StoreInst>(I)) {
1848 if (!S->isSimple() || !HoistStoresWithCondFaulting)
1849 return false;
1850 IsStore = true;
1851 } else
1852 return false;
1853
1854 // llvm.masked.load/store use i32 for alignment while load/store use i64.
1855 // That's why we have the alignment limitation.
1856 // FIXME: Update the prototype of the intrinsics?
1857 return TTI.hasConditionalLoadStoreForType(getLoadStoreType(I), IsStore) &&
1859}
1860
1861/// Hoist any common code in the successor blocks up into the block. This
1862/// function guarantees that BB dominates all successors. If AllInstsEqOnly is
1863/// given, only perform hoisting in case all successors blocks contain matching
1864/// instructions only. In that case, all instructions can be hoisted and the
1865/// original branch will be replaced and selects for PHIs are added.
1866bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(Instruction *TI,
1867 bool AllInstsEqOnly) {
1868 // This does very trivial matching, with limited scanning, to find identical
1869 // instructions in the two blocks. In particular, we don't want to get into
1870 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1871 // such, we currently just scan for obviously identical instructions in an
1872 // identical order, possibly separated by the same number of non-identical
1873 // instructions.
1874 BasicBlock *BB = TI->getParent();
1875 unsigned int SuccSize = succ_size(BB);
1876 if (SuccSize < 2)
1877 return false;
1878
1879 // If either of the blocks has it's address taken, then we can't do this fold,
1880 // because the code we'd hoist would no longer run when we jump into the block
1881 // by it's address.
1882 SmallSetVector<BasicBlock *, 4> UniqueSuccessors(from_range, successors(BB));
1883 for (auto *Succ : UniqueSuccessors) {
1884 if (Succ->hasAddressTaken())
1885 return false;
1886 // Use getUniquePredecessor instead of getSinglePredecessor to support
1887 // multi-cases successors in switch.
1888 if (Succ->getUniquePredecessor())
1889 continue;
1890 // If Succ has >1 predecessors, continue to check if the Succ contains only
1891 // one `unreachable` inst. Since executing `unreachable` inst is an UB, we
1892 // can relax the condition based on the assumptiom that the program would
1893 // never enter Succ and trigger such an UB.
1894 if (isa<UnreachableInst>(*Succ->begin()))
1895 continue;
1896 return false;
1897 }
1898 // The second of pair is a SkipFlags bitmask.
1899 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1900 SmallVector<SuccIterPair, 8> SuccIterPairs;
1901 for (auto *Succ : UniqueSuccessors) {
1902 BasicBlock::iterator SuccItr = Succ->begin();
1903 if (isa<PHINode>(*SuccItr))
1904 return false;
1905 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1906 }
1907
1908 if (AllInstsEqOnly) {
1909 // Check if all instructions in the successor blocks match. This allows
1910 // hoisting all instructions and removing the blocks we are hoisting from,
1911 // so does not add any new instructions.
1912
1913 // Check if sizes and terminators of all successors match.
1914 unsigned Size0 = UniqueSuccessors[0]->size();
1915 Instruction *Term0 = UniqueSuccessors[0]->getTerminator();
1916 bool AllSame =
1917 all_of(drop_begin(UniqueSuccessors), [Term0, Size0](BasicBlock *Succ) {
1918 return Succ->getTerminator()->isIdenticalTo(Term0) &&
1919 Succ->size() == Size0;
1920 });
1921 if (!AllSame)
1922 return false;
1923 LockstepReverseIterator<true> LRI(UniqueSuccessors.getArrayRef());
1924 while (LRI.isValid()) {
1925 Instruction *I0 = (*LRI)[0];
1926 if (any_of(*LRI, [I0](Instruction *I) {
1927 return !areIdenticalUpToCommutativity(I0, I);
1928 })) {
1929 return false;
1930 }
1931 --LRI;
1932 }
1933 // Now we know that all instructions in all successors can be hoisted. Let
1934 // the loop below handle the hoisting.
1935 }
1936
1937 // Count how many instructions were not hoisted so far. There's a limit on how
1938 // many instructions we skip, serving as a compilation time control as well as
1939 // preventing excessive increase of life ranges.
1940 unsigned NumSkipped = 0;
1941 // If we find an unreachable instruction at the beginning of a basic block, we
1942 // can still hoist instructions from the rest of the basic blocks.
1943 if (SuccIterPairs.size() > 2) {
1944 erase_if(SuccIterPairs,
1945 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1946 if (SuccIterPairs.size() < 2)
1947 return false;
1948 }
1949
1950 bool Changed = false;
1951
1952 for (;;) {
1953 auto *SuccIterPairBegin = SuccIterPairs.begin();
1954 auto &BB1ItrPair = *SuccIterPairBegin++;
1955 auto OtherSuccIterPairRange =
1956 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1957 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1958
1959 Instruction *I1 = &*BB1ItrPair.first;
1960
1961 bool AllInstsAreIdentical = true;
1962 bool HasTerminator = I1->isTerminator();
1963 for (auto &SuccIter : OtherSuccIterRange) {
1964 Instruction *I2 = &*SuccIter;
1965 HasTerminator |= I2->isTerminator();
1966 if (AllInstsAreIdentical && (!areIdenticalUpToCommutativity(I1, I2) ||
1967 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1968 AllInstsAreIdentical = false;
1969 }
1970
1971 SmallVector<Instruction *, 8> OtherInsts;
1972 for (auto &SuccIter : OtherSuccIterRange)
1973 OtherInsts.push_back(&*SuccIter);
1974
1975 // If we are hoisting the terminator instruction, don't move one (making a
1976 // broken BB), instead clone it, and remove BI.
1977 if (HasTerminator) {
1978 // Even if BB, which contains only one unreachable instruction, is ignored
1979 // at the beginning of the loop, we can hoist the terminator instruction.
1980 // If any instructions remain in the block, we cannot hoist terminators.
1981 if (NumSkipped || !AllInstsAreIdentical) {
1982 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1983 return Changed;
1984 }
1985
1986 return hoistSuccIdenticalTerminatorToSwitchOrIf(
1987 TI, I1, OtherInsts, UniqueSuccessors.getArrayRef()) ||
1988 Changed;
1989 }
1990
1991 if (AllInstsAreIdentical) {
1992 unsigned SkipFlagsBB1 = BB1ItrPair.second;
1993 AllInstsAreIdentical =
1994 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
1995 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
1996 Instruction *I2 = &*Pair.first;
1997 unsigned SkipFlagsBB2 = Pair.second;
1998 // Even if the instructions are identical, it may not
1999 // be safe to hoist them if we have skipped over
2000 // instructions with side effects or their operands
2001 // weren't hoisted.
2002 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
2004 });
2005 }
2006
2007 // A musttail call must be immediately followed by a ret, so hoisting is
2008 // only legal if its ret is hoisted with it on the next iteration. That is,
2009 // no instruction has been skipped (the entire successor can be hoisted into
2010 // the predecessor) and the call is directly followed by a ret.
2011 if (auto *CI = dyn_cast<CallInst>(I1);
2012 AllInstsAreIdentical && CI && CI->isMustTailCall()) {
2013 AllInstsAreIdentical =
2014 NumSkipped == 0 && all_of(SuccIterPairs, [](const SuccIterPair &P) {
2015 return isa<ReturnInst>(*std::next(P.first));
2016 });
2017 }
2018
2019 if (AllInstsAreIdentical) {
2020 BB1ItrPair.first++;
2021 // For a normal instruction, we just move one to right before the
2022 // branch, then replace all uses of the other with the first. Finally,
2023 // we remove the now redundant second instruction.
2024 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2025 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
2026 // and leave any that were not hoisted behind (by calling moveBefore
2027 // rather than moveBeforePreserving).
2028 I1->moveBefore(TI->getIterator());
2029 for (auto &SuccIter : OtherSuccIterRange) {
2030 Instruction *I2 = &*SuccIter++;
2031 assert(I2 != I1);
2032 if (!I2->use_empty())
2033 I2->replaceAllUsesWith(I1);
2034 I1->andIRFlags(I2);
2035 if (auto *CB = dyn_cast<CallBase>(I1)) {
2036 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I2));
2037 assert(Success && "We should not be trying to hoist callbases "
2038 "with non-intersectable attributes");
2039 // For NDEBUG Compile.
2040 (void)Success;
2041 }
2042
2043 combineMetadataForCSE(I1, I2, true);
2044 // I1 and I2 are being combined into a single instruction. Its debug
2045 // location is the merged locations of the original instructions.
2046 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
2047 I2->eraseFromParent();
2048 }
2049 if (!Changed)
2050 NumHoistCommonCode += SuccIterPairs.size();
2051 Changed = true;
2052 NumHoistCommonInstrs += SuccIterPairs.size();
2053 } else {
2054 if (NumSkipped >= HoistCommonSkipLimit) {
2055 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2056 return Changed;
2057 }
2058 // We are about to skip over a pair of non-identical instructions. Record
2059 // if any have characteristics that would prevent reordering instructions
2060 // across them.
2061 for (auto &SuccIterPair : SuccIterPairs) {
2062 Instruction *I = &*SuccIterPair.first++;
2063 SuccIterPair.second |= skippedInstrFlags(I);
2064 }
2065 ++NumSkipped;
2066 }
2067 }
2068}
2069
2070bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
2071 Instruction *TI, Instruction *I1,
2072 SmallVectorImpl<Instruction *> &OtherSuccTIs,
2073 ArrayRef<BasicBlock *> UniqueSuccessors) {
2074
2075 auto *BI = dyn_cast<CondBrInst>(TI);
2076
2077 bool Changed = false;
2078 BasicBlock *TIParent = TI->getParent();
2079 BasicBlock *BB1 = I1->getParent();
2080
2081 // Use only for an if statement.
2082 auto *I2 = *OtherSuccTIs.begin();
2083 auto *BB2 = I2->getParent();
2084 if (BI) {
2085 assert(OtherSuccTIs.size() == 1);
2086 assert(BI->getSuccessor(0) == I1->getParent());
2087 assert(BI->getSuccessor(1) == I2->getParent());
2088 }
2089
2090 // In the case of an if statement, we try to hoist an invoke.
2091 // FIXME: Can we define a safety predicate for CallBr?
2092 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
2093 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
2094 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
2095 return false;
2096
2097 // TODO: callbr hoisting currently disabled pending further study.
2098 if (isa<CallBrInst>(I1))
2099 return false;
2100
2101 for (BasicBlock *Succ : successors(BB1)) {
2102 for (PHINode &PN : Succ->phis()) {
2103 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2104 for (Instruction *OtherSuccTI : OtherSuccTIs) {
2105 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
2106 if (BB1V == BB2V)
2107 continue;
2108
2109 // In the case of an if statement, check for
2110 // passingValueIsAlwaysUndefined here because we would rather eliminate
2111 // undefined control flow then converting it to a select.
2112 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
2114 return false;
2115 }
2116 }
2117 }
2118
2119 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
2120 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
2121 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
2122 // Clone the terminator and hoist it into the pred, without any debug info.
2123 Instruction *NT = I1->clone();
2124 NT->insertInto(TIParent, TI->getIterator());
2125 if (!NT->getType()->isVoidTy()) {
2126 I1->replaceAllUsesWith(NT);
2127 for (Instruction *OtherSuccTI : OtherSuccTIs)
2128 OtherSuccTI->replaceAllUsesWith(NT);
2129 NT->takeName(I1);
2130 }
2131 Changed = true;
2132 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
2133
2134 // Ensure terminator gets a debug location, even an unknown one, in case
2135 // it involves inlinable calls.
2137 Locs.push_back(I1->getDebugLoc());
2138 for (auto *OtherSuccTI : OtherSuccTIs)
2139 Locs.push_back(OtherSuccTI->getDebugLoc());
2140 NT->setDebugLoc(DebugLoc::getMergedLocations(Locs));
2141
2142 // PHIs created below will adopt NT's merged DebugLoc.
2143 IRBuilder<NoFolder> Builder(NT);
2144
2145 // In the case of an if statement, hoisting one of the terminators from our
2146 // successor is a great thing. Unfortunately, the successors of the if/else
2147 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
2148 // must agree for all PHI nodes, so we insert select instruction to compute
2149 // the final result.
2150 if (BI) {
2151 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
2152 for (BasicBlock *Succ : successors(BB1)) {
2153 for (PHINode &PN : Succ->phis()) {
2154 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2155 Value *BB2V = PN.getIncomingValueForBlock(BB2);
2156 if (BB1V == BB2V)
2157 continue;
2158
2159 // These values do not agree. Insert a select instruction before NT
2160 // that determines the right value.
2161 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
2162 if (!SI) {
2163 // Propagate fast-math-flags from phi node to its replacement select.
2165 BI->getCondition(), BB1V, BB2V,
2166 isa<FPMathOperator>(PN) ? &PN : nullptr,
2167 BB1V->getName() + "." + BB2V->getName(), BI));
2168 }
2169
2170 // Make the PHI node use the select for all incoming values for BB1/BB2
2171 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2172 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
2173 PN.setIncomingValue(i, SI);
2174 }
2175 }
2176 }
2177
2179
2180 // Update any PHI nodes in our new successors.
2181 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
2182 for (BasicBlock *Succ : successors(BB1)) {
2183 addPredecessorToBlock(Succ, TIParent, BB1);
2184
2185 if (DTU && VisitedSuccs.insert(Succ).second)
2186 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
2187 }
2188
2189 if (DTU) {
2190 // TI might be a switch with multi-cases destination, so we need to care for
2191 // the duplication of successors.
2192 for (BasicBlock *Succ : UniqueSuccessors)
2193 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
2194 }
2195
2197 if (DTU)
2198 DTU->applyUpdates(Updates);
2199 return Changed;
2200}
2201
2202// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
2203// into variables.
2205 int OpIdx) {
2206 // Divide/Remainder by constant is typically much cheaper than by variable.
2207 if (I->isIntDivRem())
2208 return OpIdx != 1;
2209 return !isa<IntrinsicInst>(I);
2210}
2211
2212// All instructions in Insts belong to different blocks that all unconditionally
2213// branch to a common successor. Analyze each instruction and return true if it
2214// would be possible to sink them into their successor, creating one common
2215// instruction instead. For every value that would be required to be provided by
2216// PHI node (because an operand varies in each input block), add to PHIOperands.
2219 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
2220 // Prune out obviously bad instructions to move. Each instruction must have
2221 // the same number of uses, and we check later that the uses are consistent.
2222 std::optional<unsigned> NumUses;
2223 for (auto *I : Insts) {
2224 // These instructions may change or break semantics if moved.
2225 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
2226 I->getType()->isTokenTy())
2227 return false;
2228
2229 // Do not try to sink an instruction in an infinite loop - it can cause
2230 // this algorithm to infinite loop.
2231 if (I->getParent()->getSingleSuccessor() == I->getParent())
2232 return false;
2233
2234 // Conservatively return false if I is an inline-asm instruction. Sinking
2235 // and merging inline-asm instructions can potentially create arguments
2236 // that cannot satisfy the inline-asm constraints.
2237 // If the instruction has nomerge or convergent attribute, return false.
2238 if (const auto *C = dyn_cast<CallBase>(I))
2239 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
2240 return false;
2241
2242 if (!NumUses)
2243 NumUses = I->getNumUses();
2244 else if (NumUses != I->getNumUses())
2245 return false;
2246 }
2247
2248 const Instruction *I0 = Insts.front();
2249 const auto I0MMRA = MMRAMetadata(*I0);
2250 for (auto *I : Insts) {
2251 if (!I->isSameOperationAs(I0, Instruction::CompareUsingIntersectedAttrs))
2252 return false;
2253
2254 // Treat MMRAs conservatively. This pass can be quite aggressive and
2255 // could drop a lot of MMRAs otherwise.
2256 if (MMRAMetadata(*I) != I0MMRA)
2257 return false;
2258 }
2259
2260 // Uses must be consistent: If I0 is used in a phi node in the sink target,
2261 // then the other phi operands must match the instructions from Insts. This
2262 // also has to hold true for any phi nodes that would be created as a result
2263 // of sinking. Both of these cases are represented by PhiOperands.
2264 for (const Use &U : I0->uses()) {
2265 auto It = PHIOperands.find(&U);
2266 if (It == PHIOperands.end())
2267 // There may be uses in other blocks when sinking into a loop header.
2268 return false;
2269 if (!equal(Insts, It->second))
2270 return false;
2271 }
2272
2273 // For calls to be sinkable, they must all be indirect, or have same callee.
2274 // I.e. if we have two direct calls to different callees, we don't want to
2275 // turn that into an indirect call. Likewise, if we have an indirect call,
2276 // and a direct call, we don't actually want to have a single indirect call.
2277 if (isa<CallBase>(I0)) {
2278 auto IsIndirectCall = [](const Instruction *I) {
2279 return cast<CallBase>(I)->isIndirectCall();
2280 };
2281 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
2282 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
2283 if (HaveIndirectCalls) {
2284 if (!AllCallsAreIndirect)
2285 return false;
2286 } else {
2287 // All callees must be identical.
2288 Value *Callee = nullptr;
2289 for (const Instruction *I : Insts) {
2290 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
2291 if (!Callee)
2292 Callee = CurrCallee;
2293 else if (Callee != CurrCallee)
2294 return false;
2295 }
2296 }
2297 }
2298
2299 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2300 Value *Op = I0->getOperand(OI);
2301 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2302 assert(I->getNumOperands() == I0->getNumOperands());
2303 return I->getOperand(OI) == I0->getOperand(OI);
2304 };
2305 if (!all_of(Insts, SameAsI0)) {
2306 auto CanReplaceOperand = [OI](const Instruction *I) {
2307 return canReplaceOperandWithVariable(I, OI);
2308 };
2310 !all_of(Insts, CanReplaceOperand))
2311 // We can't create a PHI from this operand.
2312 return false;
2313 auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
2314 for (auto *I : Insts)
2315 Ops.push_back(I->getOperand(OI));
2316 }
2317 }
2318 return true;
2319}
2320
2321// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2322// instruction of every block in Blocks to their common successor, commoning
2323// into one instruction.
2325 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
2326
2327 // canSinkInstructions returning true guarantees that every block has at
2328 // least one non-terminator instruction.
2330 for (auto *BB : Blocks) {
2331 Instruction *I = BB->getTerminator();
2332 I = I->getPrevNode();
2333 Insts.push_back(I);
2334 }
2335
2336 // We don't need to do any more checking here; canSinkInstructions should
2337 // have done it all for us.
2338 SmallVector<Value*, 4> NewOperands;
2339 Instruction *I0 = Insts.front();
2340 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2341 // This check is different to that in canSinkInstructions. There, we
2342 // cared about the global view once simplifycfg (and instcombine) have
2343 // completed - it takes into account PHIs that become trivially
2344 // simplifiable. However here we need a more local view; if an operand
2345 // differs we create a PHI and rely on instcombine to clean up the very
2346 // small mess we may make.
2347 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2348 return I->getOperand(O) != I0->getOperand(O);
2349 });
2350 if (!NeedPHI) {
2351 NewOperands.push_back(I0->getOperand(O));
2352 continue;
2353 }
2354
2355 // Create a new PHI in the successor block and populate it.
2356 auto *Op = I0->getOperand(O);
2357 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2358 auto *PN =
2359 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2360 PN->insertBefore(BBEnd->begin());
2361 for (auto *I : Insts)
2362 PN->addIncoming(I->getOperand(O), I->getParent());
2363 NewOperands.push_back(PN);
2364 }
2365
2366 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2367 // and move it to the start of the successor block.
2368 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2369 I0->getOperandUse(O).set(NewOperands[O]);
2370
2371 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2372
2373 // Update metadata and IR flags, and merge debug locations.
2374 for (auto *I : Insts)
2375 if (I != I0) {
2376 // The debug location for the "common" instruction is the merged locations
2377 // of all the commoned instructions. We start with the original location
2378 // of the "common" instruction and iteratively merge each location in the
2379 // loop below.
2380 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2381 // However, as N-way merge for CallInst is rare, so we use simplified API
2382 // instead of using complex API for N-way merge.
2383 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2384 combineMetadataForCSE(I0, I, true);
2385 I0->andIRFlags(I);
2386 if (auto *CB = dyn_cast<CallBase>(I0)) {
2387 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I));
2388 assert(Success && "We should not be trying to sink callbases "
2389 "with non-intersectable attributes");
2390 // For NDEBUG Compile.
2391 (void)Success;
2392 }
2393 }
2394
2395 for (User *U : make_early_inc_range(I0->users())) {
2396 // canSinkLastInstruction checked that all instructions are only used by
2397 // phi nodes in a way that allows replacing the phi node with the common
2398 // instruction.
2399 auto *PN = cast<PHINode>(U);
2400 PN->replaceAllUsesWith(I0);
2401 PN->eraseFromParent();
2402 }
2403
2404 // Finally nuke all instructions apart from the common instruction.
2405 for (auto *I : Insts) {
2406 if (I == I0)
2407 continue;
2408 // The remaining uses are debug users, replace those with the common inst.
2409 // In most (all?) cases this just introduces a use-before-def.
2410 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2411 I->replaceAllUsesWith(I0);
2412 I->eraseFromParent();
2413 }
2414}
2415
2416/// Check whether BB's predecessors end with unconditional branches. If it is
2417/// true, sink any common code from the predecessors to BB.
2419 DomTreeUpdater *DTU) {
2420 // We support two situations:
2421 // (1) all incoming arcs are unconditional
2422 // (2) there are non-unconditional incoming arcs
2423 //
2424 // (2) is very common in switch defaults and
2425 // else-if patterns;
2426 //
2427 // if (a) f(1);
2428 // else if (b) f(2);
2429 //
2430 // produces:
2431 //
2432 // [if]
2433 // / \
2434 // [f(1)] [if]
2435 // | | \
2436 // | | |
2437 // | [f(2)]|
2438 // \ | /
2439 // [ end ]
2440 //
2441 // [end] has two unconditional predecessor arcs and one conditional. The
2442 // conditional refers to the implicit empty 'else' arc. This conditional
2443 // arc can also be caused by an empty default block in a switch.
2444 //
2445 // In this case, we attempt to sink code from all *unconditional* arcs.
2446 // If we can sink instructions from these arcs (determined during the scan
2447 // phase below) we insert a common successor for all unconditional arcs and
2448 // connect that to [end], to enable sinking:
2449 //
2450 // [if]
2451 // / \
2452 // [x(1)] [if]
2453 // | | \
2454 // | | \
2455 // | [x(2)] |
2456 // \ / |
2457 // [sink.split] |
2458 // \ /
2459 // [ end ]
2460 //
2461 SmallVector<BasicBlock*,4> UnconditionalPreds;
2462 bool HaveNonUnconditionalPredecessors = false;
2463 for (auto *PredBB : predecessors(BB)) {
2464 auto *PredBr = dyn_cast<UncondBrInst>(PredBB->getTerminator());
2465 if (PredBr)
2466 UnconditionalPreds.push_back(PredBB);
2467 else
2468 HaveNonUnconditionalPredecessors = true;
2469 }
2470 if (UnconditionalPreds.size() < 2)
2471 return false;
2472
2473 // We take a two-step approach to tail sinking. First we scan from the end of
2474 // each block upwards in lockstep. If the n'th instruction from the end of each
2475 // block can be sunk, those instructions are added to ValuesToSink and we
2476 // carry on. If we can sink an instruction but need to PHI-merge some operands
2477 // (because they're not identical in each instruction) we add these to
2478 // PHIOperands.
2479 // We prepopulate PHIOperands with the phis that already exist in BB.
2481 for (PHINode &PN : BB->phis()) {
2483 for (const Use &U : PN.incoming_values())
2484 IncomingVals.insert({PN.getIncomingBlock(U), &U});
2485 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2486 for (BasicBlock *Pred : UnconditionalPreds)
2487 Ops.push_back(*IncomingVals[Pred]);
2488 }
2489
2490 int ScanIdx = 0;
2491 SmallPtrSet<Value*,4> InstructionsToSink;
2492 LockstepReverseIterator<true> LRI(UnconditionalPreds);
2493 while (LRI.isValid() &&
2494 canSinkInstructions(*LRI, PHIOperands)) {
2495 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2496 << "\n");
2497 InstructionsToSink.insert_range(*LRI);
2498 ++ScanIdx;
2499 --LRI;
2500 }
2501
2502 // If no instructions can be sunk, early-return.
2503 if (ScanIdx == 0)
2504 return false;
2505
2506 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2507
2508 if (!followedByDeoptOrUnreachable) {
2509 // Check whether this is the pointer operand of a load/store.
2510 auto IsMemOperand = [](Use &U) {
2511 auto *I = cast<Instruction>(U.getUser());
2512 if (isa<LoadInst>(I))
2513 return U.getOperandNo() == LoadInst::getPointerOperandIndex();
2514 if (isa<StoreInst>(I))
2515 return U.getOperandNo() == StoreInst::getPointerOperandIndex();
2516 return false;
2517 };
2518
2519 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2520 // actually sink before encountering instruction that is unprofitable to
2521 // sink?
2522 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator<true> &LRI) {
2523 unsigned NumPHIInsts = 0;
2524 for (Use &U : (*LRI)[0]->operands()) {
2525 auto It = PHIOperands.find(&U);
2526 if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2527 return InstructionsToSink.contains(V);
2528 })) {
2529 ++NumPHIInsts;
2530 // Do not separate a load/store from the gep producing the address.
2531 // The gep can likely be folded into the load/store as an addressing
2532 // mode. Additionally, a load of a gep is easier to analyze than a
2533 // load of a phi.
2534 if (IsMemOperand(U) &&
2535 any_of(It->second, [](Value *V) { return isa<GEPOperator>(V); }))
2536 return false;
2537 // FIXME: this check is overly optimistic. We may end up not sinking
2538 // said instruction, due to the very same profitability check.
2539 // See @creating_too_many_phis in sink-common-code.ll.
2540 }
2541 }
2542 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2543 return NumPHIInsts <= 1;
2544 };
2545
2546 // We've determined that we are going to sink last ScanIdx instructions,
2547 // and recorded them in InstructionsToSink. Now, some instructions may be
2548 // unprofitable to sink. But that determination depends on the instructions
2549 // that we are going to sink.
2550
2551 // First, forward scan: find the first instruction unprofitable to sink,
2552 // recording all the ones that are profitable to sink.
2553 // FIXME: would it be better, after we detect that not all are profitable.
2554 // to either record the profitable ones, or erase the unprofitable ones?
2555 // Maybe we need to choose (at runtime) the one that will touch least
2556 // instrs?
2557 LRI.reset();
2558 int Idx = 0;
2559 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2560 while (Idx < ScanIdx) {
2561 if (!ProfitableToSinkInstruction(LRI)) {
2562 // Too many PHIs would be created.
2563 LLVM_DEBUG(
2564 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2565 break;
2566 }
2567 InstructionsProfitableToSink.insert_range(*LRI);
2568 --LRI;
2569 ++Idx;
2570 }
2571
2572 // If no instructions can be sunk, early-return.
2573 if (Idx == 0)
2574 return false;
2575
2576 // Did we determine that (only) some instructions are unprofitable to sink?
2577 if (Idx < ScanIdx) {
2578 // Okay, some instructions are unprofitable.
2579 ScanIdx = Idx;
2580 InstructionsToSink = InstructionsProfitableToSink;
2581
2582 // But, that may make other instructions unprofitable, too.
2583 // So, do a backward scan, do any earlier instructions become
2584 // unprofitable?
2585 assert(
2586 !ProfitableToSinkInstruction(LRI) &&
2587 "We already know that the last instruction is unprofitable to sink");
2588 ++LRI;
2589 --Idx;
2590 while (Idx >= 0) {
2591 // If we detect that an instruction becomes unprofitable to sink,
2592 // all earlier instructions won't be sunk either,
2593 // so preemptively keep InstructionsProfitableToSink in sync.
2594 // FIXME: is this the most performant approach?
2595 for (auto *I : *LRI)
2596 InstructionsProfitableToSink.erase(I);
2597 if (!ProfitableToSinkInstruction(LRI)) {
2598 // Everything starting with this instruction won't be sunk.
2599 ScanIdx = Idx;
2600 InstructionsToSink = InstructionsProfitableToSink;
2601 }
2602 ++LRI;
2603 --Idx;
2604 }
2605 }
2606
2607 // If no instructions can be sunk, early-return.
2608 if (ScanIdx == 0)
2609 return false;
2610 }
2611
2612 bool Changed = false;
2613
2614 if (HaveNonUnconditionalPredecessors) {
2615 if (!followedByDeoptOrUnreachable) {
2616 // It is always legal to sink common instructions from unconditional
2617 // predecessors. However, if not all predecessors are unconditional,
2618 // this transformation might be pessimizing. So as a rule of thumb,
2619 // don't do it unless we'd sink at least one non-speculatable instruction.
2620 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2621 LRI.reset();
2622 int Idx = 0;
2623 bool Profitable = false;
2624 while (Idx < ScanIdx) {
2625 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2626 Profitable = true;
2627 break;
2628 }
2629 --LRI;
2630 ++Idx;
2631 }
2632 if (!Profitable)
2633 return false;
2634 }
2635
2636 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2637 // We have a conditional edge and we're going to sink some instructions.
2638 // Insert a new block postdominating all blocks we're going to sink from.
2639 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2640 // Edges couldn't be split.
2641 return false;
2642 Changed = true;
2643 }
2644
2645 // Now that we've analyzed all potential sinking candidates, perform the
2646 // actual sink. We iteratively sink the last non-terminator of the source
2647 // blocks into their common successor unless doing so would require too
2648 // many PHI instructions to be generated (currently only one PHI is allowed
2649 // per sunk instruction).
2650 //
2651 // We can use InstructionsToSink to discount values needing PHI-merging that will
2652 // actually be sunk in a later iteration. This allows us to be more
2653 // aggressive in what we sink. This does allow a false positive where we
2654 // sink presuming a later value will also be sunk, but stop half way through
2655 // and never actually sink it which means we produce more PHIs than intended.
2656 // This is unlikely in practice though.
2657 int SinkIdx = 0;
2658 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2659 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2660 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2661 << "\n");
2662
2663 // Because we've sunk every instruction in turn, the current instruction to
2664 // sink is always at index 0.
2665 LRI.reset();
2666
2667 sinkLastInstruction(UnconditionalPreds);
2668 NumSinkCommonInstrs++;
2669 Changed = true;
2670 }
2671 if (SinkIdx != 0)
2672 ++NumSinkCommonCode;
2673 return Changed;
2674}
2675
2676namespace {
2677
2678struct CompatibleSets {
2679 using SetTy = SmallVector<InvokeInst *, 2>;
2680
2682
2683 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2684
2685 SetTy &getCompatibleSet(InvokeInst *II);
2686
2687 void insert(InvokeInst *II);
2688};
2689
2690CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2691 // Perform a linear scan over all the existing sets, see if the new `invoke`
2692 // is compatible with any particular set. Since we know that all the `invokes`
2693 // within a set are compatible, only check the first `invoke` in each set.
2694 // WARNING: at worst, this has quadratic complexity.
2695 for (CompatibleSets::SetTy &Set : Sets) {
2696 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2697 return Set;
2698 }
2699
2700 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2701 return Sets.emplace_back();
2702}
2703
2704void CompatibleSets::insert(InvokeInst *II) {
2705 getCompatibleSet(II).emplace_back(II);
2706}
2707
2708bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2709 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2710
2711 // Can we theoretically merge these `invoke`s?
2712 auto IsIllegalToMerge = [](InvokeInst *II) {
2713 return II->cannotMerge() || II->isInlineAsm();
2714 };
2715 if (any_of(Invokes, IsIllegalToMerge))
2716 return false;
2717
2718 // Either both `invoke`s must be direct,
2719 // or both `invoke`s must be indirect.
2720 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2721 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2722 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2723 if (HaveIndirectCalls) {
2724 if (!AllCallsAreIndirect)
2725 return false;
2726 } else {
2727 // All callees must be identical.
2728 Value *Callee = nullptr;
2729 for (InvokeInst *II : Invokes) {
2730 Value *CurrCallee = II->getCalledOperand();
2731 assert(CurrCallee && "There is always a called operand.");
2732 if (!Callee)
2733 Callee = CurrCallee;
2734 else if (Callee != CurrCallee)
2735 return false;
2736 }
2737 }
2738
2739 // Either both `invoke`s must not have a normal destination,
2740 // or both `invoke`s must have a normal destination,
2741 auto HasNormalDest = [](InvokeInst *II) {
2742 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2743 };
2744 if (any_of(Invokes, HasNormalDest)) {
2745 // Do not merge `invoke` that does not have a normal destination with one
2746 // that does have a normal destination, even though doing so would be legal.
2747 if (!all_of(Invokes, HasNormalDest))
2748 return false;
2749
2750 // All normal destinations must be identical.
2751 BasicBlock *NormalBB = nullptr;
2752 for (InvokeInst *II : Invokes) {
2753 BasicBlock *CurrNormalBB = II->getNormalDest();
2754 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2755 if (!NormalBB)
2756 NormalBB = CurrNormalBB;
2757 else if (NormalBB != CurrNormalBB)
2758 return false;
2759 }
2760
2761 // In the normal destination, the incoming values for these two `invoke`s
2762 // must be compatible.
2763 SmallPtrSet<Value *, 16> EquivalenceSet(llvm::from_range, Invokes);
2765 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2766 &EquivalenceSet))
2767 return false;
2768 }
2769
2770#ifndef NDEBUG
2771 // All unwind destinations must be identical.
2772 // We know that because we have started from said unwind destination.
2773 BasicBlock *UnwindBB = nullptr;
2774 for (InvokeInst *II : Invokes) {
2775 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2776 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2777 if (!UnwindBB)
2778 UnwindBB = CurrUnwindBB;
2779 else
2780 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2781 }
2782#endif
2783
2784 // In the unwind destination, the incoming values for these two `invoke`s
2785 // must be compatible.
2787 Invokes.front()->getUnwindDest(),
2788 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2789 return false;
2790
2791 // Ignoring arguments, these `invoke`s must be identical,
2792 // including operand bundles.
2793 const InvokeInst *II0 = Invokes.front();
2794 for (auto *II : Invokes.drop_front())
2795 if (!II->isSameOperationAs(II0, Instruction::CompareUsingIntersectedAttrs))
2796 return false;
2797
2798 // Can we theoretically form the data operands for the merged `invoke`?
2799 auto IsIllegalToMergeArguments = [](auto Ops) {
2800 Use &U0 = std::get<0>(Ops);
2801 Use &U1 = std::get<1>(Ops);
2802 if (U0 == U1)
2803 return false;
2805 U0.getOperandNo());
2806 };
2807 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2808 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2809 IsIllegalToMergeArguments))
2810 return false;
2811
2812 return true;
2813}
2814
2815} // namespace
2816
2817// Merge all invokes in the provided set, all of which are compatible
2818// as per the `CompatibleSets::shouldBelongToSameSet()`.
2820 DomTreeUpdater *DTU) {
2821 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2822
2824 if (DTU)
2825 Updates.reserve(2 + 3 * Invokes.size());
2826
2827 bool HasNormalDest =
2828 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2829
2830 // Clone one of the invokes into a new basic block.
2831 // Since they are all compatible, it doesn't matter which invoke is cloned.
2832 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2833 InvokeInst *II0 = Invokes.front();
2834 BasicBlock *II0BB = II0->getParent();
2835 BasicBlock *InsertBeforeBlock =
2836 II0->getParent()->getIterator()->getNextNode();
2837 Function *Func = II0BB->getParent();
2838 LLVMContext &Ctx = II0->getContext();
2839
2840 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2841 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2842
2843 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2844 // NOTE: all invokes have the same attributes, so no handling needed.
2845 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2846
2847 if (!HasNormalDest) {
2848 // This set does not have a normal destination,
2849 // so just form a new block with unreachable terminator.
2850 BasicBlock *MergedNormalDest = BasicBlock::Create(
2851 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2852 auto *UI = new UnreachableInst(Ctx, MergedNormalDest);
2853 UI->setDebugLoc(DebugLoc::getTemporary());
2854 MergedInvoke->setNormalDest(MergedNormalDest);
2855 }
2856
2857 // The unwind destination, however, remainds identical for all invokes here.
2858
2859 return MergedInvoke;
2860 }();
2861
2862 if (DTU) {
2863 // Predecessor blocks that contained these invokes will now branch to
2864 // the new block that contains the merged invoke, ...
2865 for (InvokeInst *II : Invokes)
2866 Updates.push_back(
2867 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2868
2869 // ... which has the new `unreachable` block as normal destination,
2870 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2871 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2872 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2873 SuccBBOfMergedInvoke});
2874
2875 // Since predecessor blocks now unconditionally branch to a new block,
2876 // they no longer branch to their original successors.
2877 for (InvokeInst *II : Invokes)
2878 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2879 Updates.push_back(
2880 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2881 }
2882
2883 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2884
2885 // Form the merged operands for the merged invoke.
2886 for (Use &U : MergedInvoke->operands()) {
2887 // Only PHI together the indirect callees and data operands.
2888 if (MergedInvoke->isCallee(&U)) {
2889 if (!IsIndirectCall)
2890 continue;
2891 } else if (!MergedInvoke->isDataOperand(&U))
2892 continue;
2893
2894 // Don't create trivial PHI's with all-identical incoming values.
2895 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2896 return II->getOperand(U.getOperandNo()) != U.get();
2897 });
2898 if (!NeedPHI)
2899 continue;
2900
2901 // Form a PHI out of all the data ops under this index.
2903 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
2904 for (InvokeInst *II : Invokes)
2905 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2906
2907 U.set(PN);
2908 }
2909
2910 // We've ensured that each PHI node has compatible (identical) incoming values
2911 // when coming from each of the `invoke`s in the current merge set,
2912 // so update the PHI nodes accordingly.
2913 for (BasicBlock *Succ : successors(MergedInvoke))
2914 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2915 /*ExistPred=*/Invokes.front()->getParent());
2916
2917 // And finally, replace the original `invoke`s with an unconditional branch
2918 // to the block with the merged `invoke`. Also, give that merged `invoke`
2919 // the merged debugloc of all the original `invoke`s.
2920 DILocation *MergedDebugLoc = nullptr;
2921 for (InvokeInst *II : Invokes) {
2922 // Compute the debug location common to all the original `invoke`s.
2923 if (!MergedDebugLoc)
2924 MergedDebugLoc = II->getDebugLoc();
2925 else
2926 MergedDebugLoc =
2927 DebugLoc::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2928
2929 // And replace the old `invoke` with an unconditionally branch
2930 // to the block with the merged `invoke`.
2931 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2932 OrigSuccBB->removePredecessor(II->getParent());
2933 auto *BI = UncondBrInst::Create(MergedInvoke->getParent(), II->getParent());
2934 // The unconditional branch is part of the replacement for the original
2935 // invoke, so should use its DebugLoc.
2936 BI->setDebugLoc(II->getDebugLoc());
2937 bool Success = MergedInvoke->tryIntersectAttributes(II);
2938 assert(Success && "Merged invokes with incompatible attributes");
2939 // For NDEBUG Compile
2940 (void)Success;
2941 II->replaceAllUsesWith(MergedInvoke);
2942 II->eraseFromParent();
2943 ++NumInvokesMerged;
2944 }
2945 MergedInvoke->setDebugLoc(MergedDebugLoc);
2946 ++NumInvokeSetsFormed;
2947
2948 if (DTU)
2949 DTU->applyUpdates(Updates);
2950}
2951
2952/// If this block is a `landingpad` exception handling block, categorize all
2953/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2954/// being "mergeable" together, and then merge invokes in each set together.
2955///
2956/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2957/// [...] [...]
2958/// | |
2959/// [invoke0] [invoke1]
2960/// / \ / \
2961/// [cont0] [landingpad] [cont1]
2962/// to:
2963/// [...] [...]
2964/// \ /
2965/// [invoke]
2966/// / \
2967/// [cont] [landingpad]
2968///
2969/// But of course we can only do that if the invokes share the `landingpad`,
2970/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2971/// and the invoked functions are "compatible".
2974 return false;
2975
2976 bool Changed = false;
2977
2978 // FIXME: generalize to all exception handling blocks?
2979 if (!BB->isLandingPad())
2980 return Changed;
2981
2982 CompatibleSets Grouper;
2983
2984 // Record all the predecessors of this `landingpad`. As per verifier,
2985 // the only allowed predecessor is the unwind edge of an `invoke`.
2986 // We want to group "compatible" `invokes` into the same set to be merged.
2987 for (BasicBlock *PredBB : predecessors(BB))
2988 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2989
2990 // And now, merge `invoke`s that were grouped togeter.
2991 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2992 if (Invokes.size() < 2)
2993 continue;
2994 Changed = true;
2995 mergeCompatibleInvokesImpl(Invokes, DTU);
2996 }
2997
2998 return Changed;
2999}
3000
3001namespace {
3002/// Track ephemeral values, which should be ignored for cost-modelling
3003/// purposes. Requires walking instructions in reverse order.
3004class EphemeralValueTracker {
3005 SmallPtrSet<const Instruction *, 32> EphValues;
3006
3007 bool isEphemeral(const Instruction *I) {
3008 if (isa<AssumeInst>(I))
3009 return true;
3010 return !I->mayHaveSideEffects() && !I->isTerminator() &&
3011 all_of(I->users(), [&](const User *U) {
3012 return EphValues.count(cast<Instruction>(U));
3013 });
3014 }
3015
3016public:
3017 bool track(const Instruction *I) {
3018 if (isEphemeral(I)) {
3019 EphValues.insert(I);
3020 return true;
3021 }
3022 return false;
3023 }
3024
3025 bool contains(const Instruction *I) const { return EphValues.contains(I); }
3026};
3027} // namespace
3028
3029/// Determine if we can hoist sink a sole store instruction out of a
3030/// conditional block.
3031///
3032/// We are looking for code like the following:
3033/// BrBB:
3034/// store i32 %add, i32* %arrayidx2
3035/// ... // No other stores or function calls (we could be calling a memory
3036/// ... // function).
3037/// %cmp = icmp ult %x, %y
3038/// br i1 %cmp, label %EndBB, label %ThenBB
3039/// ThenBB:
3040/// store i32 %add5, i32* %arrayidx2
3041/// br label EndBB
3042/// EndBB:
3043/// ...
3044/// We are going to transform this into:
3045/// BrBB:
3046/// store i32 %add, i32* %arrayidx2
3047/// ... //
3048/// %cmp = icmp ult %x, %y
3049/// %add.add5 = select i1 %cmp, i32 %add, %add5
3050/// store i32 %add.add5, i32* %arrayidx2
3051/// ...
3052///
3053/// \return The pointer to the value of the previous store if the store can be
3054/// hoisted into the predecessor block. 0 otherwise.
3056 BasicBlock *StoreBB, BasicBlock *EndBB) {
3057 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
3058 if (!StoreToHoist)
3059 return nullptr;
3060
3061 // Volatile or atomic.
3062 if (!StoreToHoist->isSimple())
3063 return nullptr;
3064
3065 Value *StorePtr = StoreToHoist->getPointerOperand();
3066 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
3067
3068 // Look for a store to the same pointer in BrBB.
3069 unsigned MaxNumInstToLookAt = 9;
3070 // Skip pseudo probe intrinsic calls which are not really killing any memory
3071 // accesses.
3072 for (Instruction &CurI : reverse(*BrBB)) {
3073 if (!MaxNumInstToLookAt)
3074 break;
3075 --MaxNumInstToLookAt;
3076
3077 if (isa<PseudoProbeInst>(CurI))
3078 continue;
3079
3080 // Could be calling an instruction that affects memory like free().
3081 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
3082 return nullptr;
3083
3084 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
3085 // Found the previous store to same location and type. Make sure it is
3086 // simple, to avoid introducing a spurious non-atomic write after an
3087 // atomic write.
3088 if (SI->getPointerOperand() == StorePtr &&
3089 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
3090 SI->getAlign() >= StoreToHoist->getAlign())
3091 // Found the previous store, return its value operand.
3092 return SI->getValueOperand();
3093 return nullptr; // Unknown store.
3094 }
3095
3096 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
3097 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
3098 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
3099 Value *Obj = getUnderlyingObject(StorePtr);
3100 bool ExplicitlyDereferenceableOnly;
3101 // The dereferenceability query here is only required to satisfy the
3102 // writable contract, actual dereferenceability is proven by the
3103 // presence of an access. As such, we can ignore frees.
3104 if (isWritableObject(Obj, ExplicitlyDereferenceableOnly) &&
3107 .WithoutRet) &&
3108 (!ExplicitlyDereferenceableOnly ||
3109 isDereferenceablePointer(StorePtr, StoreTy, LI->getDataLayout(),
3110 /*IgnoreFree=*/true))) {
3111 // Found a previous load, return it.
3112 return LI;
3113 }
3114 }
3115 // The load didn't work out, but we may still find a store.
3116 }
3117 }
3118
3119 return nullptr;
3120}
3121
3122/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
3123/// converted to selects.
3125 BasicBlock *EndBB,
3126 unsigned &SpeculatedInstructions,
3127 InstructionCost &Cost,
3128 const TargetTransformInfo &TTI) {
3130 BB->getParent()->hasMinSize()
3133
3134 bool HaveRewritablePHIs = false;
3135 for (PHINode &PN : EndBB->phis()) {
3136 Value *OrigV = PN.getIncomingValueForBlock(BB);
3137 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
3138
3139 // FIXME: Try to remove some of the duplication with
3140 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
3141 if (ThenV == OrigV)
3142 continue;
3143
3144 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(),
3145 CmpInst::makeCmpResultType(PN.getType()),
3147
3148 // Don't convert to selects if we could remove undefined behavior instead.
3149 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
3151 return false;
3152
3153 HaveRewritablePHIs = true;
3154 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
3155 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
3156 if (!OrigCE && !ThenCE)
3157 continue; // Known cheap (FIXME: Maybe not true for aggregates).
3158
3159 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
3160 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
3161 InstructionCost MaxCost =
3163 if (OrigCost + ThenCost > MaxCost)
3164 return false;
3165
3166 // Account for the cost of an unfolded ConstantExpr which could end up
3167 // getting expanded into Instructions.
3168 // FIXME: This doesn't account for how many operations are combined in the
3169 // constant expression.
3170 ++SpeculatedInstructions;
3171 if (SpeculatedInstructions > 1)
3172 return false;
3173 }
3174
3175 return HaveRewritablePHIs;
3176}
3177
3179 std::optional<bool> Invert,
3180 const TargetTransformInfo &TTI) {
3181 // If the branch is non-unpredictable, and is predicted to *not* branch to
3182 // the `then` block, then avoid speculating it.
3183 if (BI->getMetadata(LLVMContext::MD_unpredictable))
3184 return true;
3185
3186 uint64_t TWeight, FWeight;
3187 if (!extractBranchWeights(*BI, TWeight, FWeight) || (TWeight + FWeight) == 0)
3188 return true;
3189
3190 if (!Invert.has_value())
3191 return false;
3192
3193 uint64_t EndWeight = *Invert ? TWeight : FWeight;
3194 BranchProbability BIEndProb =
3195 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
3196 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3197 return BIEndProb < Likely;
3198}
3199
3200/// Speculate a conditional basic block flattening the CFG.
3201///
3202/// Note that this is a very risky transform currently. Speculating
3203/// instructions like this is most often not desirable. Instead, there is an MI
3204/// pass which can do it with full awareness of the resource constraints.
3205/// However, some cases are "obvious" and we should do directly. An example of
3206/// this is speculating a single, reasonably cheap instruction.
3207///
3208/// There is only one distinct advantage to flattening the CFG at the IR level:
3209/// it makes very common but simplistic optimizations such as are common in
3210/// instcombine and the DAG combiner more powerful by removing CFG edges and
3211/// modeling their effects with easier to reason about SSA value graphs.
3212///
3213///
3214/// An illustration of this transform is turning this IR:
3215/// \code
3216/// BB:
3217/// %cmp = icmp ult %x, %y
3218/// br i1 %cmp, label %EndBB, label %ThenBB
3219/// ThenBB:
3220/// %sub = sub %x, %y
3221/// br label BB2
3222/// EndBB:
3223/// %phi = phi [ %sub, %ThenBB ], [ 0, %BB ]
3224/// ...
3225/// \endcode
3226///
3227/// Into this IR:
3228/// \code
3229/// BB:
3230/// %cmp = icmp ult %x, %y
3231/// %sub = sub %x, %y
3232/// %cond = select i1 %cmp, 0, %sub
3233/// ...
3234/// \endcode
3235///
3236/// \returns true if the conditional block is removed.
3237bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
3238 BasicBlock *ThenBB) {
3239 if (!Options.SpeculateBlocks)
3240 return false;
3241
3242 // Be conservative for now. FP select instruction can often be expensive.
3243 Value *BrCond = BI->getCondition();
3244 if (isa<FCmpInst>(BrCond))
3245 return false;
3246
3247 BasicBlock *BB = BI->getParent();
3248 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
3249 InstructionCost Budget =
3251
3252 // If ThenBB is actually on the false edge of the conditional branch, remember
3253 // to swap the select operands later.
3254 bool Invert = false;
3255 if (ThenBB != BI->getSuccessor(0)) {
3256 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3257 Invert = true;
3258 }
3259 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3260
3261 if (!isProfitableToSpeculate(BI, Invert, TTI))
3262 return false;
3263
3264 // Keep a count of how many times instructions are used within ThenBB when
3265 // they are candidates for sinking into ThenBB. Specifically:
3266 // - They are defined in BB, and
3267 // - They have no side effects, and
3268 // - All of their uses are in ThenBB.
3269 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3270
3271 SmallVector<Instruction *, 4> SpeculatedPseudoProbes;
3272
3273 unsigned SpeculatedInstructions = 0;
3274 bool HoistLoadsStores = Options.HoistLoadsStoresWithCondFaulting;
3275 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
3276 Value *SpeculatedStoreValue = nullptr;
3277 StoreInst *SpeculatedStore = nullptr;
3278 EphemeralValueTracker EphTracker;
3279 for (Instruction &I : reverse(drop_end(*ThenBB))) {
3280 // Skip pseudo probes. The consequence is we lose track of the branch
3281 // probability for ThenBB, which is fine since the optimization here takes
3282 // place regardless of the branch probability.
3283 if (isa<PseudoProbeInst>(I)) {
3284 // The probe should be deleted so that it will not be over-counted when
3285 // the samples collected on the non-conditional path are counted towards
3286 // the conditional path. We leave it for the counts inference algorithm to
3287 // figure out a proper count for an unknown probe.
3288 SpeculatedPseudoProbes.push_back(&I);
3289 continue;
3290 }
3291
3292 // Ignore ephemeral values, they will be dropped by the transform.
3293 if (EphTracker.track(&I))
3294 continue;
3295
3296 // Only speculatively execute a single instruction (not counting the
3297 // terminator) for now.
3298 bool IsSafeCheapLoadStore = HoistLoadsStores &&
3300 SpeculatedConditionalLoadsStores.size() <
3302 // Not count load/store into cost if target supports conditional faulting
3303 // b/c it's cheap to speculate it.
3304 if (IsSafeCheapLoadStore)
3305 SpeculatedConditionalLoadsStores.push_back(&I);
3306 else
3307 ++SpeculatedInstructions;
3308
3309 if (SpeculatedInstructions > 1)
3310 return false;
3311
3312 // Don't hoist the instruction if it's unsafe or expensive.
3313 if (!IsSafeCheapLoadStore &&
3315 !(HoistCondStores && !SpeculatedStoreValue &&
3316 (SpeculatedStoreValue =
3317 isSafeToSpeculateStore(&I, BB, ThenBB, EndBB))))
3318 return false;
3319 if (!IsSafeCheapLoadStore && !SpeculatedStoreValue &&
3322 return false;
3323
3324 // Store the store speculation candidate.
3325 if (!SpeculatedStore && SpeculatedStoreValue)
3326 SpeculatedStore = cast<StoreInst>(&I);
3327
3328 // Do not hoist the instruction if any of its operands are defined but not
3329 // used in BB. The transformation will prevent the operand from
3330 // being sunk into the use block.
3331 for (Use &Op : I.operands()) {
3333 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3334 continue; // Not a candidate for sinking.
3335
3336 ++SinkCandidateUseCounts[OpI];
3337 }
3338 }
3339
3340 // Consider any sink candidates which are only used in ThenBB as costs for
3341 // speculation. Note, while we iterate over a DenseMap here, we are summing
3342 // and so iteration order isn't significant.
3343 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3344 if (Inst->hasNUses(Count)) {
3345 ++SpeculatedInstructions;
3346 if (SpeculatedInstructions > 1)
3347 return false;
3348 }
3349
3350 // Check that we can insert the selects and that it's not too expensive to do
3351 // so.
3352 bool Convert =
3353 SpeculatedStore != nullptr || !SpeculatedConditionalLoadsStores.empty();
3355 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3356 SpeculatedInstructions, Cost, TTI);
3357 if (!Convert || Cost > Budget)
3358 return false;
3359
3360 // If we get here, we can hoist the instruction and if-convert.
3361 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3362
3363 Instruction *Sel = nullptr;
3364 // Insert a select of the value of the speculated store.
3365 if (SpeculatedStoreValue) {
3366 IRBuilder<NoFolder> Builder(BI);
3367 Value *OrigV = SpeculatedStore->getValueOperand();
3368 Value *TrueV = SpeculatedStore->getValueOperand();
3369 Value *FalseV = SpeculatedStoreValue;
3370 if (Invert)
3371 std::swap(TrueV, FalseV);
3372 Value *S = Builder.CreateSelect(
3373 BrCond, TrueV, FalseV, "spec.store.select", BI);
3374 Sel = cast<Instruction>(S);
3375 SpeculatedStore->setOperand(0, S);
3376 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3377 SpeculatedStore->getDebugLoc());
3378 // The value stored is still conditional, but the store itself is now
3379 // unconditionally executed, so we must be sure that any linked dbg.assign
3380 // intrinsics are tracking the new stored value (the result of the
3381 // select). If we don't, and the store were to be removed by another pass
3382 // (e.g. DSE), then we'd eventually end up emitting a location describing
3383 // the conditional value, unconditionally.
3384 //
3385 // === Before this transformation ===
3386 // pred:
3387 // store %one, %x.dest, !DIAssignID !1
3388 // dbg.assign %one, "x", ..., !1, ...
3389 // br %cond if.then
3390 //
3391 // if.then:
3392 // store %two, %x.dest, !DIAssignID !2
3393 // dbg.assign %two, "x", ..., !2, ...
3394 //
3395 // === After this transformation ===
3396 // pred:
3397 // store %one, %x.dest, !DIAssignID !1
3398 // dbg.assign %one, "x", ..., !1
3399 /// ...
3400 // %merge = select %cond, %two, %one
3401 // store %merge, %x.dest, !DIAssignID !2
3402 // dbg.assign %merge, "x", ..., !2
3403 for (DbgVariableRecord *DbgAssign :
3404 at::getDVRAssignmentMarkers(SpeculatedStore))
3405 if (llvm::is_contained(DbgAssign->location_ops(), OrigV))
3406 DbgAssign->replaceVariableLocationOp(OrigV, S);
3407 }
3408
3409 // Metadata can be dependent on the condition we are hoisting above.
3410 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3411 // to avoid making it appear as if the condition is a constant, which would
3412 // be misleading while debugging.
3413 // Similarly strip attributes that maybe dependent on condition we are
3414 // hoisting above.
3415 for (auto &I : make_early_inc_range(*ThenBB)) {
3416 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3417 I.dropLocation();
3418 }
3419 I.dropUBImplyingAttrsAndMetadata();
3420
3421 // Drop ephemeral values.
3422 if (EphTracker.contains(&I)) {
3423 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3424 I.eraseFromParent();
3425 }
3426 }
3427
3428 // Hoist the instructions.
3429 // Drop DbgVariableRecords attached to these instructions.
3430 for (auto &It : *ThenBB)
3431 for (DbgRecord &DR : make_early_inc_range(It.getDbgRecordRange()))
3432 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3433 // equivalent).
3434 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
3435 !DVR || !DVR->isDbgAssign())
3436 It.dropOneDbgRecord(&DR);
3437 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3438 std::prev(ThenBB->end()));
3439
3440 if (!SpeculatedConditionalLoadsStores.empty())
3441 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores, Invert,
3442 Sel);
3443
3444 // Insert selects and rewrite the PHI operands.
3445 IRBuilder<NoFolder> Builder(BI);
3446 for (PHINode &PN : EndBB->phis()) {
3447 unsigned OrigI = PN.getBasicBlockIndex(BB);
3448 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3449 Value *OrigV = PN.getIncomingValue(OrigI);
3450 Value *ThenV = PN.getIncomingValue(ThenI);
3451
3452 // Skip PHIs which are trivial.
3453 if (OrigV == ThenV)
3454 continue;
3455
3456 // Create a select whose true value is the speculatively executed value and
3457 // false value is the pre-existing value. Swap them if the branch
3458 // destinations were inverted.
3459 Value *TrueV = ThenV, *FalseV = OrigV;
3460 if (Invert)
3461 std::swap(TrueV, FalseV);
3462 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
3463 PN.setIncomingValue(OrigI, V);
3464 PN.setIncomingValue(ThenI, V);
3465 }
3466
3467 // Remove speculated pseudo probes.
3468 for (Instruction *I : SpeculatedPseudoProbes)
3469 I->eraseFromParent();
3470
3471 ++NumSpeculations;
3472 return true;
3473}
3474
3476
3477// Return false if number of blocks searched is too much.
3478static bool findReaching(BasicBlock *BB, BasicBlock *DefBB,
3479 BlocksSet &ReachesNonLocalUses) {
3480 if (BB == DefBB)
3481 return true;
3482 if (!ReachesNonLocalUses.insert(BB).second)
3483 return true;
3484
3485 if (ReachesNonLocalUses.size() > MaxJumpThreadingLiveBlocks)
3486 return false;
3487 for (BasicBlock *Pred : predecessors(BB))
3488 if (!findReaching(Pred, DefBB, ReachesNonLocalUses))
3489 return false;
3490 return true;
3491}
3492
3493/// Return true if we can thread a branch across this block.
3495 BlocksSet &NonLocalUseBlocks) {
3496 int Size = 0;
3497 EphemeralValueTracker EphTracker;
3498
3499 // Walk the loop in reverse so that we can identify ephemeral values properly
3500 // (values only feeding assumes).
3501 for (Instruction &I : reverse(*BB)) {
3502 // Can't fold blocks that contain noduplicate or convergent calls.
3503 if (CallInst *CI = dyn_cast<CallInst>(&I))
3504 if (CI->cannotDuplicate() || CI->isConvergent())
3505 return false;
3506
3507 // Ignore ephemeral values which are deleted during codegen.
3508 // We will delete Phis while threading, so Phis should not be accounted in
3509 // block's size.
3510 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3511 if (Size++ > MaxSmallBlockSize)
3512 return false; // Don't clone large BB's.
3513 }
3514
3515 // Record blocks with non-local uses of values defined in the current basic
3516 // block.
3517 for (User *U : I.users()) {
3519 BasicBlock *UsedInBB = UI->getParent();
3520 if (UsedInBB == BB) {
3521 if (isa<PHINode>(UI))
3522 return false;
3523 } else
3524 NonLocalUseBlocks.insert(UsedInBB);
3525 }
3526
3527 // Looks ok, continue checking.
3528 }
3529
3530 return true;
3531}
3532
3534 BasicBlock *To) {
3535 // Don't look past the block defining the value, we might get the value from
3536 // a previous loop iteration.
3537 auto *I = dyn_cast<Instruction>(V);
3538 if (I && I->getParent() == To)
3539 return nullptr;
3540
3541 // We know the value if the From block branches on it.
3542 auto *BI = dyn_cast<CondBrInst>(From->getTerminator());
3543 if (BI && BI->getCondition() == V &&
3544 BI->getSuccessor(0) != BI->getSuccessor(1))
3545 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3547
3548 return nullptr;
3549}
3550
3552 return CB->isConvergent() && !isa<ConvergenceControlInst>(CB) &&
3554}
3555
3557 BasicBlock *StopBB) {
3558 static constexpr unsigned MaxInstructionsToScan = 512;
3559
3560 // Walk predecessors of StopBB to find blocks that can reach it. Only
3561 // convergent calls on a cycle with StopBB matter - a convergent call on a
3562 // path to function exit cannot have its dynamic instance changed by
3563 // threading.
3564 SmallPtrSet<BasicBlock *, 8> CanReachStop;
3565 SmallPtrSet<BasicBlock *, 8> BlocksWithUncontrolledConvergentCalls;
3567 for (BasicBlock *Pred : predecessors(StopBB))
3568 Worklist.push_back(Pred);
3569
3570 // Cache blocks with relevant calls while building CanReachStop. This keeps
3571 // the instruction scan bounded without a separate block limit.
3572 unsigned NumScannedInstructions = 0;
3573 while (!Worklist.empty()) {
3574 BasicBlock *BB = Worklist.pop_back_val();
3575 if (BB == StopBB)
3576 continue;
3577 if (!CanReachStop.insert(BB).second)
3578 continue;
3579
3580 for (Instruction &I : *BB) {
3581 if (++NumScannedInstructions > MaxInstructionsToScan)
3582 return true;
3583 auto *CB = dyn_cast<CallBase>(&I);
3584 if (CB && isUncontrolledConvergentCall(CB)) {
3585 BlocksWithUncontrolledConvergentCalls.insert(BB);
3586 break;
3587 }
3588 }
3589
3590 append_range(Worklist, predecessors(BB));
3591 }
3592
3593 if (!CanReachStop.contains(From))
3594 return false;
3595
3597 Worklist.push_back(From);
3598
3599 while (!Worklist.empty()) {
3600 BasicBlock *BB = Worklist.pop_back_val();
3601 if (BB == StopBB || !CanReachStop.contains(BB))
3602 continue;
3603
3604 if (!Visited.insert(BB).second)
3605 continue;
3606
3607 if (BlocksWithUncontrolledConvergentCalls.contains(BB))
3608 return true;
3609
3610 append_range(Worklist, successors(BB));
3611 }
3612
3613 return false;
3614}
3615
3616/// If we have a conditional branch on something for which we know the constant
3617/// value in predecessors (e.g. a phi node in the current block), thread edges
3618/// from the predecessor to their ultimate destination.
3621 AssumptionCache *AC, const DataLayout &DL) {
3623 BasicBlock *BB = BI->getParent();
3624 Value *Cond = BI->getCondition();
3626 if (PN && PN->getParent() == BB) {
3627 // Degenerate case of a single entry PHI.
3628 if (PN->getNumIncomingValues() == 1) {
3630 return true;
3631 }
3632
3633 for (Use &U : PN->incoming_values())
3634 if (auto *CB = dyn_cast<ConstantInt>(U))
3635 KnownValues[CB].insert(PN->getIncomingBlock(U));
3636 } else {
3637 for (BasicBlock *Pred : predecessors(BB)) {
3638 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3639 KnownValues[CB].insert(Pred);
3640 }
3641 }
3642
3643 if (KnownValues.empty())
3644 return false;
3645
3646 // Now we know that this block has multiple preds and two succs.
3647 // Check that the block is small enough and record which non-local blocks use
3648 // values defined in the block.
3649
3650 BlocksSet NonLocalUseBlocks;
3651 BlocksSet ReachesNonLocalUseBlocks;
3652 if (!blockIsSimpleEnoughToThreadThrough(BB, NonLocalUseBlocks))
3653 return false;
3654
3655 // Jump-threading can only be done to destinations where no values defined
3656 // in BB are live.
3657
3658 // Quickly check if both destinations have uses. If so, jump-threading cannot
3659 // be done.
3660 if (NonLocalUseBlocks.contains(BI->getSuccessor(0)) &&
3661 NonLocalUseBlocks.contains(BI->getSuccessor(1)))
3662 return false;
3663
3664 // Search backward from NonLocalUseBlocks to find which blocks
3665 // reach non-local uses.
3666 for (BasicBlock *UseBB : NonLocalUseBlocks)
3667 // Give up if too many blocks are searched.
3668 if (!findReaching(UseBB, BB, ReachesNonLocalUseBlocks))
3669 return false;
3670
3671 for (const auto &Pair : KnownValues) {
3672 ConstantInt *CB = Pair.first;
3673 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3674 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3675
3676 // Okay, we now know that all edges from PredBB should be revectored to
3677 // branch to RealDest.
3678 if (RealDest == BB)
3679 continue; // Skip self loops.
3680
3681 // Skip if the predecessor's terminator is an indirect branch.
3682 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3683 return isa<IndirectBrInst>(PredBB->getTerminator());
3684 }))
3685 continue;
3686
3687 // Only revector to RealDest if no values defined in BB are live.
3688 if (ReachesNonLocalUseBlocks.contains(RealDest))
3689 continue;
3690
3691 // Threading through a branch can bypass a reconvergence point. If the
3692 // destination can execute an uncontrolled convergent operation before
3693 // returning to this block, this may change the dynamic instance of that
3694 // operation.
3695 if (TTI.hasBranchDivergence(BB->getParent()) &&
3697 continue;
3698
3699 LLVM_DEBUG({
3700 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3701 << " has value " << *Pair.first << " in predecessors:\n";
3702 for (const BasicBlock *PredBB : Pair.second)
3703 dbgs() << " " << PredBB->getName() << "\n";
3704 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3705 });
3706
3707 // Split the predecessors we are threading into a new edge block. We'll
3708 // clone the instructions into this block, and then redirect it to RealDest.
3709 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3710 if (!EdgeBB)
3711 continue;
3712
3713 // TODO: These just exist to reduce test diff, we can drop them if we like.
3714 EdgeBB->setName(RealDest->getName() + ".critedge");
3715 EdgeBB->moveBefore(RealDest);
3716
3717 // Update PHI nodes.
3718 addPredecessorToBlock(RealDest, EdgeBB, BB);
3719
3720 // BB may have instructions that are being threaded over. Clone these
3721 // instructions into EdgeBB. We know that there will be no uses of the
3722 // cloned instructions outside of EdgeBB.
3723 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3724 ValueToValueMapTy TranslateMap; // Track translated values.
3725 TranslateMap[Cond] = CB;
3726
3727 // RemoveDIs: track instructions that we optimise away while folding, so
3728 // that we can copy DbgVariableRecords from them later.
3729 BasicBlock::iterator SrcDbgCursor = BB->begin();
3730 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3731 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3732 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3733 continue;
3734 }
3735 // Clone the instruction.
3736 Instruction *N = BBI->clone();
3737 // Insert the new instruction into its new home.
3738 N->insertInto(EdgeBB, InsertPt);
3739
3740 if (BBI->hasName())
3741 N->setName(BBI->getName() + ".c");
3742
3743 // Update operands due to translation.
3744 // Key Instructions: Remap all the atom groups.
3745 if (const DebugLoc &DL = BBI->getDebugLoc())
3746 mapAtomInstance(DL, TranslateMap);
3747 RemapInstruction(N, TranslateMap,
3749
3750 // Check for trivial simplification.
3751 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3752 if (!BBI->use_empty())
3753 TranslateMap[&*BBI] = V;
3754 if (!N->mayHaveSideEffects()) {
3755 N->eraseFromParent(); // Instruction folded away, don't need actual
3756 // inst
3757 N = nullptr;
3758 }
3759 } else {
3760 if (!BBI->use_empty())
3761 TranslateMap[&*BBI] = N;
3762 }
3763 if (N) {
3764 // Copy all debug-info attached to instructions from the last we
3765 // successfully clone, up to this instruction (they might have been
3766 // folded away).
3767 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3768 N->cloneDebugInfoFrom(&*SrcDbgCursor);
3769 SrcDbgCursor = std::next(BBI);
3770 // Clone debug-info on this instruction too.
3771 N->cloneDebugInfoFrom(&*BBI);
3772
3773 // Register the new instruction with the assumption cache if necessary.
3774 if (auto *Assume = dyn_cast<AssumeInst>(N))
3775 if (AC)
3776 AC->registerAssumption(Assume);
3777 }
3778 }
3779
3780 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3781 InsertPt->cloneDebugInfoFrom(&*SrcDbgCursor);
3782 InsertPt->cloneDebugInfoFrom(BI);
3783
3784 BB->removePredecessor(EdgeBB);
3785 UncondBrInst *EdgeBI = cast<UncondBrInst>(EdgeBB->getTerminator());
3786 EdgeBI->setSuccessor(0, RealDest);
3787 EdgeBI->setDebugLoc(BI->getDebugLoc());
3788
3789 if (DTU) {
3791 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3792 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3793 DTU->applyUpdates(Updates);
3794 }
3795
3796 // For simplicity, we created a separate basic block for the edge. Merge
3797 // it back into the predecessor if possible. This not only avoids
3798 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3799 // bypass the check for trivial cycles above.
3800 MergeBlockIntoPredecessor(EdgeBB, DTU);
3801
3802 // Signal repeat, simplifying any other constants.
3803 return std::nullopt;
3804 }
3805
3806 return false;
3807}
3808
3809bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
3810 // Note: If BB is a loop header then there is a risk that threading introduces
3811 // a non-canonical loop by moving a back edge. So we avoid this optimization
3812 // for loop headers if NeedCanonicalLoop is set.
3813 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BI->getParent()))
3814 return false;
3815
3816 std::optional<bool> Result;
3817 bool EverChanged = false;
3818 do {
3819 // Note that None means "we changed things, but recurse further."
3821 Options.AC, DL);
3822 EverChanged |= Result == std::nullopt || *Result;
3823 } while (Result == std::nullopt);
3824 return EverChanged;
3825}
3826
3827/// Given a BB that starts with the specified two-entry PHI node,
3828/// see if we can eliminate it.
3831 const DataLayout &DL,
3832 bool SpeculateUnpredictables) {
3833 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3834 // statement", which has a very simple dominance structure. Basically, we
3835 // are trying to find the condition that is being branched on, which
3836 // subsequently causes this merge to happen. We really want control
3837 // dependence information for this check, but simplifycfg can't keep it up
3838 // to date, and this catches most of the cases we care about anyway.
3839 BasicBlock *BB = PN->getParent();
3840
3841 BasicBlock *IfTrue, *IfFalse;
3842 CondBrInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3843 if (!DomBI)
3844 return false;
3845 Value *IfCond = DomBI->getCondition();
3846 // Don't bother if the branch will be constant folded trivially.
3847 if (isa<ConstantInt>(IfCond))
3848 return false;
3849
3850 BasicBlock *DomBlock = DomBI->getParent();
3852 llvm::copy_if(PN->blocks(), std::back_inserter(IfBlocks),
3853 [](BasicBlock *IfBlock) {
3854 return isa<UncondBrInst>(IfBlock->getTerminator());
3855 });
3856 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3857 "Will have either one or two blocks to speculate.");
3858
3859 // If the branch is non-unpredictable, see if we either predictably jump to
3860 // the merge bb (if we have only a single 'then' block), or if we predictably
3861 // jump to one specific 'then' block (if we have two of them).
3862 // It isn't beneficial to speculatively execute the code
3863 // from the block that we know is predictably not entered.
3864 bool IsUnpredictable = DomBI->getMetadata(LLVMContext::MD_unpredictable);
3865 if (!IsUnpredictable) {
3866 uint64_t TWeight, FWeight;
3867 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3868 (TWeight + FWeight) != 0) {
3869 BranchProbability BITrueProb =
3870 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3871 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3872 BranchProbability BIFalseProb = BITrueProb.getCompl();
3873 if (IfBlocks.size() == 1) {
3874 BranchProbability BIBBProb =
3875 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3876 if (BIBBProb >= Likely)
3877 return false;
3878 } else {
3879 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3880 return false;
3881 }
3882 }
3883 }
3884
3885 // Don't try to fold an unreachable block. For example, the phi node itself
3886 // can't be the candidate if-condition for a select that we want to form.
3887 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3888 if (IfCondPhiInst->getParent() == BB)
3889 return false;
3890
3891 // Okay, we found that we can merge this two-entry phi node into a select.
3892 // Doing so would require us to fold *all* two entry phi nodes in this block.
3893 // At some point this becomes non-profitable (particularly if the target
3894 // doesn't support cmov's). Only do this transformation if there are two or
3895 // fewer PHI nodes in this block.
3896 unsigned NumPhis = 0;
3897 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3898 if (NumPhis > 2)
3899 return false;
3900
3901 // Loop over the PHI's seeing if we can promote them all to select
3902 // instructions. While we are at it, keep track of the instructions
3903 // that need to be moved to the dominating block.
3904 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3905 SmallPtrSet<Instruction *, 2> ZeroCostInstructions;
3906 InstructionCost Cost = 0;
3907 InstructionCost Budget =
3909 if (SpeculateUnpredictables && IsUnpredictable)
3910 Budget += TTI.getBranchMispredictPenalty();
3911
3912 bool Changed = false;
3913 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3914 PHINode *PN = cast<PHINode>(II++);
3915 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3916 PN->replaceAllUsesWith(V);
3917 PN->eraseFromParent();
3918 Changed = true;
3919 continue;
3920 }
3921
3922 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, DomBI,
3923 AggressiveInsts, Cost, Budget, TTI, AC,
3924 ZeroCostInstructions) ||
3925 !dominatesMergePoint(PN->getIncomingValue(1), BB, DomBI,
3926 AggressiveInsts, Cost, Budget, TTI, AC,
3927 ZeroCostInstructions))
3928 return Changed;
3929 }
3930
3931 // If we folded the first phi, PN dangles at this point. Refresh it. If
3932 // we ran out of PHIs then we simplified them all.
3933 PN = dyn_cast<PHINode>(BB->begin());
3934 if (!PN)
3935 return true;
3936
3937 // Don't fold i1 branches on PHIs which contain binary operators or
3938 // (possibly inverted) select form of or/ands if their parameters are
3939 // an equality test.
3940 auto IsBinOpOrAndEq = [](Value *V) {
3941 CmpPredicate Pred;
3942 if (match(V, m_CombineOr(
3944 m_BinOp(m_Cmp(Pred, m_Value(), m_Value()), m_Value()),
3945 m_BinOp(m_Value(), m_Cmp(Pred, m_Value(), m_Value()))),
3947 m_Cmp(Pred, m_Value(), m_Value()))))) {
3948 return CmpInst::isEquality(Pred);
3949 }
3950 return false;
3951 };
3952 if (PN->getType()->isIntegerTy(1) &&
3953 (IsBinOpOrAndEq(PN->getIncomingValue(0)) ||
3954 IsBinOpOrAndEq(PN->getIncomingValue(1)) || IsBinOpOrAndEq(IfCond)))
3955 return Changed;
3956
3957 // If all PHI nodes are promotable, check to make sure that all instructions
3958 // in the predecessor blocks can be promoted as well. If not, we won't be able
3959 // to get rid of the control flow, so it's not worth promoting to select
3960 // instructions.
3961 for (BasicBlock *IfBlock : IfBlocks)
3962 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3963 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3964 // This is not an aggressive instruction that we can promote.
3965 // Because of this, we won't be able to get rid of the control flow, so
3966 // the xform is not worth it.
3967 return Changed;
3968 }
3969
3970 // If either of the blocks has it's address taken, we can't do this fold.
3971 if (any_of(IfBlocks,
3972 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3973 return Changed;
3974
3975 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
3976 if (IsUnpredictable) dbgs() << " (unpredictable)";
3977 dbgs() << " T: " << IfTrue->getName()
3978 << " F: " << IfFalse->getName() << "\n");
3979
3980 // If we can still promote the PHI nodes after this gauntlet of tests,
3981 // do all of the PHI's now.
3982
3983 // Move all 'aggressive' instructions, which are defined in the
3984 // conditional parts of the if's up to the dominating block.
3985 for (BasicBlock *IfBlock : IfBlocks)
3986 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3987
3988 IRBuilder<NoFolder> Builder(DomBI);
3989 // Propagate fast-math-flags from phi nodes to replacement selects.
3990 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3991 // Change the PHI node into a select instruction.
3992 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3993 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3994
3995 Value *Sel = Builder.CreateSelectFMF(IfCond, TrueVal, FalseVal,
3996 isa<FPMathOperator>(PN) ? PN : nullptr,
3997 "", DomBI);
3998 PN->replaceAllUsesWith(Sel);
3999 Sel->takeName(PN);
4000 PN->eraseFromParent();
4001 }
4002
4003 // At this point, all IfBlocks are empty, so our if statement
4004 // has been flattened. Change DomBlock to jump directly to our new block to
4005 // avoid other simplifycfg's kicking in on the diamond.
4006 Builder.CreateBr(BB);
4007
4009 if (DTU) {
4010 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
4011 for (auto *Successor : successors(DomBlock))
4012 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
4013 }
4014
4015 DomBI->eraseFromParent();
4016 if (DTU)
4017 DTU->applyUpdates(Updates);
4018
4019 return true;
4020}
4021
4024 Value *RHS, const Twine &Name = "") {
4025 // Try to relax logical op to binary op.
4026 if (impliesPoison(RHS, LHS))
4027 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
4028 if (Opc == Instruction::And)
4029 return Builder.CreateLogicalAnd(LHS, RHS, Name);
4030 if (Opc == Instruction::Or)
4031 return Builder.CreateLogicalOr(LHS, RHS, Name);
4032 llvm_unreachable("Invalid logical opcode");
4033}
4034
4035/// Return true if either PBI or BI has branch weight available, and store
4036/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
4037/// not have branch weight, use 1:1 as its weight.
4039 uint64_t &PredTrueWeight,
4040 uint64_t &PredFalseWeight,
4041 uint64_t &SuccTrueWeight,
4042 uint64_t &SuccFalseWeight) {
4043 bool PredHasWeights =
4044 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
4045 bool SuccHasWeights =
4046 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
4047 if (PredHasWeights || SuccHasWeights) {
4048 if (!PredHasWeights)
4049 PredTrueWeight = PredFalseWeight = 1;
4050 if (!SuccHasWeights)
4051 SuccTrueWeight = SuccFalseWeight = 1;
4052 return true;
4053 } else {
4054 return false;
4055 }
4056}
4057
4058/// Determine if the two branches share a common destination and deduce a glue
4059/// that joins the branches' conditions to arrive at the common destination if
4060/// that would be profitable.
4061static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
4063 const TargetTransformInfo *TTI) {
4064 assert(BI && PBI && "Both blocks must end with a conditional branches.");
4066 "PredBB must be a predecessor of BB.");
4067
4068 // We have the potential to fold the conditions together, but if the
4069 // predecessor branch is predictable, we may not want to merge them.
4070 uint64_t PTWeight, PFWeight;
4071 BranchProbability PBITrueProb, Likely;
4072 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4073 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
4074 (PTWeight + PFWeight) != 0) {
4075 PBITrueProb =
4076 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
4077 Likely = TTI->getPredictableBranchThreshold();
4078 }
4079
4080 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4081 // Speculate the 2nd condition unless the 1st is probably true.
4082 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4083 return {{BI->getSuccessor(0), Instruction::Or, false}};
4084 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4085 // Speculate the 2nd condition unless the 1st is probably false.
4086 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4087 return {{BI->getSuccessor(1), Instruction::And, false}};
4088 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4089 // Speculate the 2nd condition unless the 1st is probably true.
4090 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4091 return {{BI->getSuccessor(1), Instruction::And, true}};
4092 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4093 // Speculate the 2nd condition unless the 1st is probably false.
4094 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4095 return {{BI->getSuccessor(0), Instruction::Or, true}};
4096 }
4097 return std::nullopt;
4098}
4099
4101 DomTreeUpdater *DTU,
4102 MemorySSAUpdater *MSSAU,
4103 const TargetTransformInfo *TTI) {
4104 BasicBlock *BB = BI->getParent();
4105 BasicBlock *PredBlock = PBI->getParent();
4106
4107 // Determine if the two branches share a common destination.
4108 BasicBlock *CommonSucc;
4110 bool InvertPredCond;
4111 std::tie(CommonSucc, Opc, InvertPredCond) =
4113
4114 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
4115
4117 BB->getContext(), ConstantFolder{},
4119 // The builder is used to create instructions to eliminate the branch in
4120 // BB. If BB's terminator has !annotation metadata, add it to the new
4121 // instructions.
4122 I->copyMetadata(*BB->getTerminator(), LLVMContext::MD_annotation);
4123 }));
4124 Builder.SetInsertPoint(PBI);
4125
4126 // If we need to invert the condition in the pred block to match, do so now.
4127 if (InvertPredCond) {
4128 InvertBranch(PBI, Builder);
4129 }
4130
4131 BasicBlock *UniqueSucc =
4132 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
4133
4134 // Before cloning instructions, notify the successor basic block that it
4135 // is about to have a new predecessor. This will update PHI nodes,
4136 // which will allow us to update live-out uses of bonus instructions.
4137 addPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
4138
4139 // Try to update branch weights.
4140 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4141 SmallVector<uint64_t, 2> MDWeights;
4142 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4143 SuccTrueWeight, SuccFalseWeight)) {
4144
4145 if (PBI->getSuccessor(0) == BB) {
4146 // PBI: br i1 %x, BB, FalseDest
4147 // BI: br i1 %y, UniqueSucc, FalseDest
4148 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
4149 MDWeights.push_back(PredTrueWeight * SuccTrueWeight);
4150 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
4151 // TrueWeight for PBI * FalseWeight for BI.
4152 // We assume that total weights of a CondBrInst can fit into 32 bits.
4153 // Therefore, we will not have overflow using 64-bit arithmetic.
4154 MDWeights.push_back(PredFalseWeight * (SuccFalseWeight + SuccTrueWeight) +
4155 PredTrueWeight * SuccFalseWeight);
4156 } else {
4157 // PBI: br i1 %x, TrueDest, BB
4158 // BI: br i1 %y, TrueDest, UniqueSucc
4159 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
4160 // FalseWeight for PBI * TrueWeight for BI.
4161 MDWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
4162 PredFalseWeight * SuccTrueWeight);
4163 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
4164 MDWeights.push_back(PredFalseWeight * SuccFalseWeight);
4165 }
4166
4167 setFittedBranchWeights(*PBI, MDWeights, /*IsExpected=*/false,
4168 /*ElideAllZero=*/true);
4169
4170 // TODO: If BB is reachable from all paths through PredBlock, then we
4171 // could replace PBI's branch probabilities with BI's.
4172 } else
4173 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
4174
4175 // Now, update the CFG.
4176 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
4177
4178 if (DTU)
4179 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
4180 {DominatorTree::Delete, PredBlock, BB}});
4181
4182 // If BI was a loop latch, it may have had associated loop metadata.
4183 // We need to copy it to the new latch, that is, PBI.
4184 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
4185 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
4186
4187 ValueToValueMapTy VMap; // maps original values to cloned values
4189
4190 Module *M = BB->getModule();
4191
4192 PredBlock->getTerminator()->cloneDebugInfoFrom(BB->getTerminator());
4193 for (DbgVariableRecord &DVR :
4195 RemapDbgRecord(M, &DVR, VMap,
4197 }
4198
4199 // Now that the Cond was cloned into the predecessor basic block,
4200 // or/and the two conditions together.
4201 Value *BICond = VMap[BI->getCondition()];
4202 PBI->setCondition(
4203 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
4205 if (auto *SI = dyn_cast<SelectInst>(PBI->getCondition()))
4206 if (!MDWeights.empty()) {
4207 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4208 setFittedBranchWeights(*SI, {MDWeights[0], MDWeights[1]},
4209 /*IsExpected=*/false, /*ElideAllZero=*/true);
4210 }
4211
4212 ++NumFoldBranchToCommonDest;
4213 return true;
4214}
4215
4216/// Return if an instruction's type or any of its operands' types are a vector
4217/// type.
4218static bool isVectorOp(Instruction &I) {
4219 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
4220 return U->getType()->isVectorTy();
4221 });
4222}
4223
4224/// If this basic block is simple enough, and if a predecessor branches to us
4225/// and one of our successors, fold the block into the predecessor and use
4226/// logical operations to pick the right destination.
4228 MemorySSAUpdater *MSSAU,
4229 const TargetTransformInfo *TTI,
4230 AssumptionCache *AC,
4231 unsigned BonusInstThreshold) {
4232 BasicBlock *BB = BI->getParent();
4236
4238
4240 Cond->getParent() != BB || !Cond->hasOneUse())
4241 return false;
4242
4243 // Finally, don't infinitely unroll conditional loops.
4244 if (is_contained(successors(BB), BB))
4245 return false;
4246
4247 // With which predecessors will we want to deal with?
4249 for (BasicBlock *PredBlock : predecessors(BB)) {
4250 CondBrInst *PBI = dyn_cast<CondBrInst>(PredBlock->getTerminator());
4251
4252 // Check that we have two conditional branches. If there is a PHI node in
4253 // the common successor, verify that the same value flows in from both
4254 // blocks.
4255 if (!PBI || !safeToMergeTerminators(BI, PBI))
4256 continue;
4257
4258 // Determine if the two branches share a common destination.
4259 BasicBlock *CommonSucc;
4261 bool InvertPredCond;
4262 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
4263 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
4264 else
4265 continue;
4266
4267 // Check the cost of inserting the necessary logic before performing the
4268 // transformation.
4269 if (TTI) {
4270 Type *Ty = BI->getCondition()->getType();
4271 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
4272 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
4273 !isa<CmpInst>(PBI->getCondition())))
4274 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
4275
4277 continue;
4278 }
4279
4280 // Ok, we do want to deal with this predecessor. Record it.
4281 Preds.emplace_back(PredBlock);
4282 }
4283
4284 // If there aren't any predecessors into which we can fold,
4285 // don't bother checking the cost.
4286 if (Preds.empty())
4287 return false;
4288
4289 // Only allow this transformation if computing the condition doesn't involve
4290 // too many instructions and these involved instructions can be executed
4291 // unconditionally. We denote all involved instructions except the condition
4292 // as "bonus instructions", and only allow this transformation when the
4293 // number of the bonus instructions we'll need to create when cloning into
4294 // each predecessor does not exceed a certain threshold.
4295 unsigned NumBonusInsts = 0;
4296 bool SawVectorOp = false;
4297 const unsigned PredCount = Preds.size();
4298 // Speculated instructions will be inserted before the terminator of the
4299 // predecessor. Only handle the simple case of one predecessor.
4300 const Instruction *CxtI =
4301 PredCount == 1 ? Preds[0]->getTerminator() : nullptr;
4302 for (Instruction &I : *BB) {
4303 // Don't check the branch condition comparison itself.
4304 if (&I == Cond)
4305 continue;
4306 // Ignore the terminator.
4308 continue;
4309 // Pseudo probes aren't speculatable but can be dropped on fold.
4311 continue;
4312 // I must be safe to execute unconditionally.
4313 if (!isSafeToSpeculativelyExecute(&I, CxtI, AC))
4314 return false;
4315 SawVectorOp |= isVectorOp(I);
4316
4317 // Account for the cost of duplicating this instruction into each
4318 // predecessor. Ignore free instructions.
4319 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
4321 NumBonusInsts += PredCount;
4322
4323 // Early exits once we reach the limit.
4324 if (NumBonusInsts >
4325 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
4326 return false;
4327 }
4328
4329 auto IsBCSSAUse = [BB, &I](Use &U) {
4330 auto *UI = cast<Instruction>(U.getUser());
4331 if (auto *PN = dyn_cast<PHINode>(UI))
4332 return PN->getIncomingBlock(U) == BB;
4333 return UI->getParent() == BB && I.comesBefore(UI);
4334 };
4335
4336 // Does this instruction require rewriting of uses?
4337 if (!all_of(I.uses(), IsBCSSAUse))
4338 return false;
4339 }
4340 if (NumBonusInsts >
4341 BonusInstThreshold *
4342 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
4343 return false;
4344
4345 // Ok, we have the budget. Perform the transformation.
4346 for (BasicBlock *PredBlock : Preds) {
4347 auto *PBI = cast<CondBrInst>(PredBlock->getTerminator());
4348 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4349 }
4350 return false;
4351}
4352
4353// If there is only one store in BB1 and BB2, return it, otherwise return
4354// nullptr.
4356 StoreInst *S = nullptr;
4357 for (auto *BB : {BB1, BB2}) {
4358 if (!BB)
4359 continue;
4360 for (auto &I : *BB)
4361 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4362 if (S)
4363 // Multiple stores seen.
4364 return nullptr;
4365 else
4366 S = SI;
4367 }
4368 }
4369 return S;
4370}
4371
4373 Value *AlternativeV = nullptr) {
4374 // PHI is going to be a PHI node that allows the value V that is defined in
4375 // BB to be referenced in BB's only successor.
4376 //
4377 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4378 // doesn't matter to us what the other operand is (it'll never get used). We
4379 // could just create a new PHI with an undef incoming value, but that could
4380 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4381 // other PHI. So here we directly look for some PHI in BB's successor with V
4382 // as an incoming operand. If we find one, we use it, else we create a new
4383 // one.
4384 //
4385 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4386 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4387 // where OtherBB is the single other predecessor of BB's only successor.
4388 PHINode *PHI = nullptr;
4389 BasicBlock *Succ = BB->getSingleSuccessor();
4390
4391 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
4392 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
4393 PHI = cast<PHINode>(I);
4394 if (!AlternativeV)
4395 break;
4396
4397 assert(Succ->hasNPredecessors(2));
4398 auto PredI = pred_begin(Succ);
4399 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4400 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
4401 break;
4402 PHI = nullptr;
4403 }
4404 if (PHI)
4405 return PHI;
4406
4407 // If V is not an instruction defined in BB, just return it.
4408 if (!AlternativeV &&
4409 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
4410 return V;
4411
4412 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
4413 PHI->insertBefore(Succ->begin());
4414 PHI->addIncoming(V, BB);
4415 for (BasicBlock *PredBB : predecessors(Succ))
4416 if (PredBB != BB)
4417 PHI->addIncoming(
4418 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
4419 return PHI;
4420}
4421
4423 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4424 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4425 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4426 // For every pointer, there must be exactly two stores, one coming from
4427 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4428 // store (to any address) in PTB,PFB or QTB,QFB.
4429 // FIXME: We could relax this restriction with a bit more work and performance
4430 // testing.
4431 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
4432 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
4433 if (!PStore || !QStore)
4434 return false;
4435
4436 // Now check the stores are compatible.
4437 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4438 PStore->getOrdering() != QStore->getOrdering() ||
4439 PStore->getSyncScopeID() != QStore->getSyncScopeID() ||
4440 PStore->getValueOperand()->getType() !=
4441 QStore->getValueOperand()->getType())
4442 return false;
4443
4444 // Check that sinking the store won't cause program behavior changes. Sinking
4445 // the store out of the Q blocks won't change any behavior as we're sinking
4446 // from a block to its unconditional successor. But we're moving a store from
4447 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4448 // So we need to check that there are no aliasing loads or stores in
4449 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4450 // operations between PStore and the end of its parent block.
4451 //
4452 // The ideal way to do this is to query AliasAnalysis, but we don't
4453 // preserve AA currently so that is dangerous. Be super safe and just
4454 // check there are no other memory operations at all.
4455 for (auto &I : *QFB->getSinglePredecessor())
4456 if (I.mayReadOrWriteMemory())
4457 return false;
4458 for (auto &I : *QFB)
4459 if (&I != QStore && I.mayReadOrWriteMemory())
4460 return false;
4461 if (QTB)
4462 for (auto &I : *QTB)
4463 if (&I != QStore && I.mayReadOrWriteMemory())
4464 return false;
4465 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4466 I != E; ++I)
4467 if (&*I != PStore && I->mayReadOrWriteMemory())
4468 return false;
4469
4470 // If we're not in aggressive mode, we only optimize if we have some
4471 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4472 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4473 if (!BB)
4474 return true;
4475 // Heuristic: if the block can be if-converted/phi-folded and the
4476 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4477 // thread this store.
4478 InstructionCost Cost = 0;
4479 InstructionCost Budget =
4481 for (auto &I : *BB) {
4482 // Consider terminator instruction to be free.
4483 if (I.isTerminator())
4484 continue;
4485 // If this is one the stores that we want to speculate out of this BB,
4486 // then don't count it's cost, consider it to be free.
4487 if (auto *S = dyn_cast<StoreInst>(&I))
4488 if (llvm::find(FreeStores, S))
4489 continue;
4490 // Else, we have a white-list of instructions that we are ak speculating.
4492 return false; // Not in white-list - not worthwhile folding.
4493 // And finally, if this is a non-free instruction that we are okay
4494 // speculating, ensure that we consider the speculation budget.
4495 Cost +=
4496 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
4497 if (Cost > Budget)
4498 return false; // Eagerly refuse to fold as soon as we're out of budget.
4499 }
4500 assert(Cost <= Budget &&
4501 "When we run out of budget we will eagerly return from within the "
4502 "per-instruction loop.");
4503 return true;
4504 };
4505
4506 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4508 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4509 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4510 return false;
4511
4512 // If PostBB has more than two predecessors, we need to split it so we can
4513 // sink the store.
4514 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4515 // We know that QFB's only successor is PostBB. And QFB has a single
4516 // predecessor. If QTB exists, then its only successor is also PostBB.
4517 // If QTB does not exist, then QFB's only predecessor has a conditional
4518 // branch to QFB and PostBB.
4519 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4520 BasicBlock *NewBB =
4521 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4522 if (!NewBB)
4523 return false;
4524 PostBB = NewBB;
4525 }
4526
4527 // OK, we're going to sink the stores to PostBB. The store has to be
4528 // conditional though, so first create the predicate.
4529 CondBrInst *PBranch =
4531 CondBrInst *QBranch =
4533 Value *PCond = PBranch->getCondition();
4534 Value *QCond = QBranch->getCondition();
4535
4537 PStore->getParent());
4539 QStore->getParent(), PPHI);
4540
4541 BasicBlock::iterator PostBBFirst = PostBB->getFirstInsertionPt();
4542 IRBuilder<> QB(PostBB, PostBBFirst);
4543 QB.SetCurrentDebugLocation(PostBBFirst->getStableDebugLoc());
4544
4545 InvertPCond ^= (PStore->getParent() != PTB);
4546 InvertQCond ^= (QStore->getParent() != QTB);
4547 Value *PPred = InvertPCond ? QB.CreateNot(PCond) : PCond;
4548 Value *QPred = InvertQCond ? QB.CreateNot(QCond) : QCond;
4549
4550 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4551
4552 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4553 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4554 /*Unreachable=*/false,
4555 /*BranchWeights=*/nullptr, DTU);
4556 if (hasBranchWeightMD(*PBranch) && hasBranchWeightMD(*QBranch) &&
4558 SmallVector<uint32_t, 2> PWeights, QWeights;
4559 extractBranchWeights(*PBranch, PWeights);
4560 extractBranchWeights(*QBranch, QWeights);
4561 if (InvertPCond)
4562 std::swap(PWeights[0], PWeights[1]);
4563 if (InvertQCond)
4564 std::swap(QWeights[0], QWeights[1]);
4565 auto CombinedWeights = getDisjunctionWeights(PWeights, QWeights);
4567 {CombinedWeights[0], CombinedWeights[1]},
4568 /*IsExpected=*/false, /*ElideAllZero=*/true);
4569 }
4570
4571 QB.SetInsertPoint(T);
4572 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4573 combineMetadataForCSE(QStore, PStore, true);
4574 SI->copyMetadata(*QStore);
4575 // Update any dbg.assign intrinsics to track the merged value (QPHI) instead
4576 // of the original constant values, likely making these identical.
4577 for (auto *DbgAssign : at::getDVRAssignmentMarkers(SI)) {
4578 if (llvm::is_contained(DbgAssign->location_ops(),
4579 PStore->getValueOperand()))
4580 DbgAssign->replaceVariableLocationOp(PStore->getValueOperand(), QPHI);
4581 if (llvm::is_contained(DbgAssign->location_ops(),
4582 QStore->getValueOperand()))
4583 DbgAssign->replaceVariableLocationOp(QStore->getValueOperand(), QPHI);
4584 }
4585
4586 // Choose the minimum alignment. If we could prove both stores execute, we
4587 // could use biggest one. In this case, though, we only know that one of the
4588 // stores executes. And we don't know it's safe to take the alignment from a
4589 // store that doesn't execute.
4590 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4591
4592 if (QStore->isAtomic())
4593 SI->setAtomic(QStore->getOrdering(), QStore->getSyncScopeID());
4594
4595 QStore->eraseFromParent();
4596 PStore->eraseFromParent();
4597
4598 return true;
4599}
4600
4602 DomTreeUpdater *DTU, const DataLayout &DL,
4603 const TargetTransformInfo &TTI) {
4604 // The intention here is to find diamonds or triangles (see below) where each
4605 // conditional block contains a store to the same address. Both of these
4606 // stores are conditional, so they can't be unconditionally sunk. But it may
4607 // be profitable to speculatively sink the stores into one merged store at the
4608 // end, and predicate the merged store on the union of the two conditions of
4609 // PBI and QBI.
4610 //
4611 // This can reduce the number of stores executed if both of the conditions are
4612 // true, and can allow the blocks to become small enough to be if-converted.
4613 // This optimization will also chain, so that ladders of test-and-set
4614 // sequences can be if-converted away.
4615 //
4616 // We only deal with simple diamonds or triangles:
4617 //
4618 // PBI or PBI or a combination of the two
4619 // / \ | \
4620 // PTB PFB | PFB
4621 // \ / | /
4622 // QBI QBI
4623 // / \ | \
4624 // QTB QFB | QFB
4625 // \ / | /
4626 // PostBB PostBB
4627 //
4628 // We model triangles as a type of diamond with a nullptr "true" block.
4629 // Triangles are canonicalized so that the fallthrough edge is represented by
4630 // a true condition, as in the diagram above.
4631 BasicBlock *PTB = PBI->getSuccessor(0);
4632 BasicBlock *PFB = PBI->getSuccessor(1);
4633 BasicBlock *QTB = QBI->getSuccessor(0);
4634 BasicBlock *QFB = QBI->getSuccessor(1);
4635 BasicBlock *PostBB = QFB->getSingleSuccessor();
4636
4637 // Make sure we have a good guess for PostBB. If QTB's only successor is
4638 // QFB, then QFB is a better PostBB.
4639 if (QTB->getSingleSuccessor() == QFB)
4640 PostBB = QFB;
4641
4642 // If we couldn't find a good PostBB, stop.
4643 if (!PostBB)
4644 return false;
4645
4646 bool InvertPCond = false, InvertQCond = false;
4647 // Canonicalize fallthroughs to the true branches.
4648 if (PFB == QBI->getParent()) {
4649 std::swap(PFB, PTB);
4650 InvertPCond = true;
4651 }
4652 if (QFB == PostBB) {
4653 std::swap(QFB, QTB);
4654 InvertQCond = true;
4655 }
4656
4657 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4658 // and QFB may not. Model fallthroughs as a nullptr block.
4659 if (PTB == QBI->getParent())
4660 PTB = nullptr;
4661 if (QTB == PostBB)
4662 QTB = nullptr;
4663
4664 // Legality bailouts. We must have at least the non-fallthrough blocks and
4665 // the post-dominating block, and the non-fallthroughs must only have one
4666 // predecessor.
4667 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4668 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4669 };
4670 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4671 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4672 return false;
4673 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4674 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4675 return false;
4676 if (!QBI->getParent()->hasNUses(2))
4677 return false;
4678
4679 // OK, this is a sequence of two diamonds or triangles.
4680 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4681 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4682 for (auto *BB : {PTB, PFB}) {
4683 if (!BB)
4684 continue;
4685 for (auto &I : *BB)
4687 PStoreAddresses.insert(SI->getPointerOperand());
4688 }
4689 for (auto *BB : {QTB, QFB}) {
4690 if (!BB)
4691 continue;
4692 for (auto &I : *BB)
4694 QStoreAddresses.insert(SI->getPointerOperand());
4695 }
4696
4697 set_intersect(PStoreAddresses, QStoreAddresses);
4698 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4699 // clear what it contains.
4700 auto &CommonAddresses = PStoreAddresses;
4701
4702 bool Changed = false;
4703 for (auto *Address : CommonAddresses)
4704 Changed |=
4705 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4706 InvertPCond, InvertQCond, DTU, DL, TTI);
4707 return Changed;
4708}
4709
4710/// If the previous block ended with a widenable branch, determine if reusing
4711/// the target block is profitable and legal. This will have the effect of
4712/// "widening" PBI, but doesn't require us to reason about hosting safety.
4714 DomTreeUpdater *DTU) {
4715 // TODO: This can be generalized in two important ways:
4716 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4717 // values from the PBI edge.
4718 // 2) We can sink side effecting instructions into BI's fallthrough
4719 // successor provided they doesn't contribute to computation of
4720 // BI's condition.
4721 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4722 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4723 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4724 !BI->getParent()->getSinglePredecessor())
4725 return false;
4726 if (!IfFalseBB->phis().empty())
4727 return false; // TODO
4728 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4729 // may undo the transform done here.
4730 // TODO: There might be a more fine-grained solution to this.
4731 if (!llvm::succ_empty(IfFalseBB))
4732 return false;
4733 // Use lambda to lazily compute expensive condition after cheap ones.
4734 auto NoSideEffects = [](BasicBlock &BB) {
4735 return llvm::none_of(BB, [](const Instruction &I) {
4736 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4737 });
4738 };
4739 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4740 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4741 NoSideEffects(*BI->getParent())) {
4742 auto *OldSuccessor = BI->getSuccessor(1);
4743 OldSuccessor->removePredecessor(BI->getParent());
4744 BI->setSuccessor(1, IfFalseBB);
4745 if (DTU)
4746 DTU->applyUpdates(
4747 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4748 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4749 return true;
4750 }
4751 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4752 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4753 NoSideEffects(*BI->getParent())) {
4754 auto *OldSuccessor = BI->getSuccessor(0);
4755 OldSuccessor->removePredecessor(BI->getParent());
4756 BI->setSuccessor(0, IfFalseBB);
4757 if (DTU)
4758 DTU->applyUpdates(
4759 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4760 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4761 return true;
4762 }
4763 return false;
4764}
4765
4766/// If we have a conditional branch as a predecessor of another block,
4767/// this function tries to simplify it. We know
4768/// that PBI and BI are both conditional branches, and BI is in one of the
4769/// successor blocks of PBI - PBI branches to BI.
4771 DomTreeUpdater *DTU,
4772 const DataLayout &DL,
4773 const TargetTransformInfo &TTI) {
4774 BasicBlock *BB = BI->getParent();
4775
4776 // If this block ends with a branch instruction, and if there is a
4777 // predecessor that ends on a branch of the same condition, make
4778 // this conditional branch redundant.
4779 if (PBI->getCondition() == BI->getCondition() &&
4780 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4781 // Okay, the outcome of this conditional branch is statically
4782 // knowable. If this block had a single pred, handle specially, otherwise
4783 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4784 if (BB->getSinglePredecessor()) {
4785 // Turn this into a branch on constant.
4786 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4787 BI->setCondition(
4788 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4789 return true; // Nuke the branch on constant.
4790 }
4791 }
4792
4793 // If the previous block ended with a widenable branch, determine if reusing
4794 // the target block is profitable and legal. This will have the effect of
4795 // "widening" PBI, but doesn't require us to reason about hosting safety.
4796 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4797 return true;
4798
4799 // If both branches are conditional and both contain stores to the same
4800 // address, remove the stores from the conditionals and create a conditional
4801 // merged store at the end.
4802 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4803 return true;
4804
4805 // If this is a conditional branch in an empty block, and if any
4806 // predecessors are a conditional branch to one of our destinations,
4807 // fold the conditions into logical ops and one cond br.
4808
4809 // Ignore dbg intrinsics.
4810 if (&*BB->begin() != BI)
4811 return false;
4812
4813 int PBIOp, BIOp;
4814 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4815 PBIOp = 0;
4816 BIOp = 0;
4817 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4818 PBIOp = 0;
4819 BIOp = 1;
4820 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4821 PBIOp = 1;
4822 BIOp = 0;
4823 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4824 PBIOp = 1;
4825 BIOp = 1;
4826 } else {
4827 return false;
4828 }
4829
4830 // Check to make sure that the other destination of this branch
4831 // isn't BB itself. If so, this is an infinite loop that will
4832 // keep getting unwound.
4833 if (PBI->getSuccessor(PBIOp) == BB)
4834 return false;
4835
4836 // If predecessor's branch probability to BB is too low don't merge branches.
4837 SmallVector<uint32_t, 2> PredWeights;
4838 if (!PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4839 extractBranchWeights(*PBI, PredWeights) &&
4840 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4841
4843 PredWeights[PBIOp],
4844 static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4845
4846 BranchProbability Likely = TTI.getPredictableBranchThreshold();
4847 if (CommonDestProb >= Likely)
4848 return false;
4849 }
4850
4851 // Do not perform this transformation if it would require
4852 // insertion of a large number of select instructions. For targets
4853 // without predication/cmovs, this is a big pessimization.
4854
4855 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4856 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4857 unsigned NumPhis = 0;
4858 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4859 ++II, ++NumPhis) {
4860 if (NumPhis > 2) // Disable this xform.
4861 return false;
4862 }
4863
4864 // Finally, if everything is ok, fold the branches to logical ops.
4865 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4866
4867 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4868 << "AND: " << *BI->getParent());
4869
4871
4872 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4873 // branch in it, where one edge (OtherDest) goes back to itself but the other
4874 // exits. We don't *know* that the program avoids the infinite loop
4875 // (even though that seems likely). If we do this xform naively, we'll end up
4876 // recursively unpeeling the loop. Since we know that (after the xform is
4877 // done) that the block *is* infinite if reached, we just make it an obviously
4878 // infinite loop with no cond branch.
4879 if (OtherDest == BB) {
4880 // Insert it at the end of the function, because it's either code,
4881 // or it won't matter if it's hot. :)
4882 BasicBlock *InfLoopBlock =
4883 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4884 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
4885 if (DTU)
4886 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4887 OtherDest = InfLoopBlock;
4888 }
4889
4890 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4891
4892 // BI may have other predecessors. Because of this, we leave
4893 // it alone, but modify PBI.
4894
4895 // Make sure we get to CommonDest on True&True directions.
4896 Value *PBICond = PBI->getCondition();
4897 IRBuilder<NoFolder> Builder(PBI);
4898 if (PBIOp)
4899 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4900
4901 Value *BICond = BI->getCondition();
4902 if (BIOp)
4903 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4904
4905 // Merge the conditions.
4906 Value *Cond =
4907 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4908
4909 // Modify PBI to branch on the new condition to the new dests.
4910 PBI->setCondition(Cond);
4911 PBI->setSuccessor(0, CommonDest);
4912 PBI->setSuccessor(1, OtherDest);
4913
4914 if (DTU) {
4915 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4916 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4917
4918 DTU->applyUpdates(Updates);
4919 }
4920
4921 // Update branch weight for PBI.
4922 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4923 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4924 bool HasWeights =
4925 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4926 SuccTrueWeight, SuccFalseWeight);
4927 if (HasWeights) {
4928 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4929 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4930 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4931 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4932 // The weight to CommonDest should be PredCommon * SuccTotal +
4933 // PredOther * SuccCommon.
4934 // The weight to OtherDest should be PredOther * SuccOther.
4935 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4936 PredOther * SuccCommon,
4937 PredOther * SuccOther};
4938
4939 setFittedBranchWeights(*PBI, NewWeights, /*IsExpected=*/false,
4940 /*ElideAllZero=*/true);
4941 // Cond may be a select instruction with the first operand set to "true", or
4942 // the second to "false" (see how createLogicalOp works for `and` and `or`)
4944 if (auto *SI = dyn_cast<SelectInst>(Cond)) {
4945 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4946 // The select is predicated on PBICond
4947 assert(SI->getCondition() == PBICond);
4948 // The corresponding probabilities are what was referred to above as
4949 // PredCommon and PredOther.
4950 setFittedBranchWeights(*SI, {PredCommon, PredOther},
4951 /*IsExpected=*/false, /*ElideAllZero=*/true);
4952 }
4953 }
4954
4955 // OtherDest may have phi nodes. If so, add an entry from PBI's
4956 // block that are identical to the entries for BI's block.
4957 addPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4958
4959 // We know that the CommonDest already had an edge from PBI to
4960 // it. If it has PHIs though, the PHIs may have different
4961 // entries for BB and PBI's BB. If so, insert a select to make
4962 // them agree.
4963 for (PHINode &PN : CommonDest->phis()) {
4964 Value *BIV = PN.getIncomingValueForBlock(BB);
4965 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4966 Value *PBIV = PN.getIncomingValue(PBBIdx);
4967 if (BIV != PBIV) {
4968 // Insert a select in PBI to pick the right value.
4970 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4971 PN.setIncomingValue(PBBIdx, NV);
4972 // The select has the same condition as PBI, in the same BB. The
4973 // probabilities don't change.
4974 if (HasWeights) {
4975 uint64_t TrueWeight = PBIOp ? PredFalseWeight : PredTrueWeight;
4976 uint64_t FalseWeight = PBIOp ? PredTrueWeight : PredFalseWeight;
4977 setFittedBranchWeights(*NV, {TrueWeight, FalseWeight},
4978 /*IsExpected=*/false, /*ElideAllZero=*/true);
4979 }
4980 }
4981 }
4982
4983 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4984 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4985
4986 // This basic block is probably dead. We know it has at least
4987 // one fewer predecessor.
4988 return true;
4989}
4990
4991// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4992// true or to FalseBB if Cond is false.
4993// Takes care of updating the successors and removing the old terminator.
4994// Also makes sure not to introduce new successors by assuming that edges to
4995// non-successor TrueBBs and FalseBBs aren't reachable.
4996bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
4997 Value *Cond, BasicBlock *TrueBB,
4998 BasicBlock *FalseBB,
4999 uint32_t TrueWeight,
5000 uint32_t FalseWeight) {
5001 auto *BB = OldTerm->getParent();
5002 // Remove any superfluous successor edges from the CFG.
5003 // First, figure out which successors to preserve.
5004 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
5005 // successor.
5006 BasicBlock *KeepEdge1 = TrueBB;
5007 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
5008
5009 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
5010
5011 // Then remove the rest.
5012 for (BasicBlock *Succ : successors(OldTerm)) {
5013 // Make sure only to keep exactly one copy of each edge.
5014 if (Succ == KeepEdge1)
5015 KeepEdge1 = nullptr;
5016 else if (Succ == KeepEdge2)
5017 KeepEdge2 = nullptr;
5018 else {
5019 Succ->removePredecessor(BB,
5020 /*KeepOneInputPHIs=*/true);
5021
5022 if (Succ != TrueBB && Succ != FalseBB)
5023 RemovedSuccessors.insert(Succ);
5024 }
5025 }
5026
5027 IRBuilder<> Builder(OldTerm);
5028 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
5029
5030 // Insert an appropriate new terminator.
5031 if (!KeepEdge1 && !KeepEdge2) {
5032 if (TrueBB == FalseBB) {
5033 // We were only looking for one successor, and it was present.
5034 // Create an unconditional branch to it.
5035 Builder.CreateBr(TrueBB);
5036 } else {
5037 // We found both of the successors we were looking for.
5038 // Create a conditional branch sharing the condition of the select.
5039 CondBrInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
5040 setBranchWeights(*NewBI, {TrueWeight, FalseWeight},
5041 /*IsExpected=*/false, /*ElideAllZero=*/true);
5042 }
5043 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
5044 // Neither of the selected blocks were successors, so this
5045 // terminator must be unreachable.
5046 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
5047 } else {
5048 // One of the selected values was a successor, but the other wasn't.
5049 // Insert an unconditional branch to the one that was found;
5050 // the edge to the one that wasn't must be unreachable.
5051 if (!KeepEdge1) {
5052 // Only TrueBB was found.
5053 Builder.CreateBr(TrueBB);
5054 } else {
5055 // Only FalseBB was found.
5056 Builder.CreateBr(FalseBB);
5057 }
5058 }
5059
5061
5062 if (DTU) {
5063 SmallVector<DominatorTree::UpdateType, 2> Updates;
5064 Updates.reserve(RemovedSuccessors.size());
5065 for (auto *RemovedSuccessor : RemovedSuccessors)
5066 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
5067 DTU->applyUpdates(Updates);
5068 }
5069
5070 return true;
5071}
5072
5073// Replaces
5074// (switch (select cond, X, Y)) on constant X, Y
5075// with a branch - conditional if X and Y lead to distinct BBs,
5076// unconditional otherwise.
5077bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
5078 SelectInst *Select) {
5079 // Check for constant integer values in the select.
5080 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
5081 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
5082 if (!TrueVal || !FalseVal)
5083 return false;
5084
5085 // Find the relevant condition and destinations.
5086 Value *Condition = Select->getCondition();
5087 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
5088 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
5089
5090 // Get weight for TrueBB and FalseBB.
5091 uint32_t TrueWeight = 0, FalseWeight = 0;
5092 SmallVector<uint64_t, 8> Weights;
5093 bool HasWeights = hasBranchWeightMD(*SI);
5094 if (HasWeights) {
5095 getBranchWeights(SI, Weights);
5096 if (Weights.size() == 1 + SI->getNumCases()) {
5097 TrueWeight =
5098 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
5099 FalseWeight =
5100 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
5101 }
5102 }
5103
5104 // Perform the actual simplification.
5105 return simplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
5106 FalseWeight);
5107}
5108
5109// Replaces
5110// (indirectbr (select cond, blockaddress(@fn, BlockA),
5111// blockaddress(@fn, BlockB)))
5112// with
5113// (br cond, BlockA, BlockB).
5114bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
5115 SelectInst *SI) {
5116 // Check that both operands of the select are block addresses.
5117 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
5118 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
5119 if (!TBA || !FBA)
5120 return false;
5121
5122 // Extract the actual blocks.
5123 BasicBlock *TrueBB = TBA->getBasicBlock();
5124 BasicBlock *FalseBB = FBA->getBasicBlock();
5125
5126 // The select's profile becomes the profile of the conditional branch that
5127 // replaces the indirect branch.
5128 SmallVector<uint32_t> SelectBranchWeights(2);
5130 extractBranchWeights(*SI, SelectBranchWeights);
5131 // Perform the actual simplification.
5132 return simplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
5133 SelectBranchWeights[0],
5134 SelectBranchWeights[1]);
5135}
5136
5137/// This is called when we find an icmp instruction
5138/// (a seteq/setne with a constant) as the only instruction in a
5139/// block that ends with an uncond branch. We are looking for a very specific
5140/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
5141/// this case, we merge the first two "or's of icmp" into a switch, but then the
5142/// default value goes to an uncond block with a seteq in it, we get something
5143/// like:
5144///
5145/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
5146/// DEFAULT:
5147/// %tmp = icmp eq i8 %A, 92
5148/// br label %end
5149/// end:
5150/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
5151///
5152/// We prefer to split the edge to 'end' so that there is a true/false entry to
5153/// the PHI, merging the third icmp into the switch.
5154bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
5155 ICmpInst *ICI, IRBuilder<> &Builder) {
5156 // Select == nullptr means we assume that there is a hidden no-op select
5157 // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...`
5158 return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, nullptr, Builder);
5159}
5160
5161/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic
5162/// case. This is called when we find an icmp instruction (a seteq/setne with a
5163/// constant) and its following select instruction as the only TWO instructions
5164/// in a block that ends with an uncond branch. We are looking for a very
5165/// specific pattern that occurs when "
5166/// if (A == 1) return C1;
5167/// if (A == 2) return C2;
5168/// if (A < 3) return C3;
5169/// return C4;
5170/// " gets simplified. In this case, we merge the first two "branches of icmp"
5171/// into a switch, but then the default value goes to an uncond block with a lt
5172/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2".
5173/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might
5174/// get something like:
5175///
5176/// case1:
5177/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ]
5178/// case2:
5179/// br label %end
5180/// DEFAULT:
5181/// %tmp = icmp eq i8 %A, 2
5182/// %val = select i1 %tmp, i8 C3, i8 C4
5183/// br label %end
5184/// end:
5185/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ]
5186///
5187/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4
5188/// to the PHI, merging the icmp & select into the switch, as follows:
5189///
5190/// case1:
5191/// switch i8 %A, label %DEFAULT [
5192/// i8 0, label %end
5193/// i8 1, label %case2
5194/// i8 2, label %case3
5195/// ]
5196/// case2:
5197/// br label %end
5198/// case3:
5199/// br label %end
5200/// DEFAULT:
5201/// br label %end
5202/// end:
5203/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT]
5204bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
5205 ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) {
5206 BasicBlock *BB = ICI->getParent();
5207
5208 // If the block has any PHIs in it or the icmp/select has multiple uses, it is
5209 // too complex.
5210 /// TODO: support multi-phis in succ BB of select's BB.
5211 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse() ||
5212 (Select && !Select->hasOneUse()))
5213 return false;
5214
5215 // The pattern we're looking for is where our only predecessor is a switch on
5216 // 'V' and this block is the default case for the switch. In this case we can
5217 // fold the compared value into the switch to simplify things.
5218 BasicBlock *Pred = BB->getSinglePredecessor();
5219 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
5220 return false;
5221
5222 Value *IcmpCond;
5223 ConstantInt *NewCaseVal;
5224 CmpPredicate Predicate;
5225
5226 // Match icmp X, C
5227 if (!match(ICI,
5228 m_ICmp(Predicate, m_Value(IcmpCond), m_ConstantInt(NewCaseVal))))
5229 return false;
5230
5231 Value *SelectCond, *SelectTrueVal, *SelectFalseVal;
5233 if (!Select) {
5234 // If Select == nullptr, we can assume that there is a hidden no-op select
5235 // just after icmp
5236 SelectCond = ICI;
5237 SelectTrueVal = Builder.getTrue();
5238 SelectFalseVal = Builder.getFalse();
5239 User = ICI->user_back();
5240 } else {
5241 SelectCond = Select->getCondition();
5242 // Check if the select condition is the same as the icmp condition.
5243 if (SelectCond != ICI)
5244 return false;
5245 SelectTrueVal = Select->getTrueValue();
5246 SelectFalseVal = Select->getFalseValue();
5247 User = Select->user_back();
5248 }
5249
5250 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
5251 if (SI->getCondition() != IcmpCond)
5252 return false;
5253
5254 // If BB is reachable on a non-default case, then we simply know the value of
5255 // V in this block. Substitute it and constant fold the icmp instruction
5256 // away.
5257 if (SI->getDefaultDest() != BB) {
5258 ConstantInt *VVal = SI->findCaseDest(BB);
5259 assert(VVal && "Should have a unique destination value");
5260 ICI->setOperand(0, VVal);
5261
5262 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
5263 ICI->replaceAllUsesWith(V);
5264 ICI->eraseFromParent();
5265 }
5266 // BB is now empty, so it is likely to simplify away.
5267 return requestResimplify();
5268 }
5269
5270 // Ok, the block is reachable from the default dest. If the constant we're
5271 // comparing exists in one of the other edges, then we can constant fold ICI
5272 // and zap it.
5273 if (SI->findCaseValue(NewCaseVal) != SI->case_default()) {
5274 Value *V;
5275 if (Predicate == ICmpInst::ICMP_EQ)
5277 else
5279
5280 ICI->replaceAllUsesWith(V);
5281 ICI->eraseFromParent();
5282 // BB is now empty, so it is likely to simplify away.
5283 return requestResimplify();
5284 }
5285
5286 // The use of the select has to be in the 'end' block, by the only PHI node in
5287 // the block.
5288 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
5289 PHINode *PHIUse = dyn_cast<PHINode>(User);
5290 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
5292 return false;
5293
5294 // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new
5295 // edge gets SelectTrueVal in the PHI.
5296 Value *DefaultCst = SelectFalseVal;
5297 Value *NewCst = SelectTrueVal;
5298
5299 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
5300 std::swap(DefaultCst, NewCst);
5301
5302 // Replace Select (which is used by the PHI for the default value) with
5303 // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE.
5304 if (Select) {
5305 Select->replaceAllUsesWith(DefaultCst);
5306 Select->eraseFromParent();
5307 } else {
5308 ICI->replaceAllUsesWith(DefaultCst);
5309 }
5310 ICI->eraseFromParent();
5311
5312 SmallVector<DominatorTree::UpdateType, 2> Updates;
5313
5314 // Okay, the switch goes to this block on a default value. Add an edge from
5315 // the switch to the merge point on the compared value.
5316 BasicBlock *NewBB =
5317 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
5318 {
5319 SwitchInstProfUpdateWrapper SIW(*SI);
5320 auto W0 = SIW.getSuccessorWeight(0);
5322 if (W0) {
5323 NewW = ((uint64_t(*W0) + 1) >> 1);
5324 SIW.setSuccessorWeight(0, *NewW);
5325 }
5326 SIW.addCase(NewCaseVal, NewBB, NewW);
5327 if (DTU)
5328 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
5329 }
5330
5331 // NewBB branches to the phi block, add the uncond branch and the phi entry.
5332 Builder.SetInsertPoint(NewBB);
5333 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
5334 Builder.CreateBr(SuccBlock);
5335 PHIUse->addIncoming(NewCst, NewBB);
5336 if (DTU) {
5337 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
5338 DTU->applyUpdates(Updates);
5339 }
5340 return true;
5341}
5342
5343/// Check to see if it is branching on an or/and chain of icmp instructions, and
5344/// fold it into a switch instruction if so.
5345bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
5346 IRBuilder<> &Builder,
5347 const DataLayout &DL) {
5349 if (!Cond)
5350 return false;
5351
5352 // Change br (X == 0 | X == 1), T, F into a switch instruction.
5353 // If this is a bunch of seteq's or'd together, or if it's a bunch of
5354 // 'setne's and'ed together, collect them.
5355
5356 // Try to gather values from a chain of and/or to be turned into a switch
5357 ConstantComparesGatherer ConstantCompare(Cond, DL);
5358 // Unpack the result
5359 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
5360 Value *CompVal = ConstantCompare.CompValue;
5361 unsigned UsedICmps = ConstantCompare.UsedICmps;
5362 Value *ExtraCase = ConstantCompare.Extra;
5363 bool TrueWhenEqual = ConstantCompare.IsEq;
5364
5365 // If we didn't have a multiply compared value, fail.
5366 if (!CompVal)
5367 return false;
5368
5369 // Avoid turning single icmps into a switch.
5370 if (UsedICmps <= 1)
5371 return false;
5372
5373 // There might be duplicate constants in the list, which the switch
5374 // instruction can't handle, remove them now.
5376 Values.erase(llvm::unique(Values), Values.end());
5377
5378 // If Extra was used, we require at least two switch values to do the
5379 // transformation. A switch with one value is just a conditional branch.
5380 if (ExtraCase && Values.size() < 2)
5381 return false;
5382
5383 SmallVector<uint32_t> BranchWeights;
5384 const bool HasProfile = !ProfcheckDisableMetadataFixes &&
5385 extractBranchWeights(*BI, BranchWeights);
5386
5387 // Figure out which block is which destination.
5388 BasicBlock *DefaultBB = BI->getSuccessor(1);
5389 BasicBlock *EdgeBB = BI->getSuccessor(0);
5390 if (!TrueWhenEqual) {
5391 std::swap(DefaultBB, EdgeBB);
5392 if (HasProfile)
5393 std::swap(BranchWeights[0], BranchWeights[1]);
5394 }
5395
5396 BasicBlock *BB = BI->getParent();
5397
5398 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
5399 << " cases into SWITCH. BB is:\n"
5400 << *BB);
5401
5402 SmallVector<DominatorTree::UpdateType, 2> Updates;
5403
5404 // If there are any extra values that couldn't be folded into the switch
5405 // then we evaluate them with an explicit branch first. Split the block
5406 // right before the condbr to handle it.
5407 if (ExtraCase) {
5408 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
5409 /*MSSAU=*/nullptr, "switch.early.test");
5410
5411 // Remove the uncond branch added to the old block.
5412 Instruction *OldTI = BB->getTerminator();
5413 Builder.SetInsertPoint(OldTI);
5414
5415 // There can be an unintended UB if extra values are Poison. Before the
5416 // transformation, extra values may not be evaluated according to the
5417 // condition, and it will not raise UB. But after transformation, we are
5418 // evaluating extra values before checking the condition, and it will raise
5419 // UB. It can be solved by adding freeze instruction to extra values.
5420 AssumptionCache *AC = Options.AC;
5421
5422 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
5423 ExtraCase = Builder.CreateFreeze(ExtraCase);
5424
5425 // We don't have any info about this condition.
5426 auto *Br = TrueWhenEqual ? Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB)
5427 : Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
5429
5430 OldTI->eraseFromParent();
5431
5432 if (DTU)
5433 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
5434
5435 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
5436 // for the edge we just added.
5437 addPredecessorToBlock(EdgeBB, BB, NewBB);
5438
5439 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
5440 << "\nEXTRABB = " << *BB);
5441 BB = NewBB;
5442 }
5443
5444 Builder.SetInsertPoint(BI);
5445 // Convert pointer to int before we switch.
5446 if (CompVal->getType()->isPointerTy()) {
5447 assert(!DL.hasUnstableRepresentation(CompVal->getType()) &&
5448 "Should not end up here with unstable pointers");
5449 CompVal = Builder.CreatePtrToInt(
5450 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
5451 }
5452
5453 // Check if we can represent the values as a contiguous range. If so, we use a
5454 // range check + conditional branch instead of a switch.
5455 if (Values.front()->getValue() - Values.back()->getValue() ==
5456 Values.size() - 1) {
5457 ConstantRange RangeToCheck = ConstantRange::getNonEmpty(
5458 Values.back()->getValue(), Values.front()->getValue() + 1);
5459 APInt Offset, RHS;
5460 ICmpInst::Predicate Pred;
5461 RangeToCheck.getEquivalentICmp(Pred, RHS, Offset);
5462 Value *X = CompVal;
5463 if (!Offset.isZero())
5464 X = Builder.CreateAdd(X, ConstantInt::get(CompVal->getType(), Offset));
5465 Value *Cond =
5466 Builder.CreateICmp(Pred, X, ConstantInt::get(CompVal->getType(), RHS));
5467 CondBrInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
5468 if (HasProfile)
5469 setBranchWeights(*NewBI, BranchWeights, /*IsExpected=*/false);
5470 // We don't need to update PHI nodes since we don't add any new edges.
5471 } else {
5472 // Create the new switch instruction now.
5473 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
5474 if (HasProfile) {
5475 // We know the weight of the default case. We don't know the weight of the
5476 // other cases, but rather than completely lose profiling info, we split
5477 // the remaining probability equally over them.
5478 SmallVector<uint32_t> NewWeights(Values.size() + 1);
5479 NewWeights[0] = BranchWeights[1]; // this is the default, and we swapped
5480 // if TrueWhenEqual.
5481 for (auto &V : drop_begin(NewWeights))
5482 V = BranchWeights[0] / Values.size();
5483 setBranchWeights(*New, NewWeights, /*IsExpected=*/false);
5484 }
5485
5486 // Add all of the 'cases' to the switch instruction.
5487 for (ConstantInt *Val : Values)
5488 New->addCase(Val, EdgeBB);
5489
5490 // We added edges from PI to the EdgeBB. As such, if there were any
5491 // PHI nodes in EdgeBB, they need entries to be added corresponding to
5492 // the number of edges added.
5493 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
5494 PHINode *PN = cast<PHINode>(BBI);
5495 Value *InVal = PN->getIncomingValueForBlock(BB);
5496 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5497 PN->addIncoming(InVal, BB);
5498 }
5499 }
5500
5501 // Erase the old branch instruction.
5503 if (DTU)
5504 DTU->applyUpdates(Updates);
5505
5506 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5507 return true;
5508}
5509
5510bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5511 if (isa<PHINode>(RI->getValue()))
5512 return simplifyCommonResume(RI);
5513 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHIIt()) &&
5514 RI->getValue() == &*RI->getParent()->getFirstNonPHIIt())
5515 // The resume must unwind the exception that caused control to branch here.
5516 return simplifySingleResume(RI);
5517
5518 return false;
5519}
5520
5521// Check if cleanup block is empty
5523 for (Instruction &I : R) {
5524 auto *II = dyn_cast<IntrinsicInst>(&I);
5525 if (!II)
5526 return false;
5527
5528 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
5529 switch (IntrinsicID) {
5530 case Intrinsic::dbg_declare:
5531 case Intrinsic::dbg_value:
5532 case Intrinsic::dbg_label:
5533 case Intrinsic::lifetime_end:
5534 break;
5535 default:
5536 return false;
5537 }
5538 }
5539 return true;
5540}
5541
5542// Simplify resume that is shared by several landing pads (phi of landing pad).
5543bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5544 BasicBlock *BB = RI->getParent();
5545
5546 // Check that there are no other instructions except for debug and lifetime
5547 // intrinsics between the phi's and resume instruction.
5548 if (!isCleanupBlockEmpty(make_range(RI->getParent()->getFirstNonPHIIt(),
5549 BB->getTerminator()->getIterator())))
5550 return false;
5551
5552 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5553 auto *PhiLPInst = cast<PHINode>(RI->getValue());
5554
5555 // Check incoming blocks to see if any of them are trivial.
5556 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5557 Idx++) {
5558 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
5559 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
5560
5561 // If the block has other successors, we can not delete it because
5562 // it has other dependents.
5563 if (IncomingBB->getUniqueSuccessor() != BB)
5564 continue;
5565
5566 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHIIt());
5567 // Not the landing pad that caused the control to branch here.
5568 if (IncomingValue != LandingPad)
5569 continue;
5570
5572 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
5573 TrivialUnwindBlocks.insert(IncomingBB);
5574 }
5575
5576 // If no trivial unwind blocks, don't do any simplifications.
5577 if (TrivialUnwindBlocks.empty())
5578 return false;
5579
5580 // Turn all invokes that unwind here into calls.
5581 for (auto *TrivialBB : TrivialUnwindBlocks) {
5582 // Blocks that will be simplified should be removed from the phi node.
5583 // Note there could be multiple edges to the resume block, and we need
5584 // to remove them all.
5585 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
5586 BB->removePredecessor(TrivialBB, true);
5587
5588 for (BasicBlock *Pred :
5590 removeUnwindEdge(Pred, DTU);
5591 ++NumInvokes;
5592 }
5593
5594 // In each SimplifyCFG run, only the current processed block can be erased.
5595 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5596 // of erasing TrivialBB, we only remove the branch to the common resume
5597 // block so that we can later erase the resume block since it has no
5598 // predecessors.
5599 TrivialBB->getTerminator()->eraseFromParent();
5600 new UnreachableInst(RI->getContext(), TrivialBB);
5601 if (DTU)
5602 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
5603 }
5604
5605 // Delete the resume block if all its predecessors have been removed.
5606 if (pred_empty(BB))
5607 DeleteDeadBlock(BB, DTU);
5608
5609 return !TrivialUnwindBlocks.empty();
5610}
5611
5612// Simplify resume that is only used by a single (non-phi) landing pad.
5613bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5614 BasicBlock *BB = RI->getParent();
5615 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHIIt());
5616 assert(RI->getValue() == LPInst &&
5617 "Resume must unwind the exception that caused control to here");
5618
5619 // Check that there are no other instructions except for debug intrinsics.
5621 make_range<Instruction *>(LPInst->getNextNode(), RI)))
5622 return false;
5623
5624 // Turn all invokes that unwind here into calls and delete the basic block.
5625 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
5626 removeUnwindEdge(Pred, DTU);
5627 ++NumInvokes;
5628 }
5629
5630 // The landingpad is now unreachable. Zap it.
5631 DeleteDeadBlock(BB, DTU);
5632 return true;
5633}
5634
5636 // If this is a trivial cleanup pad that executes no instructions, it can be
5637 // eliminated. If the cleanup pad continues to the caller, any predecessor
5638 // that is an EH pad will be updated to continue to the caller and any
5639 // predecessor that terminates with an invoke instruction will have its invoke
5640 // instruction converted to a call instruction. If the cleanup pad being
5641 // simplified does not continue to the caller, each predecessor will be
5642 // updated to continue to the unwind destination of the cleanup pad being
5643 // simplified.
5644 BasicBlock *BB = RI->getParent();
5645 CleanupPadInst *CPInst = RI->getCleanupPad();
5646 if (CPInst->getParent() != BB)
5647 // This isn't an empty cleanup.
5648 return false;
5649
5650 // We cannot kill the pad if it has multiple uses. This typically arises
5651 // from unreachable basic blocks.
5652 if (!CPInst->hasOneUse())
5653 return false;
5654
5655 // Check that there are no other instructions except for benign intrinsics.
5657 make_range<Instruction *>(CPInst->getNextNode(), RI)))
5658 return false;
5659
5660 // If the cleanup return we are simplifying unwinds to the caller, this will
5661 // set UnwindDest to nullptr.
5662 BasicBlock *UnwindDest = RI->getUnwindDest();
5663
5664 // We're about to remove BB from the control flow. Before we do, sink any
5665 // PHINodes into the unwind destination. Doing this before changing the
5666 // control flow avoids some potentially slow checks, since we can currently
5667 // be certain that UnwindDest and BB have no common predecessors (since they
5668 // are both EH pads).
5669 if (UnwindDest) {
5670 // First, go through the PHI nodes in UnwindDest and update any nodes that
5671 // reference the block we are removing
5672 for (PHINode &DestPN : UnwindDest->phis()) {
5673 int Idx = DestPN.getBasicBlockIndex(BB);
5674 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5675 assert(Idx != -1);
5676 // This PHI node has an incoming value that corresponds to a control
5677 // path through the cleanup pad we are removing. If the incoming
5678 // value is in the cleanup pad, it must be a PHINode (because we
5679 // verified above that the block is otherwise empty). Otherwise, the
5680 // value is either a constant or a value that dominates the cleanup
5681 // pad being removed.
5682 //
5683 // Because BB and UnwindDest are both EH pads, all of their
5684 // predecessors must unwind to these blocks, and since no instruction
5685 // can have multiple unwind destinations, there will be no overlap in
5686 // incoming blocks between SrcPN and DestPN.
5687 Value *SrcVal = DestPN.getIncomingValue(Idx);
5688 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
5689
5690 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5691 for (auto *Pred : predecessors(BB)) {
5692 Value *Incoming =
5693 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
5694 DestPN.addIncoming(Incoming, Pred);
5695 }
5696 }
5697
5698 // Sink any remaining PHI nodes directly into UnwindDest.
5699 BasicBlock::iterator InsertPt = UnwindDest->getFirstNonPHIIt();
5700 for (PHINode &PN : make_early_inc_range(BB->phis())) {
5701 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5702 // If the PHI node has no uses or all of its uses are in this basic
5703 // block (meaning they are debug or lifetime intrinsics), just leave
5704 // it. It will be erased when we erase BB below.
5705 continue;
5706
5707 // Otherwise, sink this PHI node into UnwindDest.
5708 // Any predecessors to UnwindDest which are not already represented
5709 // must be back edges which inherit the value from the path through
5710 // BB. In this case, the PHI value must reference itself.
5711 for (auto *pred : predecessors(UnwindDest))
5712 if (pred != BB)
5713 PN.addIncoming(&PN, pred);
5714 PN.moveBefore(InsertPt);
5715 // Also, add a dummy incoming value for the original BB itself,
5716 // so that the PHI is well-formed until we drop said predecessor.
5717 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5718 }
5719 }
5720
5721 std::vector<DominatorTree::UpdateType> Updates;
5722
5723 // We use make_early_inc_range here because we will remove all predecessors.
5725 if (UnwindDest == nullptr) {
5726 if (DTU) {
5727 DTU->applyUpdates(Updates);
5728 Updates.clear();
5729 }
5730 removeUnwindEdge(PredBB, DTU);
5731 ++NumInvokes;
5732 } else {
5733 BB->removePredecessor(PredBB);
5734 Instruction *TI = PredBB->getTerminator();
5735 TI->replaceUsesOfWith(BB, UnwindDest);
5736 if (DTU) {
5737 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5738 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5739 }
5740 }
5741 }
5742
5743 if (DTU)
5744 DTU->applyUpdates(Updates);
5745
5746 DeleteDeadBlock(BB, DTU);
5747
5748 return true;
5749}
5750
5751// Try to merge two cleanuppads together.
5753 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5754 // with.
5755 BasicBlock *UnwindDest = RI->getUnwindDest();
5756 if (!UnwindDest)
5757 return false;
5758
5759 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5760 // be safe to merge without code duplication.
5761 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5762 return false;
5763
5764 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5765 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5766 if (!SuccessorCleanupPad)
5767 return false;
5768
5769 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5770 // Replace any uses of the successor cleanupad with the predecessor pad
5771 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5772 // funclet bundle operands.
5773 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5774 // Remove the old cleanuppad.
5775 SuccessorCleanupPad->eraseFromParent();
5776 // Now, we simply replace the cleanupret with a branch to the unwind
5777 // destination.
5778 UncondBrInst::Create(UnwindDest, RI->getParent());
5779 RI->eraseFromParent();
5780
5781 return true;
5782}
5783
5784bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5785 // It is possible to transiantly have an undef cleanuppad operand because we
5786 // have deleted some, but not all, dead blocks.
5787 // Eventually, this block will be deleted.
5788 if (isa<UndefValue>(RI->getOperand(0)))
5789 return false;
5790
5791 if (mergeCleanupPad(RI))
5792 return true;
5793
5794 if (removeEmptyCleanup(RI, DTU))
5795 return true;
5796
5797 return false;
5798}
5799
5800// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5801bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5802 BasicBlock *BB = UI->getParent();
5803
5804 bool Changed = false;
5805
5806 // Ensure that any debug-info records that used to occur after the Unreachable
5807 // are moved to in front of it -- otherwise they'll "dangle" at the end of
5808 // the block.
5810
5811 // Debug-info records on the unreachable inst itself should be deleted, as
5812 // below we delete everything past the final executable instruction.
5813 UI->dropDbgRecords();
5814
5815 // If there are any instructions immediately before the unreachable that can
5816 // be removed, do so.
5817 while (UI->getIterator() != BB->begin()) {
5819 --BBI;
5820
5822 break; // Can not drop any more instructions. We're done here.
5823 // Otherwise, this instruction can be freely erased,
5824 // even if it is not side-effect free.
5825
5826 // Note that deleting EH's here is in fact okay, although it involves a bit
5827 // of subtle reasoning. If this inst is an EH, all the predecessors of this
5828 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
5829 // and we can therefore guarantee this block will be erased.
5830
5831 // If we're deleting this, we're deleting any subsequent debug info, so
5832 // delete DbgRecords.
5833 BBI->dropDbgRecords();
5834
5835 // Delete this instruction (any uses are guaranteed to be dead)
5836 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
5837 BBI->eraseFromParent();
5838 Changed = true;
5839 }
5840
5841 // If the unreachable instruction is the first in the block, take a gander
5842 // at all of the predecessors of this instruction, and simplify them.
5843 if (&BB->front() != UI)
5844 return Changed;
5845
5846 std::vector<DominatorTree::UpdateType> Updates;
5847
5848 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
5849 for (BasicBlock *Predecessor : Preds) {
5850 Instruction *TI = Predecessor->getTerminator();
5851 IRBuilder<> Builder(TI);
5852 if (isa<UncondBrInst>(TI)) {
5853 new UnreachableInst(TI->getContext(), TI->getIterator());
5854 TI->eraseFromParent();
5855 Changed = true;
5856 if (DTU)
5857 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5858 } else if (auto *BI = dyn_cast<CondBrInst>(TI)) {
5859 // We could either have a proper unconditional branch,
5860 // or a degenerate conditional branch with matching destinations.
5861 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
5862 new UnreachableInst(TI->getContext(), TI->getIterator());
5863 TI->eraseFromParent();
5864 Changed = true;
5865 } else {
5866 Value* Cond = BI->getCondition();
5867 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5868 "The destinations are guaranteed to be different here.");
5869 CallInst *Assumption;
5870 if (BI->getSuccessor(0) == BB) {
5871 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
5872 Builder.CreateBr(BI->getSuccessor(1));
5873 } else {
5874 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
5875 Assumption = Builder.CreateAssumption(Cond);
5876 Builder.CreateBr(BI->getSuccessor(0));
5877 }
5878 if (Options.AC)
5879 Options.AC->registerAssumption(cast<AssumeInst>(Assumption));
5880
5882 Changed = true;
5883 }
5884 if (DTU)
5885 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5886 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
5887 SwitchInstProfUpdateWrapper SU(*SI);
5888 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
5889 if (i->getCaseSuccessor() != BB) {
5890 ++i;
5891 continue;
5892 }
5893 BB->removePredecessor(SU->getParent());
5894 i = SU.removeCase(i);
5895 e = SU->case_end();
5896 Changed = true;
5897 }
5898 // Note that the default destination can't be removed!
5899 if (DTU && SI->getDefaultDest() != BB)
5900 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5901 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
5902 if (II->getUnwindDest() == BB) {
5903 if (DTU) {
5904 DTU->applyUpdates(Updates);
5905 Updates.clear();
5906 }
5907 auto *CI = cast<CallInst>(removeUnwindEdge(TI->getParent(), DTU));
5908 if (!CI->doesNotThrow())
5909 CI->setDoesNotThrow();
5910 Changed = true;
5911 }
5912 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5913 if (CSI->getUnwindDest() == BB) {
5914 if (DTU) {
5915 DTU->applyUpdates(Updates);
5916 Updates.clear();
5917 }
5918 removeUnwindEdge(TI->getParent(), DTU);
5919 Changed = true;
5920 continue;
5921 }
5922
5923 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
5924 E = CSI->handler_end();
5925 I != E; ++I) {
5926 if (*I == BB) {
5927 CSI->removeHandler(I);
5928 --I;
5929 --E;
5930 Changed = true;
5931 }
5932 }
5933 if (DTU)
5934 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5935 if (CSI->getNumHandlers() == 0) {
5936 if (CSI->hasUnwindDest()) {
5937 // Redirect all predecessors of the block containing CatchSwitchInst
5938 // to instead branch to the CatchSwitchInst's unwind destination.
5939 if (DTU) {
5940 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
5941 Updates.push_back({DominatorTree::Insert,
5942 PredecessorOfPredecessor,
5943 CSI->getUnwindDest()});
5944 Updates.push_back({DominatorTree::Delete,
5945 PredecessorOfPredecessor, Predecessor});
5946 }
5947 }
5948 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
5949 } else {
5950 // Rewrite all preds to unwind to caller (or from invoke to call).
5951 if (DTU) {
5952 DTU->applyUpdates(Updates);
5953 Updates.clear();
5954 }
5955 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
5956 for (BasicBlock *EHPred : EHPreds)
5957 removeUnwindEdge(EHPred, DTU);
5958 }
5959 // The catchswitch is no longer reachable.
5960 new UnreachableInst(CSI->getContext(), CSI->getIterator());
5961 CSI->eraseFromParent();
5962 Changed = true;
5963 }
5964 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
5965 (void)CRI;
5966 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
5967 "Expected to always have an unwind to BB.");
5968 if (DTU)
5969 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5970 new UnreachableInst(TI->getContext(), TI->getIterator());
5971 TI->eraseFromParent();
5972 Changed = true;
5973 }
5974 }
5975
5976 if (DTU)
5977 DTU->applyUpdates(Updates);
5978
5979 // If this block is now dead, remove it.
5980 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
5981 DeleteDeadBlock(BB, DTU);
5982 return true;
5983 }
5984
5985 return Changed;
5986}
5987
5996
5997static std::optional<ContiguousCasesResult>
6000 BasicBlock *Dest, BasicBlock *OtherDest) {
6001 assert(Cases.size() >= 1);
6002
6004 const APInt &Min = Cases.back()->getValue();
6005 const APInt &Max = Cases.front()->getValue();
6006 APInt Offset = Max - Min;
6007 size_t ContiguousOffset = Cases.size() - 1;
6008 if (Offset == ContiguousOffset) {
6009 return ContiguousCasesResult{
6010 /*Min=*/Cases.back(),
6011 /*Max=*/Cases.front(),
6012 /*Dest=*/Dest,
6013 /*OtherDest=*/OtherDest,
6014 /*Cases=*/&Cases,
6015 /*OtherCases=*/&OtherCases,
6016 };
6017 }
6018 ConstantRange CR = computeConstantRange(Condition, /*ForSigned=*/false,
6019 SimplifyQuery(Dest->getDataLayout()));
6020 // If this is a wrapping contiguous range, that is, [Min, OtherMin] +
6021 // [OtherMax, Max] (also [OtherMax, OtherMin]), [OtherMin+1, OtherMax-1] is a
6022 // contiguous range for the other destination. N.B. If CR is not a full range,
6023 // Max+1 is not equal to Min. It's not continuous in arithmetic.
6024 if (Max == CR.getUnsignedMax() && Min == CR.getUnsignedMin()) {
6025 assert(Cases.size() >= 2);
6026 auto *It =
6027 std::adjacent_find(Cases.begin(), Cases.end(), [](auto L, auto R) {
6028 return L->getValue() != R->getValue() + 1;
6029 });
6030 if (It == Cases.end())
6031 return std::nullopt;
6032 auto [OtherMax, OtherMin] = std::make_pair(*It, *std::next(It));
6033 if ((Max - OtherMax->getValue()) + (OtherMin->getValue() - Min) ==
6034 Cases.size() - 2) {
6035 return ContiguousCasesResult{
6036 /*Min=*/cast<ConstantInt>(
6037 ConstantInt::get(OtherMin->getType(), OtherMin->getValue() + 1)),
6038 /*Max=*/
6040 ConstantInt::get(OtherMax->getType(), OtherMax->getValue() - 1)),
6041 /*Dest=*/OtherDest,
6042 /*OtherDest=*/Dest,
6043 /*Cases=*/&OtherCases,
6044 /*OtherCases=*/&Cases,
6045 };
6046 }
6047 }
6048 return std::nullopt;
6049}
6050
6052 DomTreeUpdater *DTU,
6053 bool RemoveOrigDefaultBlock = true) {
6054 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
6055 auto *BB = Switch->getParent();
6056 auto *OrigDefaultBlock = Switch->getDefaultDest();
6057 if (RemoveOrigDefaultBlock)
6058 OrigDefaultBlock->removePredecessor(BB);
6059 BasicBlock *NewDefaultBlock = BasicBlock::Create(
6060 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
6061 OrigDefaultBlock);
6062 auto *UI = new UnreachableInst(Switch->getContext(), NewDefaultBlock);
6064 Switch->setDefaultDest(&*NewDefaultBlock);
6065 if (DTU) {
6067 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
6068 if (RemoveOrigDefaultBlock &&
6069 !is_contained(successors(BB), OrigDefaultBlock))
6070 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
6071 DTU->applyUpdates(Updates);
6072 }
6073}
6074
6075/// Turn a switch into an integer range comparison and branch.
6076/// Switches with more than 2 destinations are ignored.
6077/// Switches with 1 destination are also ignored.
6078bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
6079 IRBuilder<> &Builder) {
6080 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6081
6082 bool HasDefault = !SI->defaultDestUnreachable();
6083
6084 auto *BB = SI->getParent();
6085 // Partition the cases into two sets with different destinations.
6086 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
6087 BasicBlock *DestB = nullptr;
6090
6091 for (auto Case : SI->cases()) {
6092 BasicBlock *Dest = Case.getCaseSuccessor();
6093 if (!DestA)
6094 DestA = Dest;
6095 if (Dest == DestA) {
6096 CasesA.push_back(Case.getCaseValue());
6097 continue;
6098 }
6099 if (!DestB)
6100 DestB = Dest;
6101 if (Dest == DestB) {
6102 CasesB.push_back(Case.getCaseValue());
6103 continue;
6104 }
6105 return false; // More than two destinations.
6106 }
6107 if (!DestB)
6108 return false; // All destinations are the same and the default is unreachable
6109
6110 assert(DestA && DestB &&
6111 "Single-destination switch should have been folded.");
6112 assert(DestA != DestB);
6113 assert(DestB != SI->getDefaultDest());
6114 assert(!CasesB.empty() && "There must be non-default cases.");
6115 assert(!CasesA.empty() || HasDefault);
6116
6117 // Figure out if one of the sets of cases form a contiguous range.
6118 std::optional<ContiguousCasesResult> ContiguousCases;
6119
6120 // Only one icmp is needed when there is only one case.
6121 if (!HasDefault && CasesA.size() == 1)
6122 ContiguousCases = ContiguousCasesResult{
6123 /*Min=*/CasesA[0],
6124 /*Max=*/CasesA[0],
6125 /*Dest=*/DestA,
6126 /*OtherDest=*/DestB,
6127 /*Cases=*/&CasesA,
6128 /*OtherCases=*/&CasesB,
6129 };
6130 else if (CasesB.size() == 1)
6131 ContiguousCases = ContiguousCasesResult{
6132 /*Min=*/CasesB[0],
6133 /*Max=*/CasesB[0],
6134 /*Dest=*/DestB,
6135 /*OtherDest=*/DestA,
6136 /*Cases=*/&CasesB,
6137 /*OtherCases=*/&CasesA,
6138 };
6139 // Correctness: Cases to the default destination cannot be contiguous cases.
6140 else if (!HasDefault)
6141 ContiguousCases =
6142 findContiguousCases(SI->getCondition(), CasesA, CasesB, DestA, DestB);
6143
6144 if (!ContiguousCases)
6145 ContiguousCases =
6146 findContiguousCases(SI->getCondition(), CasesB, CasesA, DestB, DestA);
6147
6148 if (!ContiguousCases)
6149 return false;
6150
6151 auto [Min, Max, Dest, OtherDest, Cases, OtherCases] = *ContiguousCases;
6152
6153 // Start building the compare and branch.
6154
6156 Constant *NumCases = ConstantInt::get(Offset->getType(),
6157 Max->getValue() - Min->getValue() + 1);
6158 Instruction *NewBI;
6159 if (NumCases->isOneValue()) {
6160 assert(Max->getValue() == Min->getValue());
6161 Value *Cmp = Builder.CreateICmpEQ(SI->getCondition(), Min);
6162 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6163 }
6164 // If NumCases overflowed, then all possible values jump to the successor.
6165 else if (NumCases->isNullValue() && !Cases->empty()) {
6166 NewBI = Builder.CreateBr(Dest);
6167 } else {
6168 Value *Sub = SI->getCondition();
6169 if (!Offset->isNullValue())
6170 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
6171 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
6172 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6173 }
6174
6175 // Update weight for the newly-created conditional branch.
6176 if (hasBranchWeightMD(*SI) && isa<CondBrInst>(NewBI)) {
6177 SmallVector<uint64_t, 8> Weights;
6178 getBranchWeights(SI, Weights);
6179 if (Weights.size() == 1 + SI->getNumCases()) {
6180 uint64_t TrueWeight = 0;
6181 uint64_t FalseWeight = 0;
6182 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
6183 if (SI->getSuccessor(I) == Dest)
6184 TrueWeight += Weights[I];
6185 else
6186 FalseWeight += Weights[I];
6187 }
6188 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
6189 TrueWeight /= 2;
6190 FalseWeight /= 2;
6191 }
6192 setFittedBranchWeights(*NewBI, {TrueWeight, FalseWeight},
6193 /*IsExpected=*/false, /*ElideAllZero=*/true);
6194 }
6195 }
6196
6197 // Prune obsolete incoming values off the successors' PHI nodes.
6198 for (auto &PHI : make_early_inc_range(Dest->phis())) {
6199 unsigned PreviousEdges = Cases->size();
6200 if (Dest == SI->getDefaultDest())
6201 ++PreviousEdges;
6202 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
6203 PHI.removeIncomingValue(SI->getParent());
6204 }
6205 for (auto &PHI : make_early_inc_range(OtherDest->phis())) {
6206 unsigned PreviousEdges = OtherCases->size();
6207 if (OtherDest == SI->getDefaultDest())
6208 ++PreviousEdges;
6209 unsigned E = PreviousEdges - 1;
6210 // Remove all incoming values from OtherDest if OtherDest is unreachable.
6211 if (isa<UncondBrInst>(NewBI))
6212 ++E;
6213 for (unsigned I = 0; I != E; ++I)
6214 PHI.removeIncomingValue(SI->getParent());
6215 }
6216
6217 // Clean up the default block.
6218 SmallVector<DominatorTree::UpdateType, 2> Updates;
6219 if (!HasDefault) {
6220 BasicBlock *OrigDefaultBlock = SI->getDefaultDest();
6221 OrigDefaultBlock->removePredecessor(BB);
6222 Updates.push_back({DominatorTree::Delete, BB, OrigDefaultBlock});
6223 }
6224
6225 // Drop the switch.
6226 SI->eraseFromParent();
6227
6228 if (isa<UncondBrInst>(NewBI))
6229 Updates.push_back({DominatorTree::Delete, BB, OtherDest});
6230
6231 if (DTU)
6232 DTU->applyUpdates(Updates);
6233 return true;
6234}
6235
6236/// Compute masked bits for the condition of a switch
6237/// and use it to remove dead cases.
6239 AssumptionCache *AC,
6240 const DataLayout &DL) {
6241 Value *Cond = SI->getCondition();
6244 bool IsKnownValuesValid = collectPossibleValues(Cond, KnownValues, 4);
6245
6246 // We can also eliminate cases by determining that their values are outside of
6247 // the limited range of the condition based on how many significant (non-sign)
6248 // bits are in the condition value.
6249 unsigned MaxSignificantBitsInCond =
6251
6252 // Gather dead cases.
6254 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
6255 SmallVector<BasicBlock *, 8> UniqueSuccessors;
6256 for (const auto &Case : SI->cases()) {
6257 auto *Successor = Case.getCaseSuccessor();
6258 if (DTU) {
6259 auto [It, Inserted] = NumPerSuccessorCases.try_emplace(Successor);
6260 if (Inserted)
6261 UniqueSuccessors.push_back(Successor);
6262 ++It->second;
6263 }
6264 ConstantInt *CaseC = Case.getCaseValue();
6265 const APInt &CaseVal = CaseC->getValue();
6266 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
6267 (CaseVal.getSignificantBits() > MaxSignificantBitsInCond) ||
6268 (IsKnownValuesValid && !KnownValues.contains(CaseC))) {
6269 DeadCases.push_back(CaseC);
6270 if (DTU)
6271 --NumPerSuccessorCases[Successor];
6272 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
6273 << " is dead.\n");
6274 } else if (IsKnownValuesValid)
6275 KnownValues.erase(CaseC);
6276 }
6277
6278 // If we can prove that the cases must cover all possible values, the
6279 // default destination becomes dead and we can remove it. If we know some
6280 // of the bits in the value, we can use that to more precisely compute the
6281 // number of possible unique case values.
6282 bool HasDefault = !SI->defaultDestUnreachable();
6283 const unsigned NumUnknownBits =
6284 Known.getBitWidth() - (Known.Zero | Known.One).popcount();
6285 assert(NumUnknownBits <= Known.getBitWidth());
6286 if (HasDefault && DeadCases.empty()) {
6287 if (IsKnownValuesValid && all_of(KnownValues, IsaPred<UndefValue>)) {
6289 return true;
6290 }
6291
6292 if (NumUnknownBits < 64 /* avoid overflow */) {
6293 uint64_t AllNumCases = 1ULL << NumUnknownBits;
6294 if (SI->getNumCases() == AllNumCases) {
6296 return true;
6297 }
6298 // When only one case value is missing, replace default with that case.
6299 // Eliminating the default branch will provide more opportunities for
6300 // optimization, such as lookup tables.
6301 if (SI->getNumCases() == AllNumCases - 1) {
6302 assert(NumUnknownBits > 1 && "Should be canonicalized to a branch");
6303 IntegerType *CondTy = cast<IntegerType>(Cond->getType());
6304 if (CondTy->getIntegerBitWidth() > 64 ||
6305 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6306 return false;
6307
6308 uint64_t MissingCaseVal = 0;
6309 for (const auto &Case : SI->cases())
6310 MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
6311 auto *MissingCase = cast<ConstantInt>(
6312 ConstantInt::get(Cond->getType(), MissingCaseVal));
6314 SIW.addCase(MissingCase, SI->getDefaultDest(),
6315 SIW.getSuccessorWeight(0));
6317 /*RemoveOrigDefaultBlock*/ false);
6318 SIW.setSuccessorWeight(0, 0);
6319 return true;
6320 }
6321 }
6322 }
6323
6324 if (DeadCases.empty())
6325 return false;
6326
6328 for (ConstantInt *DeadCase : DeadCases) {
6329 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
6330 assert(CaseI != SI->case_default() &&
6331 "Case was not found. Probably mistake in DeadCases forming.");
6332 // Prune unused values from PHI nodes.
6333 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
6334 SIW.removeCase(CaseI);
6335 }
6336
6337 if (DTU) {
6338 std::vector<DominatorTree::UpdateType> Updates;
6339 for (auto *Successor : UniqueSuccessors)
6340 if (NumPerSuccessorCases[Successor] == 0)
6341 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
6342 DTU->applyUpdates(Updates);
6343 }
6344
6345 return true;
6346}
6347
6348/// If BB would be eligible for simplification by
6349/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
6350/// by an unconditional branch), look at the phi node for BB in the successor
6351/// block and see if the incoming value is equal to CaseValue. If so, return
6352/// the phi node, and set PhiIndex to BB's index in the phi node.
6354 BasicBlock *BB, int *PhiIndex) {
6355 if (&*BB->getFirstNonPHIIt() != BB->getTerminator())
6356 return nullptr; // BB must be empty to be a candidate for simplification.
6357 if (!BB->getSinglePredecessor())
6358 return nullptr; // BB must be dominated by the switch.
6359
6361 if (!Branch)
6362 return nullptr; // Terminator must be unconditional branch.
6363
6364 BasicBlock *Succ = Branch->getSuccessor();
6365
6366 for (PHINode &PHI : Succ->phis()) {
6367 int Idx = PHI.getBasicBlockIndex(BB);
6368 assert(Idx >= 0 && "PHI has no entry for predecessor?");
6369
6370 Value *InValue = PHI.getIncomingValue(Idx);
6371 if (InValue != CaseValue)
6372 continue;
6373
6374 *PhiIndex = Idx;
6375 return &PHI;
6376 }
6377
6378 return nullptr;
6379}
6380
6381/// Try to forward the condition of a switch instruction to a phi node
6382/// dominated by the switch, if that would mean that some of the destination
6383/// blocks of the switch can be folded away. Return true if a change is made.
6385 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
6386
6387 ForwardingNodesMap ForwardingNodes;
6388 BasicBlock *SwitchBlock = SI->getParent();
6389 bool Changed = false;
6390 for (const auto &Case : SI->cases()) {
6391 ConstantInt *CaseValue = Case.getCaseValue();
6392 BasicBlock *CaseDest = Case.getCaseSuccessor();
6393
6394 // Replace phi operands in successor blocks that are using the constant case
6395 // value rather than the switch condition variable:
6396 // switchbb:
6397 // switch i32 %x, label %default [
6398 // i32 17, label %succ
6399 // ...
6400 // succ:
6401 // %r = phi i32 ... [ 17, %switchbb ] ...
6402 // -->
6403 // %r = phi i32 ... [ %x, %switchbb ] ...
6404
6405 for (PHINode &Phi : CaseDest->phis()) {
6406 // This only works if there is exactly 1 incoming edge from the switch to
6407 // a phi. If there is >1, that means multiple cases of the switch map to 1
6408 // value in the phi, and that phi value is not the switch condition. Thus,
6409 // this transform would not make sense (the phi would be invalid because
6410 // a phi can't have different incoming values from the same block).
6411 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
6412 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
6413 count(Phi.blocks(), SwitchBlock) == 1) {
6414 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
6415 Changed = true;
6416 }
6417 }
6418
6419 // Collect phi nodes that are indirectly using this switch's case constants.
6420 int PhiIdx;
6421 if (auto *Phi = findPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
6422 ForwardingNodes[Phi].push_back(PhiIdx);
6423 }
6424
6425 for (auto &ForwardingNode : ForwardingNodes) {
6426 PHINode *Phi = ForwardingNode.first;
6427 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
6428 // Check if it helps to fold PHI.
6429 if (Indexes.size() < 2 && !llvm::is_contained(Phi->incoming_values(), SI->getCondition()))
6430 continue;
6431
6432 for (int Index : Indexes)
6433 Phi->setIncomingValue(Index, SI->getCondition());
6434 Changed = true;
6435 }
6436
6437 return Changed;
6438}
6439
6440/// Return true if the backend will be able to handle
6441/// initializing an array of constants like C.
6443 if (C->isThreadDependent())
6444 return false;
6445 if (C->isDLLImportDependent())
6446 return false;
6447
6450 return false;
6451
6452 // Globals cannot contain scalable types.
6453 if (C->getType()->isScalableTy())
6454 return false;
6455
6457 // Pointer casts and in-bounds GEPs will not prohibit the backend from
6458 // materializing the array of constants.
6459 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
6460 if (StrippedC == C || !validLookupTableConstant(StrippedC, TTI))
6461 return false;
6462 }
6463
6464 if (!TTI.shouldBuildLookupTablesForConstant(C))
6465 return false;
6466
6467 return true;
6468}
6469
6470/// If V is a Constant, return it. Otherwise, try to look up
6471/// its constant value in ConstantPool, returning 0 if it's not there.
6472static Constant *
6475 if (Constant *C = dyn_cast<Constant>(V))
6476 return C;
6477 return ConstantPool.lookup(V);
6478}
6479
6480/// Try to fold instruction I into a constant. This works for
6481/// simple instructions such as binary operations where both operands are
6482/// constant or can be replaced by constants from the ConstantPool. Returns the
6483/// resulting constant on success, 0 otherwise.
6484static Constant *
6488 Constant *A = lookupConstant(Select->getCondition(), ConstantPool);
6489 if (!A)
6490 return nullptr;
6491 if (A->isAllOnesValue())
6492 return lookupConstant(Select->getTrueValue(), ConstantPool);
6493 if (A->isNullValue())
6494 return lookupConstant(Select->getFalseValue(), ConstantPool);
6495 return nullptr;
6496 }
6497
6499 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
6500 if (Constant *A = lookupConstant(I->getOperand(N), ConstantPool))
6501 COps.push_back(A);
6502 else
6503 return nullptr;
6504 }
6505
6506 return ConstantFoldInstOperands(I, COps, DL);
6507}
6508
6509/// Try to determine the resulting constant values in phi nodes
6510/// at the common destination basic block, *CommonDest, for one of the case
6511/// destinations CaseDest corresponding to value CaseVal (nullptr for the
6512/// default case), of a switch instruction SI.
6513static bool
6515 BasicBlock **CommonDest,
6516 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
6517 const DataLayout &DL, const TargetTransformInfo &TTI) {
6518 // The block from which we enter the common destination.
6519 BasicBlock *Pred = SI->getParent();
6520
6521 // If CaseDest is empty except for some side-effect free instructions through
6522 // which we can constant-propagate the CaseVal, continue to its successor.
6524 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
6525 for (Instruction &I : *CaseDest) {
6526 if (I.isTerminator()) {
6527 // If the terminator is a simple branch, continue to the next block.
6528 if (I.getNumSuccessors() != 1 || I.isSpecialTerminator())
6529 return false;
6530 Pred = CaseDest;
6531 CaseDest = I.getSuccessor(0);
6532 } else if (Constant *C = constantFold(&I, DL, ConstantPool)) {
6533 // Instruction is side-effect free and constant.
6534
6535 // If the instruction has uses outside this block or a phi node slot for
6536 // the block, it is not safe to bypass the instruction since it would then
6537 // no longer dominate all its uses.
6538 for (auto &Use : I.uses()) {
6539 User *User = Use.getUser();
6541 if (I->getParent() == CaseDest)
6542 continue;
6543 if (PHINode *Phi = dyn_cast<PHINode>(User))
6544 if (Phi->getIncomingBlock(Use) == CaseDest)
6545 continue;
6546 return false;
6547 }
6548
6549 ConstantPool.insert(std::make_pair(&I, C));
6550 } else {
6551 break;
6552 }
6553 }
6554
6555 // If we did not have a CommonDest before, use the current one.
6556 if (!*CommonDest)
6557 *CommonDest = CaseDest;
6558 // If the destination isn't the common one, abort.
6559 if (CaseDest != *CommonDest)
6560 return false;
6561
6562 // Get the values for this case from phi nodes in the destination block.
6563 for (PHINode &PHI : (*CommonDest)->phis()) {
6564 int Idx = PHI.getBasicBlockIndex(Pred);
6565 if (Idx == -1)
6566 continue;
6567
6568 Constant *ConstVal =
6569 lookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
6570 if (!ConstVal)
6571 return false;
6572
6573 // Be conservative about which kinds of constants we support.
6574 if (!validLookupTableConstant(ConstVal, TTI))
6575 return false;
6576
6577 Res.push_back(std::make_pair(&PHI, ConstVal));
6578 }
6579
6580 return Res.size() > 0;
6581}
6582
6583// Helper function used to add CaseVal to the list of cases that generate
6584// Result. Returns the updated number of cases that generate this result.
6585static size_t mapCaseToResult(ConstantInt *CaseVal,
6586 SwitchCaseResultVectorTy &UniqueResults,
6587 Constant *Result) {
6588 for (auto &I : UniqueResults) {
6589 if (I.first == Result) {
6590 I.second.push_back(CaseVal);
6591 return I.second.size();
6592 }
6593 }
6594 UniqueResults.push_back(
6595 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
6596 return 1;
6597}
6598
6599// Helper function that initializes a map containing
6600// results for the PHI node of the common destination block for a switch
6601// instruction. Returns false if multiple PHI nodes have been found or if
6602// there is not a common destination block for the switch.
6604 BasicBlock *&CommonDest,
6605 SwitchCaseResultVectorTy &UniqueResults,
6606 Constant *&DefaultResult,
6607 const DataLayout &DL,
6608 const TargetTransformInfo &TTI,
6609 uintptr_t MaxUniqueResults) {
6610 for (const auto &I : SI->cases()) {
6611 ConstantInt *CaseVal = I.getCaseValue();
6612
6613 // Resulting value at phi nodes for this case value.
6614 SwitchCaseResultsTy Results;
6615 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
6616 DL, TTI))
6617 return false;
6618
6619 // Only one value per case is permitted.
6620 if (Results.size() > 1)
6621 return false;
6622
6623 // Add the case->result mapping to UniqueResults.
6624 const size_t NumCasesForResult =
6625 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
6626
6627 // Early out if there are too many cases for this result.
6628 if (NumCasesForResult > MaxSwitchCasesPerResult)
6629 return false;
6630
6631 // Early out if there are too many unique results.
6632 if (UniqueResults.size() > MaxUniqueResults)
6633 return false;
6634
6635 // Check the PHI consistency.
6636 if (!PHI)
6637 PHI = Results[0].first;
6638 else if (PHI != Results[0].first)
6639 return false;
6640 }
6641 // Find the default result value.
6643 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
6644 DL, TTI);
6645 // If the default value is not found abort unless the default destination
6646 // is unreachable.
6647 DefaultResult =
6648 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
6649
6650 return DefaultResult || SI->defaultDestUnreachable();
6651}
6652
6653// Helper function that checks if it is possible to transform a switch with only
6654// two cases (or two cases + default) that produces a result into a select.
6655// TODO: Handle switches with more than 2 cases that map to the same result.
6656// The branch weights correspond to the provided Condition (i.e. if Condition is
6657// modified from the original SwitchInst, the caller must adjust the weights)
6658static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
6659 Constant *DefaultResult, Value *Condition,
6660 IRBuilder<> &Builder, const DataLayout &DL,
6661 ArrayRef<uint32_t> BranchWeights) {
6662 // If we are selecting between only two cases transform into a simple
6663 // select or a two-way select if default is possible.
6664 // Example:
6665 // switch (a) { %0 = icmp eq i32 %a, 10
6666 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
6667 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
6668 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
6669 // }
6670
6671 const bool HasBranchWeights =
6672 !BranchWeights.empty() && !ProfcheckDisableMetadataFixes;
6673
6674 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
6675 ResultVector[1].second.size() == 1) {
6676 ConstantInt *FirstCase = ResultVector[0].second[0];
6677 ConstantInt *SecondCase = ResultVector[1].second[0];
6678 Value *SelectValue = ResultVector[1].first;
6679 if (DefaultResult) {
6680 Value *ValueCompare =
6681 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
6682 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
6683 DefaultResult, "switch.select");
6684 if (auto *SI = dyn_cast<SelectInst>(SelectValue);
6685 SI && HasBranchWeights) {
6686 // We start with 3 probabilities, where the numerator is the
6687 // corresponding BranchWeights[i], and the denominator is the sum over
6688 // BranchWeights. We want the probability and negative probability of
6689 // Condition == SecondCase.
6690 assert(BranchWeights.size() == 3);
6692 *SI, {BranchWeights[2], BranchWeights[0] + BranchWeights[1]},
6693 /*IsExpected=*/false, /*ElideAllZero=*/true);
6694 }
6695 }
6696 Value *ValueCompare =
6697 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
6698 Value *Ret = Builder.CreateSelect(ValueCompare, ResultVector[0].first,
6699 SelectValue, "switch.select");
6700 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6701 // We may have had a DefaultResult. Base the position of the first and
6702 // second's branch weights accordingly. Also the proability that Condition
6703 // != FirstCase needs to take that into account.
6704 assert(BranchWeights.size() >= 2);
6705 size_t FirstCasePos = (Condition != nullptr);
6706 size_t SecondCasePos = FirstCasePos + 1;
6707 uint32_t DefaultCase = (Condition != nullptr) ? BranchWeights[0] : 0;
6709 {BranchWeights[FirstCasePos],
6710 DefaultCase + BranchWeights[SecondCasePos]},
6711 /*IsExpected=*/false, /*ElideAllZero=*/true);
6712 }
6713 return Ret;
6714 }
6715
6716 // Handle the degenerate case where two cases have the same result value.
6717 if (ResultVector.size() == 1 && DefaultResult) {
6718 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
6719 unsigned CaseCount = CaseValues.size();
6720 // n bits group cases map to the same result:
6721 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
6722 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
6723 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
6724 if (isPowerOf2_32(CaseCount)) {
6725 ConstantInt *MinCaseVal = CaseValues[0];
6726 // If there are bits that are set exclusively by CaseValues, we
6727 // can transform the switch into a select if the conjunction of
6728 // all the values uniquely identify CaseValues.
6729 APInt AndMask = APInt::getAllOnes(MinCaseVal->getBitWidth());
6730
6731 // Find the minimum value and compute the and of all the case values.
6732 for (auto *Case : CaseValues) {
6733 if (Case->getValue().slt(MinCaseVal->getValue()))
6734 MinCaseVal = Case;
6735 AndMask &= Case->getValue();
6736 }
6737 KnownBits Known = computeKnownBits(Condition, DL);
6738
6739 if (!AndMask.isZero() && Known.getMaxValue().uge(AndMask)) {
6740 // Compute the number of bits that are free to vary.
6741 unsigned FreeBits = Known.countMaxActiveBits() - AndMask.popcount();
6742
6743 // Check if the number of values covered by the mask is equal
6744 // to the number of cases.
6745 if (FreeBits == Log2_32(CaseCount)) {
6746 Value *And = Builder.CreateAnd(Condition, AndMask);
6747 Value *Cmp = Builder.CreateICmpEQ(
6748 And, Constant::getIntegerValue(And->getType(), AndMask));
6749 Value *Ret =
6750 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6751 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6752 // We know there's a Default case. We base the resulting branch
6753 // weights off its probability.
6754 assert(BranchWeights.size() >= 2);
6756 *SI,
6757 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6758 /*IsExpected=*/false, /*ElideAllZero=*/true);
6759 }
6760 return Ret;
6761 }
6762 }
6763
6764 // Mark the bits case number touched.
6765 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
6766 for (auto *Case : CaseValues)
6767 BitMask |= (Case->getValue() - MinCaseVal->getValue());
6768
6769 // Check if cases with the same result can cover all number
6770 // in touched bits.
6771 if (BitMask.popcount() == Log2_32(CaseCount)) {
6772 if (!MinCaseVal->isNullValue())
6773 Condition = Builder.CreateSub(Condition, MinCaseVal);
6774 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
6775 Value *Cmp = Builder.CreateICmpEQ(
6776 And, Constant::getNullValue(And->getType()), "switch.selectcmp");
6777 Value *Ret =
6778 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6779 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6780 assert(BranchWeights.size() >= 2);
6782 *SI,
6783 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6784 /*IsExpected=*/false, /*ElideAllZero=*/true);
6785 }
6786 return Ret;
6787 }
6788 }
6789
6790 // Handle the degenerate case where two cases have the same value.
6791 if (CaseValues.size() == 2) {
6792 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
6793 "switch.selectcmp.case1");
6794 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
6795 "switch.selectcmp.case2");
6796 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
6797 Value *Ret =
6798 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6799 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6800 assert(BranchWeights.size() >= 2);
6802 *SI, {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6803 /*IsExpected=*/false, /*ElideAllZero=*/true);
6804 }
6805 return Ret;
6806 }
6807 }
6808
6809 return nullptr;
6810}
6811
6812// Helper function to cleanup a switch instruction that has been converted into
6813// a select, fixing up PHI nodes and basic blocks.
6815 Value *SelectValue,
6816 IRBuilder<> &Builder,
6817 DomTreeUpdater *DTU) {
6818 std::vector<DominatorTree::UpdateType> Updates;
6819
6820 BasicBlock *SelectBB = SI->getParent();
6821 BasicBlock *DestBB = PHI->getParent();
6822
6823 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
6824 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
6825 Builder.CreateBr(DestBB);
6826
6827 // Remove the switch.
6828
6829 PHI->removeIncomingValueIf(
6830 [&](unsigned Idx) { return PHI->getIncomingBlock(Idx) == SelectBB; });
6831 PHI->addIncoming(SelectValue, SelectBB);
6832
6833 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
6834 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6835 BasicBlock *Succ = SI->getSuccessor(i);
6836
6837 if (Succ == DestBB)
6838 continue;
6839 Succ->removePredecessor(SelectBB);
6840 if (DTU && RemovedSuccessors.insert(Succ).second)
6841 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
6842 }
6843 SI->eraseFromParent();
6844 if (DTU)
6845 DTU->applyUpdates(Updates);
6846}
6847
6848/// If a switch is only used to initialize one or more phi nodes in a common
6849/// successor block with only two different constant values, try to replace the
6850/// switch with a select. Returns true if the fold was made.
6852 DomTreeUpdater *DTU, const DataLayout &DL,
6853 const TargetTransformInfo &TTI) {
6854 Value *const Cond = SI->getCondition();
6855 PHINode *PHI = nullptr;
6856 BasicBlock *CommonDest = nullptr;
6857 Constant *DefaultResult;
6858 SwitchCaseResultVectorTy UniqueResults;
6859 // Collect all the cases that will deliver the same value from the switch.
6860 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
6861 DL, TTI, /*MaxUniqueResults*/ 2))
6862 return false;
6863
6864 assert(PHI != nullptr && "PHI for value select not found");
6865 Builder.SetInsertPoint(SI);
6866 SmallVector<uint32_t, 4> BranchWeights;
6868 [[maybe_unused]] auto HasWeights =
6870 assert(!HasWeights == (BranchWeights.empty()));
6871 }
6872 assert(BranchWeights.empty() ||
6873 (BranchWeights.size() >=
6874 UniqueResults.size() + (DefaultResult != nullptr)));
6875
6876 Value *SelectValue = foldSwitchToSelect(UniqueResults, DefaultResult, Cond,
6877 Builder, DL, BranchWeights);
6878 if (!SelectValue)
6879 return false;
6880
6881 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
6882 return true;
6883}
6884
6885namespace {
6886
6887/// This class finds alternatives for switches to ultimately
6888/// replace the switch.
6889class SwitchReplacement {
6890public:
6891 /// Create a helper for optimizations to use as a switch replacement.
6892 /// Find a better representation for the content of Values,
6893 /// using DefaultValue to fill any holes in the table.
6894 SwitchReplacement(
6895 Module &M, uint64_t TableSize, ConstantInt *Offset,
6896 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
6897 Constant *DefaultValue, const DataLayout &DL,
6898 const TargetTransformInfo &TTI, const StringRef &FuncName);
6899
6900 /// Build instructions with Builder to retrieve values using Index
6901 /// and replace the switch.
6902 Value *replaceSwitch(Value *Index, IRBuilder<> &Builder, const DataLayout &DL,
6903 Function *Func);
6904
6905 /// Return true if a table with TableSize elements of
6906 /// type ElementType would fit in a target-legal register.
6907 static bool wouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
6908 Type *ElementType);
6909
6910 /// Return the default value of the switch.
6911 Constant *getDefaultValue();
6912
6913 /// Return true if the replacement is a lookup table.
6914 bool isLookupTable();
6915
6916 /// Return true if the replacement is a bit map.
6917 bool isBitMap();
6918
6919private:
6920 // Depending on the switch, there are different alternatives.
6921 enum {
6922 // For switches where each case contains the same value, we just have to
6923 // store that single value and return it for each lookup.
6924 SingleValueKind,
6925
6926 // For switches where there is a linear relationship between table index
6927 // and values. We calculate the result with a simple multiplication
6928 // and addition instead of a table lookup.
6929 LinearMapKind,
6930
6931 // For small tables with integer elements, we can pack them into a bitmap
6932 // that fits into a target-legal register. Values are retrieved by
6933 // shift and mask operations.
6934 BitMapKind,
6935
6936 // The table is stored as an array of values. Values are retrieved by load
6937 // instructions from the table.
6938 LookupTableKind
6939 } Kind;
6940
6941 // The default value of the switch.
6942 Constant *DefaultValue;
6943
6944 // The type of the output values.
6945 Type *ValueType;
6946
6947 // For SingleValueKind, this is the single value.
6948 Constant *SingleValue = nullptr;
6949
6950 // For BitMapKind, this is the bitmap.
6951 ConstantInt *BitMap = nullptr;
6952 IntegerType *BitMapElementTy = nullptr;
6953
6954 // For LinearMapKind, these are the constants used to derive the value.
6955 ConstantInt *LinearOffset = nullptr;
6956 ConstantInt *LinearMultiplier = nullptr;
6957 bool LinearMapValWrapped = false;
6958
6959 // For LookupTableKind, this is the table.
6960 Constant *Initializer = nullptr;
6961};
6962
6963} // end anonymous namespace
6964
6965SwitchReplacement::SwitchReplacement(
6966 Module &M, uint64_t TableSize, ConstantInt *Offset,
6967 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
6968 Constant *DefaultValue, const DataLayout &DL,
6969 const TargetTransformInfo &TTI, const StringRef &FuncName)
6970 : DefaultValue(DefaultValue) {
6971 assert(Values.size() && "Can't build lookup table without values!");
6972 assert(TableSize >= Values.size() && "Can't fit values in table!");
6973
6974 // If all values in the table are equal, this is that value.
6975 SingleValue = Values.begin()->second;
6976
6977 ValueType = Values.begin()->second->getType();
6978
6979 // Build up the table contents.
6980 SmallVector<Constant *, 64> TableContents(TableSize);
6981 for (const auto &[CaseVal, CaseRes] : Values) {
6982 assert(CaseRes->getType() == ValueType);
6983
6984 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
6985 TableContents[Idx] = CaseRes;
6986
6987 if (SingleValue && !isa<PoisonValue>(CaseRes) && CaseRes != SingleValue)
6988 SingleValue = isa<PoisonValue>(SingleValue) ? CaseRes : nullptr;
6989 }
6990
6991 // Fill in any holes in the table with the default result.
6992 if (Values.size() < TableSize) {
6993 assert(DefaultValue &&
6994 "Need a default value to fill the lookup table holes.");
6995 assert(DefaultValue->getType() == ValueType);
6996 for (uint64_t I = 0; I < TableSize; ++I) {
6997 if (!TableContents[I])
6998 TableContents[I] = DefaultValue;
6999 }
7000
7001 // If the default value is poison, all the holes are poison.
7002 bool DefaultValueIsPoison = isa<PoisonValue>(DefaultValue);
7003
7004 if (DefaultValue != SingleValue && !DefaultValueIsPoison)
7005 SingleValue = nullptr;
7006 }
7007
7008 // If each element in the table contains the same value, we only need to store
7009 // that single value.
7010 if (SingleValue) {
7011 Kind = SingleValueKind;
7012 return;
7013 }
7014
7015 // Check if we can derive the value with a linear transformation from the
7016 // table index.
7018 bool LinearMappingPossible = true;
7019 APInt PrevVal;
7020 APInt DistToPrev;
7021 // When linear map is monotonic and signed overflow doesn't happen on
7022 // maximum index, we can attach nsw on Add and Mul.
7023 bool NonMonotonic = false;
7024 assert(TableSize >= 2 && "Should be a SingleValue table.");
7025 // Check if there is the same distance between two consecutive values.
7026 for (uint64_t I = 0; I < TableSize; ++I) {
7027 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
7028
7029 if (!ConstVal && isa<PoisonValue>(TableContents[I])) {
7030 // This is an poison, so it's (probably) a lookup table hole.
7031 // To prevent any regressions from before we switched to using poison as
7032 // the default value, holes will fall back to using the first value.
7033 // This can be removed once we add proper handling for poisons in lookup
7034 // tables.
7035 ConstVal = dyn_cast<ConstantInt>(Values[0].second);
7036 }
7037
7038 if (!ConstVal) {
7039 // This is an undef. We could deal with it, but undefs in lookup tables
7040 // are very seldom. It's probably not worth the additional complexity.
7041 LinearMappingPossible = false;
7042 break;
7043 }
7044 const APInt &Val = ConstVal->getValue();
7045 if (I != 0) {
7046 APInt Dist = Val - PrevVal;
7047 if (I == 1) {
7048 DistToPrev = Dist;
7049 } else if (Dist != DistToPrev) {
7050 LinearMappingPossible = false;
7051 break;
7052 }
7053 NonMonotonic |=
7054 Dist.isStrictlyPositive() ? Val.sle(PrevVal) : Val.sgt(PrevVal);
7055 }
7056 PrevVal = Val;
7057 }
7058 if (LinearMappingPossible) {
7059 LinearOffset = cast<ConstantInt>(TableContents[0]);
7060 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
7061 APInt M = LinearMultiplier->getValue();
7062 bool MayWrap = true;
7063 if (isIntN(M.getBitWidth(), TableSize - 1))
7064 (void)M.smul_ov(APInt(M.getBitWidth(), TableSize - 1), MayWrap);
7065 LinearMapValWrapped = NonMonotonic || MayWrap;
7066 Kind = LinearMapKind;
7067 return;
7068 }
7069 }
7070
7071 // If the type is integer and the table fits in a register, build a bitmap.
7072 if (wouldFitInRegister(DL, TableSize, ValueType)) {
7074 APInt TableInt(TableSize * IT->getBitWidth(), 0);
7075 for (uint64_t I = TableSize; I > 0; --I) {
7076 TableInt <<= IT->getBitWidth();
7077 // Insert values into the bitmap. Undef values are set to zero.
7078 if (!isa<UndefValue>(TableContents[I - 1])) {
7079 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
7080 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
7081 }
7082 }
7083 BitMap = ConstantInt::get(M.getContext(), TableInt);
7084 BitMapElementTy = IT;
7085 Kind = BitMapKind;
7086 return;
7087 }
7088
7089 if (auto *IT = dyn_cast<IntegerType>(ValueType)) {
7090 ConstantRange Range(IT->getBitWidth(), false);
7091 for (Constant *Value : TableContents)
7092 if (!isa<UndefValue>(Value))
7093 Range = Range.unionWith(cast<ConstantInt>(Value)->getValue());
7094 // TODO: handle sign extension as well?
7095 unsigned NeededBitWidth =
7096 std::max(TTI.getMinimumLookupTableEntryBitWidth(),
7097 unsigned(PowerOf2Ceil(Range.getActiveBits())));
7098 if (NeededBitWidth < IT->getBitWidth()) {
7099 IntegerType *DstTy = IntegerType::get(IT->getContext(), NeededBitWidth);
7100 for (Constant *&Value : TableContents)
7101 Value = ConstantFoldCastInstruction(Instruction::Trunc, Value, DstTy);
7102 }
7103 }
7104
7105 // Store the table in an array.
7106 auto *TableTy = ArrayType::get(TableContents[0]->getType(), TableSize);
7107 Initializer = ConstantArray::get(TableTy, TableContents);
7108
7109 Kind = LookupTableKind;
7110}
7111
7112Value *SwitchReplacement::replaceSwitch(Value *Index, IRBuilder<> &Builder,
7113 const DataLayout &DL, Function *Func) {
7114 switch (Kind) {
7115 case SingleValueKind:
7116 return SingleValue;
7117 case LinearMapKind: {
7118 ++NumLinearMaps;
7119 // Derive the result value from the input value.
7120 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
7121 false, "switch.idx.cast");
7122 if (!LinearMultiplier->isOne())
7123 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult",
7124 /*HasNUW = */ false,
7125 /*HasNSW = */ !LinearMapValWrapped);
7126
7127 if (!LinearOffset->isZero())
7128 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset",
7129 /*HasNUW = */ false,
7130 /*HasNSW = */ !LinearMapValWrapped);
7131 return Result;
7132 }
7133 case BitMapKind: {
7134 ++NumBitMaps;
7135 // Type of the bitmap (e.g. i59).
7136 IntegerType *MapTy = BitMap->getIntegerType();
7137
7138 // Cast Index to the same type as the bitmap.
7139 // Note: The Index is <= the number of elements in the table, so
7140 // truncating it to the width of the bitmask is safe.
7141 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
7142
7143 // Multiply the shift amount by the element width. NUW/NSW can always be
7144 // set, because wouldFitInRegister guarantees Index * ShiftAmt is in
7145 // BitMap's bit width.
7146 ShiftAmt = Builder.CreateMul(
7147 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
7148 "switch.shiftamt",/*HasNUW =*/true,/*HasNSW =*/true);
7149
7150 // Shift down.
7151 Value *DownShifted =
7152 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
7153 // Mask off.
7154 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
7155 }
7156 case LookupTableKind: {
7157 ++NumLookupTables;
7158 auto *Table =
7159 new GlobalVariable(*Func->getParent(), Initializer->getType(),
7160 /*isConstant=*/true, GlobalVariable::PrivateLinkage,
7161 Initializer, "switch.table." + Func->getName());
7162 Table->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7163 // Set the alignment to that of an array items. We will be only loading one
7164 // value out of it.
7165 Table->setAlignment(DL.getPrefTypeAlign(ValueType));
7166 Type *IndexTy = DL.getIndexType(Table->getType());
7167 auto *ArrayTy = cast<ArrayType>(Table->getValueType());
7168
7169 if (Index->getType() != IndexTy) {
7170 unsigned OldBitWidth = Index->getType()->getIntegerBitWidth();
7171 Index = Builder.CreateZExtOrTrunc(Index, IndexTy);
7172 if (auto *Zext = dyn_cast<ZExtInst>(Index))
7173 Zext->setNonNeg(
7174 isUIntN(OldBitWidth - 1, ArrayTy->getNumElements() - 1));
7175 }
7176
7177 Value *GEPIndices[] = {ConstantInt::get(IndexTy, 0), Index};
7178 Value *GEP =
7179 Builder.CreateInBoundsGEP(ArrayTy, Table, GEPIndices, "switch.gep");
7180 Value *Load =
7181 Builder.CreateLoad(ArrayTy->getElementType(), GEP, "switch.load");
7182 if (Load->getType() == ValueType)
7183 return Load;
7184 return Builder.CreateZExt(Load, ValueType, "switch.ext");
7185 }
7186 }
7187 llvm_unreachable("Unknown helper kind!");
7188}
7189
7190bool SwitchReplacement::wouldFitInRegister(const DataLayout &DL,
7191 uint64_t TableSize,
7192 Type *ElementType) {
7193 auto *IT = dyn_cast<IntegerType>(ElementType);
7194 if (!IT)
7195 return false;
7196 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
7197 // are <= 15, we could try to narrow the type.
7198
7199 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
7200 if (TableSize >= UINT_MAX / IT->getBitWidth())
7201 return false;
7202 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
7203}
7204
7206 const DataLayout &DL) {
7207 // Allow any legal type.
7208 if (TTI.isTypeLegal(Ty))
7209 return true;
7210
7211 auto *IT = dyn_cast<IntegerType>(Ty);
7212 if (!IT)
7213 return false;
7214
7215 // Also allow power of 2 integer types that have at least 8 bits and fit in
7216 // a register. These types are common in frontend languages and targets
7217 // usually support loads of these types.
7218 // TODO: We could relax this to any integer that fits in a register and rely
7219 // on ABI alignment and padding in the table to allow the load to be widened.
7220 // Or we could widen the constants and truncate the load.
7221 unsigned BitWidth = IT->getBitWidth();
7222 return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
7223 DL.fitsInLegalInteger(IT->getBitWidth());
7224}
7225
7226Constant *SwitchReplacement::getDefaultValue() { return DefaultValue; }
7227
7228bool SwitchReplacement::isLookupTable() { return Kind == LookupTableKind; }
7229
7230bool SwitchReplacement::isBitMap() { return Kind == BitMapKind; }
7231
7232static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize) {
7233 // 40% is the default density for building a jump table in optsize/minsize
7234 // mode, 10% is the default density for jump tables. See also
7235 // TargetLoweringBase::isSuitableForJumpTable(), which this function was based
7236 // on.
7237 const uint64_t MinDensity = OptSize ? 40 : 10;
7238
7239 if (CaseRange >= UINT64_MAX / 100)
7240 return false; // Avoid multiplication overflows below.
7241
7242 return NumCases * 100 >= CaseRange * MinDensity;
7243}
7244
7245static bool isSwitchDense(ArrayRef<int64_t> Values, bool OptSize) {
7246 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
7247 uint64_t Range = Diff + 1;
7248 if (Range < Diff)
7249 return false; // Overflow.
7250
7251 return isSwitchDense(Values.size(), Range, OptSize);
7252}
7253
7254static std::optional<unsigned>
7256 bool OptSize) {
7257 assert(Values.size() > 1 && "expected multiple switch cases");
7258 if (!llvm::all_of(Values, [Base](int64_t V) { return V >= Base; }))
7259 return std::nullopt;
7260
7261 // First, transform the values by subtracting Base.
7262 SmallVector<int64_t, 4> ReducedValues(Values);
7263 uint64_t ReducedValuesOr = 0;
7264 for (auto &V : ReducedValues) {
7265 uint64_t Reduced = (uint64_t)V - (uint64_t)Base;
7266 ReducedValuesOr |= Reduced;
7267 V = (int64_t)Reduced;
7268 }
7269
7270 // Conceptually, the reduced values are non-negative distances from Base.
7271 // Since the rest of the transform is bitwise only, treat them as unsigned
7272 // bit patterns from here.
7273
7274 // countr_zero(0) returns 64. As Values is guaranteed to have more than
7275 // one element and LLVM disallows duplicate cases, ReducedValuesOr will
7276 // have at least one bit set, so Shift will be less than 64.
7277 unsigned Shift = llvm::countr_zero(ReducedValuesOr);
7278 assert(Shift < 64);
7279 if (Shift > 0)
7280 for (auto &V : ReducedValues)
7281 V = (int64_t)((uint64_t)V >> Shift);
7282
7283 if (!isSwitchDense(ReducedValues, OptSize))
7284 return std::nullopt;
7285
7286 return Shift;
7287}
7288
7289/// Determine whether a lookup table should be built for this switch, based on
7290/// the number of cases, size of the table, and the types of the results.
7291// TODO: We could support larger than legal types by limiting based on the
7292// number of loads required and/or table size. If the constants are small we
7293// could use smaller table entries and extend after the load.
7295 const TargetTransformInfo &TTI,
7296 const DataLayout &DL,
7297 const SmallVector<Type *> &ResultTypes) {
7298 if (SI->getNumCases() > TableSize)
7299 return false; // TableSize overflowed.
7300
7301 bool AllTablesFitInRegister = true;
7302 bool HasIllegalType = false;
7303 for (const auto &Ty : ResultTypes) {
7304 // Saturate this flag to true.
7305 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
7306
7307 // Saturate this flag to false.
7308 AllTablesFitInRegister =
7309 AllTablesFitInRegister &&
7310 SwitchReplacement::wouldFitInRegister(DL, TableSize, Ty);
7311
7312 // If both flags saturate, we're done. NOTE: This *only* works with
7313 // saturating flags, and all flags have to saturate first due to the
7314 // non-deterministic behavior of iterating over a dense map.
7315 if (HasIllegalType && !AllTablesFitInRegister)
7316 break;
7317 }
7318
7319 // If each table would fit in a register, we should build it anyway.
7320 if (AllTablesFitInRegister)
7321 return true;
7322
7323 // Don't build a table that doesn't fit in-register if it has illegal types.
7324 if (HasIllegalType)
7325 return false;
7326
7327 return isSwitchDense(SI->getNumCases(), TableSize,
7328 SI->getFunction()->hasOptSize());
7329}
7330
7332 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
7333 bool HasDefaultResults, const SmallVector<Type *> &ResultTypes,
7334 const DataLayout &DL, const TargetTransformInfo &TTI) {
7335 if (MinCaseVal.isNullValue())
7336 return true;
7337 if (MinCaseVal.isNegative() ||
7338 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
7339 !HasDefaultResults)
7340 return false;
7341 return all_of(ResultTypes, [&](const auto &ResultType) {
7342 return SwitchReplacement::wouldFitInRegister(
7343 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */, ResultType);
7344 });
7345}
7346
7347/// Try to reuse the switch table index compare. Following pattern:
7348/// \code
7349/// if (idx < tablesize)
7350/// r = table[idx]; // table does not contain default_value
7351/// else
7352/// r = default_value;
7353/// if (r != default_value)
7354/// ...
7355/// \endcode
7356/// Is optimized to:
7357/// \code
7358/// cond = idx < tablesize;
7359/// if (cond)
7360/// r = table[idx];
7361/// else
7362/// r = default_value;
7363/// if (cond)
7364/// ...
7365/// \endcode
7366/// Jump threading will then eliminate the second if(cond).
7368 User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
7369 Constant *DefaultValue,
7370 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
7372 if (!CmpInst)
7373 return;
7374
7375 // We require that the compare is in the same block as the phi so that jump
7376 // threading can do its work afterwards.
7377 if (CmpInst->getParent() != PhiBlock)
7378 return;
7379
7381 if (!CmpOp1)
7382 return;
7383
7384 Value *RangeCmp = RangeCheckBranch->getCondition();
7385 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
7386 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
7387
7388 // Check if the compare with the default value is constant true or false.
7389 const DataLayout &DL = PhiBlock->getDataLayout();
7391 CmpInst->getPredicate(), DefaultValue, CmpOp1, DL);
7392 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
7393 return;
7394
7395 // Check if the compare with the case values is distinct from the default
7396 // compare result.
7397 for (auto ValuePair : Values) {
7399 CmpInst->getPredicate(), ValuePair.second, CmpOp1, DL);
7400 if (!CaseConst || CaseConst == DefaultConst ||
7401 (CaseConst != TrueConst && CaseConst != FalseConst))
7402 return;
7403 }
7404
7405 // Check if the branch instruction dominates the phi node. It's a simple
7406 // dominance check, but sufficient for our needs.
7407 // Although this check is invariant in the calling loops, it's better to do it
7408 // at this late stage. Practically we do it at most once for a switch.
7409 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
7410 for (BasicBlock *Pred : predecessors(PhiBlock)) {
7411 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
7412 return;
7413 }
7414
7415 if (DefaultConst == FalseConst) {
7416 // The compare yields the same result. We can replace it.
7417 CmpInst->replaceAllUsesWith(RangeCmp);
7418 ++NumTableCmpReuses;
7419 } else {
7420 // The compare yields the same result, just inverted. We can replace it.
7421 Value *InvertedTableCmp = BinaryOperator::CreateXor(
7422 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
7423 RangeCheckBranch->getIterator());
7424 CmpInst->replaceAllUsesWith(InvertedTableCmp);
7425 ++NumTableCmpReuses;
7426 }
7427}
7428
7429/// If the switch is only used to initialize one or more phi nodes in a common
7430/// successor block with different constant values, replace the switch with
7431/// lookup tables.
7433 DomTreeUpdater *DTU, const DataLayout &DL,
7434 const TargetTransformInfo &TTI,
7435 bool ConvertSwitchToLookupTable) {
7436 assert(SI->getNumCases() > 1 && "Degenerate switch?");
7437
7438 BasicBlock *BB = SI->getParent();
7439 Function *Fn = BB->getParent();
7440
7441 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
7442 // split off a dense part and build a lookup table for that.
7443
7444 // FIXME: This creates arrays of GEPs to constant strings, which means each
7445 // GEP needs a runtime relocation in PIC code. We should just build one big
7446 // string and lookup indices into that.
7447
7448 // Ignore switches with less than three cases. Lookup tables will not make
7449 // them faster, so we don't analyze them.
7450 if (SI->getNumCases() < 3)
7451 return false;
7452
7453 // Figure out the corresponding result for each case value and phi node in the
7454 // common destination, as well as the min and max case values.
7455 assert(!SI->cases().empty());
7456 SwitchInst::CaseIt CI = SI->case_begin();
7457 ConstantInt *MinCaseVal = CI->getCaseValue();
7458 ConstantInt *MaxCaseVal = CI->getCaseValue();
7459
7460 BasicBlock *CommonDest = nullptr;
7461
7462 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
7464
7466 SmallVector<Type *> ResultTypes;
7468
7469 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
7470 ConstantInt *CaseVal = CI->getCaseValue();
7471 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
7472 MinCaseVal = CaseVal;
7473 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
7474 MaxCaseVal = CaseVal;
7475
7476 // Resulting value at phi nodes for this case value.
7478 ResultsTy Results;
7479 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
7480 Results, DL, TTI))
7481 return false;
7482
7483 // Append the result and result types from this case to the list for each
7484 // phi.
7485 for (const auto &I : Results) {
7486 PHINode *PHI = I.first;
7487 Constant *Value = I.second;
7488 auto [It, Inserted] = ResultLists.try_emplace(PHI);
7489 if (Inserted)
7490 PHIs.push_back(PHI);
7491 It->second.push_back(std::make_pair(CaseVal, Value));
7492 ResultTypes.push_back(PHI->getType());
7493 }
7494 }
7495
7496 // If the table has holes, we need a constant result for the default case
7497 // or a bitmask that fits in a register.
7498 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
7499 bool HasDefaultResults =
7500 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
7501 DefaultResultsList, DL, TTI);
7502 for (const auto &I : DefaultResultsList) {
7503 PHINode *PHI = I.first;
7504 Constant *Result = I.second;
7505 DefaultResults[PHI] = Result;
7506 }
7507
7508 bool UseSwitchConditionAsTableIndex = shouldUseSwitchConditionAsTableIndex(
7509 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
7510 uint64_t TableSize;
7511 ConstantInt *TableIndexOffset;
7512 if (UseSwitchConditionAsTableIndex) {
7513 TableSize = MaxCaseVal->getLimitedValue() + 1;
7514 TableIndexOffset = ConstantInt::get(MaxCaseVal->getIntegerType(), 0);
7515 } else {
7516 TableSize =
7517 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
7518
7519 TableIndexOffset = MinCaseVal;
7520 }
7521
7522 // If the default destination is unreachable, or if the lookup table covers
7523 // all values of the conditional variable, branch directly to the lookup table
7524 // BB. Otherwise, check that the condition is within the case range.
7525 uint64_t NumResults = ResultLists[PHIs[0]].size();
7526 bool DefaultIsReachable = !SI->defaultDestUnreachable();
7527
7528 bool TableHasHoles = (NumResults < TableSize);
7529
7530 // If the table has holes but the default destination doesn't produce any
7531 // constant results, the lookup table entries corresponding to the holes will
7532 // contain poison.
7533 bool AllHolesArePoison = TableHasHoles && !HasDefaultResults;
7534
7535 // If the default destination doesn't produce a constant result but is still
7536 // reachable, and the lookup table has holes, we need to use a mask to
7537 // determine if the current index should load from the lookup table or jump
7538 // to the default case.
7539 // The mask is unnecessary if the table has holes but the default destination
7540 // is unreachable, as in that case the holes must also be unreachable.
7541 bool NeedMask = AllHolesArePoison && DefaultIsReachable;
7542 if (NeedMask) {
7543 // As an extra penalty for the validity test we require more cases.
7544 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
7545 return false;
7546 if (!DL.fitsInLegalInteger(TableSize))
7547 return false;
7548 }
7549
7550 if (!shouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
7551 return false;
7552
7553 // Compute the table index value.
7554 Value *TableIndex;
7555 if (UseSwitchConditionAsTableIndex) {
7556 TableIndex = SI->getCondition();
7557 if (HasDefaultResults) {
7558 // Grow the table to cover all possible index values to avoid the range
7559 // check. It will use the default result to fill in the table hole later,
7560 // so make sure it exist.
7561 ConstantRange CR = computeConstantRange(TableIndex, /*ForSigned=*/false,
7562 SimplifyQuery(DL));
7563 // Grow the table shouldn't have any size impact by checking
7564 // wouldFitInRegister.
7565 // TODO: Consider growing the table also when it doesn't fit in a register
7566 // if no optsize is specified.
7567 const uint64_t UpperBound = CR.getUpper().getLimitedValue();
7568 if (!CR.isUpperWrapped() &&
7569 all_of(ResultTypes, [&](const auto &ResultType) {
7570 return SwitchReplacement::wouldFitInRegister(DL, UpperBound,
7571 ResultType);
7572 })) {
7573 // There may be some case index larger than the UpperBound (unreachable
7574 // case), so make sure the table size does not get smaller.
7575 TableSize = std::max(UpperBound, TableSize);
7576 // The default branch is unreachable after we enlarge the lookup table.
7577 // Adjust DefaultIsReachable to reuse code path.
7578 DefaultIsReachable = false;
7579 }
7580 }
7581 }
7582
7583 // Keep track of the switch replacement for each phi
7585 for (PHINode *PHI : PHIs) {
7586 const auto &ResultList = ResultLists[PHI];
7587
7588 Type *ResultType = ResultList.begin()->second->getType();
7589 // Use any value to fill the lookup table holes.
7590 Constant *DefaultVal =
7591 AllHolesArePoison ? PoisonValue::get(ResultType) : DefaultResults[PHI];
7592 StringRef FuncName = Fn->getName();
7593 SwitchReplacement Replacement(*Fn->getParent(), TableSize, TableIndexOffset,
7594 ResultList, DefaultVal, DL, TTI, FuncName);
7595 PhiToReplacementMap.insert({PHI, Replacement});
7596 }
7597
7598 bool AnyLookupTables = any_of(
7599 PhiToReplacementMap, [](auto &KV) { return KV.second.isLookupTable(); });
7600 bool AnyBitMaps = any_of(PhiToReplacementMap,
7601 [](auto &KV) { return KV.second.isBitMap(); });
7602
7603 // A few conditions prevent the generation of lookup tables:
7604 // 1. The target does not support lookup tables.
7605 // 2. The "no-jump-tables" function attribute is set.
7606 // However, these objections do not apply to other switch replacements, like
7607 // the bitmap, so we only stop here if any of these conditions are met and we
7608 // want to create a LUT. Otherwise, continue with the switch replacement.
7609 if (AnyLookupTables &&
7610 (!TTI.shouldBuildLookupTables() ||
7611 Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
7612 return false;
7613
7614 // In the early optimization pipeline, disable formation of lookup tables,
7615 // bit maps and mask checks, as they may inhibit further optimization.
7616 if (!ConvertSwitchToLookupTable &&
7617 (AnyLookupTables || AnyBitMaps || NeedMask))
7618 return false;
7619
7620 Builder.SetInsertPoint(SI);
7621 // TableIndex is the switch condition - TableIndexOffset if we don't
7622 // use the condition directly
7623 if (!UseSwitchConditionAsTableIndex) {
7624 // If the default is unreachable, all case values are s>= MinCaseVal. Then
7625 // we can try to attach nsw.
7626 bool MayWrap = true;
7627 if (!DefaultIsReachable) {
7628 APInt Res =
7629 MaxCaseVal->getValue().ssub_ov(MinCaseVal->getValue(), MayWrap);
7630 (void)Res;
7631 }
7632 TableIndex = Builder.CreateSub(SI->getCondition(), TableIndexOffset,
7633 "switch.tableidx", /*HasNUW =*/false,
7634 /*HasNSW =*/!MayWrap);
7635 }
7636
7637 std::vector<DominatorTree::UpdateType> Updates;
7638
7639 // Compute the maximum table size representable by the integer type we are
7640 // switching upon.
7641 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
7642 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
7643 assert(MaxTableSize >= TableSize &&
7644 "It is impossible for a switch to have more entries than the max "
7645 "representable value of its input integer type's size.");
7646
7647 // Create the BB that does the lookups.
7648 Module &Mod = *CommonDest->getParent()->getParent();
7649 BasicBlock *LookupBB = BasicBlock::Create(
7650 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
7651
7652 CondBrInst *RangeCheckBranch = nullptr;
7653 CondBrInst *CondBranch = nullptr;
7654
7655 Builder.SetInsertPoint(SI);
7656 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
7657 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7658 Builder.CreateBr(LookupBB);
7659 if (DTU)
7660 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7661 // Note: We call removeProdecessor later since we need to be able to get the
7662 // PHI value for the default case in case we're using a bit mask.
7663 } else {
7664 Value *Cmp = Builder.CreateICmpULT(
7665 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
7666 RangeCheckBranch =
7667 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
7668 CondBranch = RangeCheckBranch;
7669 if (DTU)
7670 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7671 }
7672
7673 // Populate the BB that does the lookups.
7674 Builder.SetInsertPoint(LookupBB);
7675
7676 if (NeedMask) {
7677 // Before doing the lookup, we do the hole check. The LookupBB is therefore
7678 // re-purposed to do the hole check, and we create a new LookupBB.
7679 BasicBlock *MaskBB = LookupBB;
7680 MaskBB->setName("switch.hole_check");
7681 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
7682 CommonDest->getParent(), CommonDest);
7683
7684 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
7685 // unnecessary illegal types.
7686 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
7687 APInt MaskInt(TableSizePowOf2, 0);
7688 APInt One(TableSizePowOf2, 1);
7689 // Build bitmask; fill in a 1 bit for every case.
7690 const ResultListTy &ResultList = ResultLists[PHIs[0]];
7691 for (const auto &Result : ResultList) {
7692 uint64_t Idx = (Result.first->getValue() - TableIndexOffset->getValue())
7693 .getLimitedValue();
7694 MaskInt |= One << Idx;
7695 }
7696 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
7697
7698 // Get the TableIndex'th bit of the bitmask.
7699 // If this bit is 0 (meaning hole) jump to the default destination,
7700 // else continue with table lookup.
7701 IntegerType *MapTy = TableMask->getIntegerType();
7702 Value *MaskIndex =
7703 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
7704 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
7705 Value *LoBit = Builder.CreateTrunc(
7706 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
7707 CondBranch = Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
7708 if (DTU) {
7709 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
7710 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
7711 }
7712 Builder.SetInsertPoint(LookupBB);
7713 addPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
7714 }
7715
7716 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7717 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
7718 // do not delete PHINodes here.
7719 SI->getDefaultDest()->removePredecessor(BB,
7720 /*KeepOneInputPHIs=*/true);
7721 if (DTU)
7722 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
7723 }
7724
7725 for (PHINode *PHI : PHIs) {
7726 const ResultListTy &ResultList = ResultLists[PHI];
7727 auto Replacement = PhiToReplacementMap.at(PHI);
7728 auto *Result = Replacement.replaceSwitch(TableIndex, Builder, DL, Fn);
7729 // Do a small peephole optimization: re-use the switch table compare if
7730 // possible.
7731 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
7732 BasicBlock *PhiBlock = PHI->getParent();
7733 // Search for compare instructions which use the phi.
7734 for (auto *User : PHI->users()) {
7735 reuseTableCompare(User, PhiBlock, RangeCheckBranch,
7736 Replacement.getDefaultValue(), ResultList);
7737 }
7738 }
7739
7740 PHI->addIncoming(Result, LookupBB);
7741 }
7742
7743 Builder.CreateBr(CommonDest);
7744 if (DTU)
7745 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
7746
7747 SmallVector<uint32_t> BranchWeights;
7748 const bool HasBranchWeights = CondBranch && !ProfcheckDisableMetadataFixes &&
7749 extractBranchWeights(*SI, BranchWeights);
7750 uint64_t ToLookupWeight = 0;
7751 uint64_t ToDefaultWeight = 0;
7752
7753 // Remove the switch.
7754 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
7755 for (unsigned I = 0, E = SI->getNumSuccessors(); I < E; ++I) {
7756 BasicBlock *Succ = SI->getSuccessor(I);
7757
7758 if (Succ == SI->getDefaultDest()) {
7759 if (HasBranchWeights)
7760 ToDefaultWeight += BranchWeights[I];
7761 continue;
7762 }
7763 Succ->removePredecessor(BB);
7764 if (DTU && RemovedSuccessors.insert(Succ).second)
7765 Updates.push_back({DominatorTree::Delete, BB, Succ});
7766 if (HasBranchWeights)
7767 ToLookupWeight += BranchWeights[I];
7768 }
7769 SI->eraseFromParent();
7770 if (HasBranchWeights)
7771 setFittedBranchWeights(*CondBranch, {ToLookupWeight, ToDefaultWeight},
7772 /*IsExpected=*/false);
7773 if (DTU)
7774 DTU->applyUpdates(Updates);
7775
7776 if (NeedMask)
7777 ++NumLookupTablesHoles;
7778 return true;
7779}
7780
7781/// Try to transform a switch that has "holes" in it to a contiguous sequence
7782/// of cases.
7783///
7784/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
7785/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
7786///
7787/// This converts a sparse switch into a dense switch which allows better
7788/// lowering and could also allow transforming into a lookup table.
7790 const DataLayout &DL,
7791 const TargetTransformInfo &TTI) {
7792 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
7793 if (CondTy->getIntegerBitWidth() > 64 ||
7794 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
7795 return false;
7796 // Only bother with this optimization if there are more than 3 switch cases;
7797 // SDAG will only bother creating jump tables for 4 or more cases.
7798 if (SI->getNumCases() < 4)
7799 return false;
7800
7801 // This transform is agnostic to the signedness of the input or case values. We
7802 // can treat the case values as signed or unsigned. We can optimize more common
7803 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
7804 // as signed.
7806 for (const auto &C : SI->cases())
7807 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
7809
7810 // If the switch is already dense, there's nothing useful to do here.
7811 bool OptSize = SI->getFunction()->hasOptSize();
7812 if (isSwitchDense(Values, OptSize))
7813 return false;
7814
7815 // Find a Base and corresponding Shift that results in a dense switch range.
7816 // Values[0] is the local minimum.
7817 int64_t Base = Values[0];
7818 std::optional<unsigned> Shift;
7819 // Prefer Base=0 when shifting out common low zero bits still produces a dense
7820 // range, as this avoids an unnecessary `(condition - local_min)` expression.
7821 // However, avoiding the subtract can leave a wider reduced range than using
7822 // the local minimum, so require Base=0 to satisfy the stricter optsize
7823 // density threshold before falling back to the normal density policy for
7824 // local-min.
7825 if ((Shift = getDenseSwitchRangeReductionShift(Values, /*Base=*/0,
7826 /*OptSize=*/true)))
7827 Base = 0;
7828 else if (Base != 0)
7830
7831 if (!Shift)
7832 return false;
7833
7834 // The obvious transform is to shift the switch condition right and emit a
7835 // check that the condition actually cleanly divided by GCD, i.e.
7836 // C & (1 << Shift - 1) == 0
7837 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
7838 //
7839 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
7840 // shift and puts the shifted-off bits in the uppermost bits. If any of these
7841 // are nonzero then the switch condition will be very large and will hit the
7842 // default case.
7843 //
7844 // This transform can be done speculatively because it is so cheap - it
7845 // results in a single rotate operation being inserted.
7846
7847 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
7848 Builder.SetInsertPoint(SI);
7849 Value *Sub = SI->getCondition();
7850 if (Base != 0)
7851 Sub = Builder.CreateSub(Sub, ConstantInt::getSigned(Ty, Base));
7852 Value *Rot = Builder.CreateIntrinsic(
7853 Ty, Intrinsic::fshl,
7854 {Sub, Sub, ConstantInt::get(Ty, Ty->getBitWidth() - *Shift)});
7855 SI->replaceUsesOfWith(SI->getCondition(), Rot);
7856
7857 for (auto Case : SI->cases()) {
7858 auto *Orig = Case.getCaseValue();
7859 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base, true);
7860 Case.setValue(cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(*Shift))));
7861 }
7862 return true;
7863}
7864
7865/// Tries to transform the switch when the condition is umin with a constant.
7866/// In that case, the default branch can be replaced by the constant's branch.
7867/// This method also removes dead cases when the simplification cannot replace
7868/// the default branch.
7869///
7870/// For example:
7871/// switch(umin(a, 3)) {
7872/// case 0:
7873/// case 1:
7874/// case 2:
7875/// case 3:
7876/// case 4:
7877/// // ...
7878/// default:
7879/// unreachable
7880/// }
7881///
7882/// Transforms into:
7883///
7884/// switch(a) {
7885/// case 0:
7886/// case 1:
7887/// case 2:
7888/// default:
7889/// // This is case 3
7890/// }
7892 Value *A;
7894
7895 if (!match(SI->getCondition(), m_UMin(m_Value(A), m_ConstantInt(Constant))))
7896 return false;
7897
7900 BasicBlock *BB = SIW->getParent();
7901
7902 // Dead cases are removed even when the simplification fails.
7903 // A case is dead when its value is higher than the Constant.
7904 for (auto I = SI->case_begin(), E = SI->case_end(); I != E;) {
7905 if (!I->getCaseValue()->getValue().ugt(Constant->getValue())) {
7906 ++I;
7907 continue;
7908 }
7909 BasicBlock *DeadCaseBB = I->getCaseSuccessor();
7910 DeadCaseBB->removePredecessor(BB);
7911 I = SIW.removeCase(I);
7912 E = SIW->case_end();
7913 if (!is_contained(successors(BB), DeadCaseBB))
7914 Updates.push_back({DominatorTree::Delete, BB, DeadCaseBB});
7915 }
7916
7917 auto Case = SI->findCaseValue(Constant);
7918 // If the case value is not found, `findCaseValue` returns the default case.
7919 // In this scenario, since there is no explicit `case 3:`, the simplification
7920 // fails. The simplification also fails when the switch’s default destination
7921 // is reachable.
7922 if (!SI->defaultDestUnreachable() || Case == SI->case_default()) {
7923 if (DTU)
7924 DTU->applyUpdates(Updates);
7925 return !Updates.empty();
7926 }
7927
7928 BasicBlock *Unreachable = SI->getDefaultDest();
7929 SIW.replaceDefaultDest(Case);
7930 SIW.removeCase(Case);
7931 SIW->setCondition(A);
7932
7933 Updates.push_back({DominatorTree::Delete, BB, Unreachable});
7934
7935 if (DTU)
7936 DTU->applyUpdates(Updates);
7937
7938 return true;
7939}
7940
7942 const DataLayout &DL,
7943 AssumptionCache *AC) {
7944 assert(SI);
7945 if (SI->defaultDestUnreachable())
7946 return false;
7947
7948 // If it can be proved that the switch condition takes some concrete value
7949 // in the default block, we can make some nice simplifications to the
7950 // switch.
7951 BasicBlock *Default = SI->getDefaultDest();
7952 const Instruction *CxtI = &*Default->getFirstNonPHIIt();
7954 SI->getCondition(),
7955 SimplifyQuery(DL, /*DT=*/nullptr, AC, CxtI).allowEphemerals(true));
7956 if (!Known.isConstant())
7957 return false;
7958
7959 // At this point, we know that only one value can be mapped to the
7960 // default block. So, if a case doesn't exist for it already, we
7961 // can create one pointing to the default block.
7962 ConstantInt *CaseVal =
7963 ConstantInt::get(SI->getContext(), Known.getConstant());
7964 const llvm::SwitchInst::CaseIt CaseIt = SI->findCaseValue(CaseVal);
7965 if (CaseIt == SI->case_default()) {
7967 SIW.addCase(CaseVal, Default, SIW.getSuccessorWeight(0));
7968 SIW.setSuccessorWeight(0, 0);
7969 }
7970 // If there is a pre-existing case for the constant, the default branch
7971 // will be removed rather than being moved. Thus, we are removing an edge
7972 // in the CFG, and need to update any PHIs in the default block.
7973 createUnreachableSwitchDefault(SI, DTU, /*RemoveOrigDefaultBlock=*/CaseIt !=
7974 SI->case_default());
7975
7976 assert(SI->getNumCases() > 0 && "Switch should have at least one case");
7977 assert(SI->findCaseValue(CaseVal) != SI->case_default() &&
7978 "Proven value should have a dedicated case");
7979 assert(SI->defaultDestUnreachable());
7980 return true;
7981}
7982
7983/// Tries to transform switch of powers of two to reduce switch range.
7984/// For example, switch like:
7985/// switch (C) { case 1: case 2: case 64: case 128: }
7986/// will be transformed to:
7987/// switch (count_trailing_zeros(C)) { case 0: case 1: case 6: case 7: }
7988///
7989/// This transformation allows better lowering and may transform the switch
7990/// instruction into a sequence of bit manipulation and a smaller
7991/// log2(C)-indexed value table (instead of traditionally emitting a load of the
7992/// address of the jump target, and indirectly jump to it).
7994 DomTreeUpdater *DTU,
7995 const DataLayout &DL,
7996 const TargetTransformInfo &TTI) {
7997 Value *Condition = SI->getCondition();
7998 LLVMContext &Context = SI->getContext();
7999 auto *CondTy = cast<IntegerType>(Condition->getType());
8000
8001 if (CondTy->getIntegerBitWidth() > 64 ||
8002 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8003 return false;
8004
8005 // Ensure trailing zeroes count intrinsic emission is not too expensive.
8006 IntrinsicCostAttributes Attrs(Intrinsic::cttz, CondTy,
8007 {Condition, ConstantInt::getTrue(Context)});
8008 if (TTI.getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) >
8009 TTI::TCC_Basic * 2)
8010 return false;
8011
8012 // Only bother with this optimization if there are more than 3 switch cases.
8013 // SDAG will start emitting jump tables for 4 or more cases.
8014 if (SI->getNumCases() < 4)
8015 return false;
8016
8017 // Check that switch cases are powers of two.
8019 for (const auto &Case : SI->cases()) {
8020 uint64_t CaseValue = Case.getCaseValue()->getValue().getZExtValue();
8021 if (llvm::has_single_bit(CaseValue))
8022 Values.push_back(CaseValue);
8023 else
8024 return false;
8025 }
8026
8027 // isSwichDense requires case values to be sorted.
8029 if (!isSwitchDense(Values.size(),
8030 llvm::countr_zero(Values.back()) -
8031 llvm::countr_zero(Values.front()) + 1,
8032 SI->getFunction()->hasOptSize()))
8033 // Transform is unable to generate dense switch.
8034 return false;
8035
8036 Builder.SetInsertPoint(SI);
8037
8038 if (!SI->defaultDestUnreachable()) {
8039 // Let non-power-of-two inputs jump to the default case, when the latter is
8040 // reachable.
8041 auto *PopC = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Condition);
8042 auto *IsPow2 = Builder.CreateICmpEQ(PopC, ConstantInt::get(CondTy, 1));
8043
8044 auto *OrigBB = SI->getParent();
8045 auto *DefaultCaseBB = SI->getDefaultDest();
8046 BasicBlock *SplitBB = SplitBlock(OrigBB, SI, DTU);
8047 auto It = OrigBB->getTerminator()->getIterator();
8048 SmallVector<uint32_t> Weights;
8049 auto HasWeights =
8051 auto *BI = CondBrInst::Create(IsPow2, SplitBB, DefaultCaseBB, It);
8052 if (HasWeights && any_of(Weights, not_equal_to(0))) {
8053 // IsPow2 covers a subset of the cases in which we'd go to the default
8054 // label. The other is those powers of 2 that don't appear in the case
8055 // statement. We don't know the distribution of the values coming in, so
8056 // the safest is to split 50-50 the original probability to `default`.
8057 uint64_t OrigDenominator =
8059 SmallVector<uint64_t> NewWeights(2);
8060 NewWeights[1] = Weights[0] / 2;
8061 NewWeights[0] = OrigDenominator - NewWeights[1];
8062 setFittedBranchWeights(*BI, NewWeights, /*IsExpected=*/false);
8063 // The probability of executing the default block stays constant. It was
8064 // p_d = Weights[0] / OrigDenominator
8065 // we rewrite as W/D
8066 // We want to find the probability of the default branch of the switch
8067 // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
8068 // i.e. the original probability is the probability we go to the default
8069 // branch from the BI branch, or we take the default branch on the SI.
8070 // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
8071 // This matches using W/2 for the default branch probability numerator and
8072 // D-W/2 as the denominator.
8073 Weights[0] = NewWeights[1];
8074 uint64_t CasesDenominator = OrigDenominator - Weights[0];
8075 for (auto &W : drop_begin(Weights))
8076 W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
8077
8078 setBranchWeights(*SI, Weights, /*IsExpected=*/false);
8079 }
8080 // BI is handling the default case for SI, and so should share its DebugLoc.
8081 BI->setDebugLoc(SI->getDebugLoc());
8082 It->eraseFromParent();
8083
8084 addPredecessorToBlock(DefaultCaseBB, OrigBB, SplitBB);
8085 if (DTU)
8086 DTU->applyUpdates({{DominatorTree::Insert, OrigBB, DefaultCaseBB}});
8087 }
8088
8089 // Replace each case with its trailing zeros number.
8090 for (auto &Case : SI->cases()) {
8091 auto *OrigValue = Case.getCaseValue();
8092 Case.setValue(ConstantInt::get(OrigValue->getIntegerType(),
8093 OrigValue->getValue().countr_zero()));
8094 }
8095
8096 // Replace condition with its trailing zeros number.
8097 auto *ConditionTrailingZeros = Builder.CreateIntrinsic(
8098 Intrinsic::cttz, {CondTy}, {Condition, ConstantInt::getTrue(Context)});
8099
8100 SI->setCondition(ConditionTrailingZeros);
8101
8102 return true;
8103}
8104
8105/// Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have
8106/// the same destination.
8108 DomTreeUpdater *DTU) {
8109 auto *Cmp = dyn_cast<CmpIntrinsic>(SI->getCondition());
8110 if (!Cmp || !Cmp->hasOneUse())
8111 return false;
8112
8114 bool HasWeights = extractBranchWeights(getBranchWeightMDNode(*SI), Weights);
8115 if (!HasWeights)
8116 Weights.resize(4); // Avoid checking HasWeights everywhere.
8117
8118 // Normalize to [us]cmp == Res ? Succ : OtherSucc.
8119 int64_t Res;
8120 BasicBlock *Succ, *OtherSucc;
8121 uint32_t SuccWeight = 0, OtherSuccWeight = 0;
8122 BasicBlock *Unreachable = nullptr;
8123
8124 if (SI->getNumCases() == 2) {
8125 // Find which of 1, 0 or -1 is missing (handled by default dest).
8126 SmallSet<int64_t, 3> Missing;
8127 Missing.insert(1);
8128 Missing.insert(0);
8129 Missing.insert(-1);
8130
8131 Succ = SI->getDefaultDest();
8132 SuccWeight = Weights[0];
8133 OtherSucc = nullptr;
8134 for (auto &Case : SI->cases()) {
8135 std::optional<int64_t> Val =
8136 Case.getCaseValue()->getValue().trySExtValue();
8137 if (!Val)
8138 return false;
8139 if (!Missing.erase(*Val))
8140 return false;
8141 if (OtherSucc && OtherSucc != Case.getCaseSuccessor())
8142 return false;
8143 OtherSucc = Case.getCaseSuccessor();
8144 OtherSuccWeight += Weights[Case.getSuccessorIndex()];
8145 }
8146
8147 assert(Missing.size() == 1 && "Should have one case left");
8148 Res = *Missing.begin();
8149 } else if (SI->getNumCases() == 3 && SI->defaultDestUnreachable()) {
8150 // Normalize so that Succ is taken once and OtherSucc twice.
8151 Unreachable = SI->getDefaultDest();
8152 Succ = OtherSucc = nullptr;
8153 for (auto &Case : SI->cases()) {
8154 BasicBlock *NewSucc = Case.getCaseSuccessor();
8155 uint32_t Weight = Weights[Case.getSuccessorIndex()];
8156 if (!OtherSucc || OtherSucc == NewSucc) {
8157 OtherSucc = NewSucc;
8158 OtherSuccWeight += Weight;
8159 } else if (!Succ) {
8160 Succ = NewSucc;
8161 SuccWeight = Weight;
8162 } else if (Succ == NewSucc) {
8163 std::swap(Succ, OtherSucc);
8164 std::swap(SuccWeight, OtherSuccWeight);
8165 } else
8166 return false;
8167 }
8168 for (auto &Case : SI->cases()) {
8169 std::optional<int64_t> Val =
8170 Case.getCaseValue()->getValue().trySExtValue();
8171 if (!Val || (Val != 1 && Val != 0 && Val != -1))
8172 return false;
8173 if (Case.getCaseSuccessor() == Succ) {
8174 Res = *Val;
8175 break;
8176 }
8177 }
8178 } else {
8179 return false;
8180 }
8181
8182 // Determine predicate for the missing case.
8184 switch (Res) {
8185 case 1:
8186 Pred = ICmpInst::ICMP_UGT;
8187 break;
8188 case 0:
8189 Pred = ICmpInst::ICMP_EQ;
8190 break;
8191 case -1:
8192 Pred = ICmpInst::ICMP_ULT;
8193 break;
8194 }
8195 if (Cmp->isSigned())
8196 Pred = ICmpInst::getSignedPredicate(Pred);
8197
8198 MDNode *NewWeights = nullptr;
8199 if (HasWeights)
8200 NewWeights = MDBuilder(SI->getContext())
8201 .createBranchWeights(SuccWeight, OtherSuccWeight);
8202
8203 BasicBlock *BB = SI->getParent();
8204 Builder.SetInsertPoint(SI->getIterator());
8205 Value *ICmp = Builder.CreateICmp(Pred, Cmp->getLHS(), Cmp->getRHS());
8206 Builder.CreateCondBr(ICmp, Succ, OtherSucc, NewWeights,
8207 SI->getMetadata(LLVMContext::MD_unpredictable));
8208 OtherSucc->removePredecessor(BB);
8209 if (Unreachable)
8210 Unreachable->removePredecessor(BB);
8211 SI->eraseFromParent();
8212 Cmp->eraseFromParent();
8213 if (DTU && Unreachable)
8214 DTU->applyUpdates({{DominatorTree::Delete, BB, Unreachable}});
8215 return true;
8216}
8217
8218/// Checking whether two BBs are equal depends on the contents of the
8219/// BasicBlock and the incoming values of their successor PHINodes.
8220/// PHINode::getIncomingValueForBlock is O(|Preds|), so we'd like to avoid
8221/// calling this function on each BasicBlock every time isEqual is called,
8222/// especially since the same BasicBlock may be passed as an argument multiple
8223/// times. To do this, we can precompute a map of PHINode -> Pred BasicBlock ->
8224/// IncomingValue and add it in the Wrapper so isEqual can do O(1) checking
8225/// of the incoming values.
8228
8229 // One Phi usually has < 8 incoming values.
8233
8234 // We only merge the identical non-entry BBs with
8235 // - terminator unconditional br to Succ (pending relaxation),
8236 // - does not have address taken / weird control.
8237 static bool canBeMerged(const BasicBlock *BB) {
8238 assert(BB && "Expected non-null BB");
8239 // Entry block cannot be eliminated or have predecessors.
8240 if (BB->isEntryBlock())
8241 return false;
8242
8243 // Single successor and must be Succ.
8244 // FIXME: Relax that the terminator is a BranchInst by checking for equality
8245 // on other kinds of terminators. We decide to only support unconditional
8246 // branches for now for compile time reasons.
8247 auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
8248 if (!BI)
8249 return false;
8250
8251 // Avoid blocks that are "address-taken" (blockaddress) or have unusual
8252 // uses.
8253 if (BB->hasAddressTaken() || BB->isEHPad())
8254 return false;
8255
8256 // TODO: relax this condition to merge equal blocks with >1 instructions?
8257 // Here, we use a O(1) form of the O(n) comparison of `size() != 1`.
8258 if (&BB->front() != &BB->back())
8259 return false;
8260
8261 // The BB must have at least one predecessor.
8262 if (pred_empty(BB))
8263 return false;
8264
8265 return true;
8266 }
8267};
8268
8270 static unsigned getHashValue(const EqualBBWrapper *EBW) {
8271 BasicBlock *BB = EBW->BB;
8273 assert(BB->size() == 1 && "Expected just a single branch in the BB");
8274
8275 // Since we assume the BB is just a single UncondBrInst with a single
8276 // successor, we hash as the BB and the incoming Values of its successor
8277 // PHIs. Initially, we tried to just use the successor BB as the hash, but
8278 // including the incoming PHI values leads to better performance.
8279 // We also tried to build a map from BB -> Succs.IncomingValues ahead of
8280 // time and passing it in EqualBBWrapper, but this slowed down the average
8281 // compile time without having any impact on the worst case compile time.
8282 BasicBlock *Succ = BI->getSuccessor();
8283 auto PhiValsForBB = map_range(Succ->phis(), [&](PHINode &Phi) {
8284 return (*EBW->PhiPredIVs)[&Phi][BB];
8285 });
8286 return hash_combine(Succ, hash_combine_range(PhiValsForBB));
8287 }
8288 static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS) {
8289 BasicBlock *A = LHS->BB;
8290 BasicBlock *B = RHS->BB;
8291
8292 // FIXME: we checked that the size of A and B are both 1 in
8293 // mergeIdenticalUncondBBs to make the Case list smaller to
8294 // improve performance. If we decide to support BasicBlocks with more
8295 // than just a single instruction, we need to check that A.size() ==
8296 // B.size() here, and we need to check more than just the BranchInsts
8297 // for equality.
8298
8299 UncondBrInst *ABI = cast<UncondBrInst>(A->getTerminator());
8300 UncondBrInst *BBI = cast<UncondBrInst>(B->getTerminator());
8301 if (ABI->getSuccessor() != BBI->getSuccessor())
8302 return false;
8303
8304 // Need to check that PHIs in successor have matching values.
8305 BasicBlock *Succ = ABI->getSuccessor();
8306 auto IfPhiIVMatch = [&](PHINode &Phi) {
8307 // Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
8308 // query.
8309 auto &PredIVs = (*LHS->PhiPredIVs)[&Phi];
8310 return PredIVs[A] == PredIVs[B];
8311 };
8312 return all_of(Succ->phis(), IfPhiIVMatch);
8313 }
8314};
8315
8316// Merge identical BBs into one of them.
8318 DomTreeUpdater *DTU) {
8319 if (Candidates.size() < 2)
8320 return false;
8321
8322 // Build Cases. Skip BBs that are not candidates for simplification. Mark
8323 // PHINodes which need to be processed into PhiPredIVs. We decide to process
8324 // an entire PHI at once after the loop, opposed to calling
8325 // getIncomingValueForBlock inside this loop, since each call to
8326 // getIncomingValueForBlock is O(|Preds|).
8327 EqualBBWrapper::Phi2IVsMap PhiPredIVs;
8329 BBs2Merge.reserve(Candidates.size());
8331
8332 for (BasicBlock *BB : Candidates) {
8333 BasicBlock *Succ = BB->getSingleSuccessor();
8334 assert(Succ && "Expected unconditional BB");
8335 BBs2Merge.emplace_back(EqualBBWrapper{BB, &PhiPredIVs});
8336 Phis.insert_range(make_pointer_range(Succ->phis()));
8337 }
8338
8339 // Precompute a data structure to improve performance of isEqual for
8340 // EqualBBWrapper.
8341 PhiPredIVs.reserve(Phis.size());
8342 for (PHINode *Phi : Phis) {
8343 auto &IVs =
8344 PhiPredIVs.try_emplace(Phi, Phi->getNumIncomingValues()).first->second;
8345 // Pre-fill all incoming for O(1) lookup as Phi.getIncomingValueForBlock is
8346 // O(|Pred|).
8347 for (auto &IV : Phi->incoming_values())
8348 IVs.insert({Phi->getIncomingBlock(IV), IV.get()});
8349 }
8350
8351 // Group duplicates using DenseSet with custom equality/hashing.
8352 // Build a set such that if the EqualBBWrapper exists in the set and another
8353 // EqualBBWrapper isEqual, then the equivalent EqualBBWrapper which is not in
8354 // the set should be replaced with the one in the set. If the EqualBBWrapper
8355 // is not in the set, then it should be added to the set so other
8356 // EqualBBWrapper can check against it in the same manner. We use
8357 // EqualBBWrapper instead of just BasicBlock because we'd like to pass around
8358 // information to isEquality, getHashValue, and when doing the replacement
8359 // with better performance.
8361 Keep.reserve(BBs2Merge.size());
8362
8364 Updates.reserve(BBs2Merge.size() * 2);
8365
8366 bool MadeChange = false;
8367
8368 // Helper: redirect all edges X -> DeadPred to X -> LivePred.
8369 auto RedirectIncomingEdges = [&](BasicBlock *Dead, BasicBlock *Live) {
8372 if (DTU) {
8373 // All predecessors of DeadPred (except the common predecessor) will be
8374 // moved to LivePred.
8375 Updates.reserve(Updates.size() + DeadPreds.size() * 2);
8377 predecessors(Live));
8378 for (BasicBlock *PredOfDead : DeadPreds) {
8379 // Do not modify those common predecessors of DeadPred and LivePred.
8380 if (!LivePreds.contains(PredOfDead))
8381 Updates.push_back({DominatorTree::Insert, PredOfDead, Live});
8382 Updates.push_back({DominatorTree::Delete, PredOfDead, Dead});
8383 }
8384 }
8385 LLVM_DEBUG(dbgs() << "Replacing duplicate pred BB ";
8386 Dead->printAsOperand(dbgs()); dbgs() << " with pred ";
8387 Live->printAsOperand(dbgs()); dbgs() << " for ";
8388 Live->getSingleSuccessor()->printAsOperand(dbgs());
8389 dbgs() << "\n");
8390 // Replace successors in all predecessors of DeadPred.
8391 for (BasicBlock *PredOfDead : DeadPreds) {
8392 Instruction *T = PredOfDead->getTerminator();
8393 T->replaceSuccessorWith(Dead, Live);
8394 }
8395 };
8396
8397 // Try to eliminate duplicate predecessors.
8398 for (const auto &EBW : BBs2Merge) {
8399 // EBW is a candidate for simplification. If we find a duplicate BB,
8400 // replace it.
8401 const auto &[It, Inserted] = Keep.insert(&EBW);
8402 if (Inserted)
8403 continue;
8404
8405 // Found duplicate: merge P into canonical predecessor It->Pred.
8406 BasicBlock *KeepBB = (*It)->BB;
8407 BasicBlock *DeadBB = EBW.BB;
8408
8409 // Avoid merging a BB with itself.
8410 if (KeepBB == DeadBB)
8411 continue;
8412
8413 // Redirect all edges into DeadPred to KeepPred.
8414 RedirectIncomingEdges(DeadBB, KeepBB);
8415
8416 // Now DeadBB should become unreachable; leave DCE to later,
8417 // but we can try to simplify it if it only branches to Succ.
8418 // (We won't erase here to keep the routine simple and DT-safe.)
8419 assert(pred_empty(DeadBB) && "DeadBB should be unreachable.");
8420 MadeChange = true;
8421 }
8422
8423 if (DTU && !Updates.empty())
8424 DTU->applyUpdates(Updates);
8425
8426 return MadeChange;
8427}
8428
8429bool SimplifyCFGOpt::simplifyDuplicateSwitchArms(SwitchInst *SI,
8430 DomTreeUpdater *DTU) {
8431 // Collect candidate switch-arms top-down.
8432 SmallSetVector<BasicBlock *, 16> FilteredArms(
8435 return mergeIdenticalBBs(FilteredArms.getArrayRef(), DTU);
8436}
8437
8438bool SimplifyCFGOpt::simplifyDuplicatePredecessors(BasicBlock *BB,
8439 DomTreeUpdater *DTU) {
8440 // Need at least 2 predecessors to do anything.
8441 if (!BB || !BB->hasNPredecessorsOrMore(2))
8442 return false;
8443
8444 // Compilation time consideration: retain the canonical loop, otherwise, we
8445 // require more time in the later loop canonicalization.
8446 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BB))
8447 return false;
8448
8449 // Collect candidate predecessors bottom-up.
8450 SmallSetVector<BasicBlock *, 8> FilteredPreds(
8453 return mergeIdenticalBBs(FilteredPreds.getArrayRef(), DTU);
8454}
8455
8456bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
8457 BasicBlock *BB = SI->getParent();
8458
8459 if (isValueEqualityComparison(SI)) {
8460 // If we only have one predecessor, and if it is a branch on this value,
8461 // see if that predecessor totally determines the outcome of this switch.
8462 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8463 if (simplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
8464 return requestResimplify();
8465
8466 Value *Cond = SI->getCondition();
8467 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
8468 if (simplifySwitchOnSelect(SI, Select))
8469 return requestResimplify();
8470
8471 // If the block only contains the switch, see if we can fold the block
8472 // away into any preds.
8473 if (SI == &*BB->begin())
8474 if (foldValueComparisonIntoPredecessors(SI, Builder))
8475 return requestResimplify();
8476 }
8477
8478 // Try to transform the switch into an icmp and a branch.
8479 // The conversion from switch to comparison may lose information on
8480 // impossible switch values, so disable it early in the pipeline.
8481 if (Options.ConvertSwitchRangeToICmp && turnSwitchRangeIntoICmp(SI, Builder))
8482 return requestResimplify();
8483
8484 // Remove unreachable cases.
8485 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
8486 return requestResimplify();
8487
8488 if (simplifySwitchOfCmpIntrinsic(SI, Builder, DTU))
8489 return requestResimplify();
8490
8491 if (trySwitchToSelect(SI, Builder, DTU, DL, TTI))
8492 return requestResimplify();
8493
8494 if (Options.ForwardSwitchCondToPhi && forwardSwitchConditionToPHI(SI))
8495 return requestResimplify();
8496
8497 // The conversion of switches to arithmetic or lookup table is disabled in
8498 // the early optimization pipeline, as it may lose information or make the
8499 // resulting code harder to analyze.
8500 if (Options.ConvertSwitchToArithmetic || Options.ConvertSwitchToLookupTable)
8501 if (simplifySwitchLookup(SI, Builder, DTU, DL, TTI,
8502 Options.ConvertSwitchToLookupTable))
8503 return requestResimplify();
8504
8505 if (simplifySwitchOfPowersOfTwo(SI, Builder, DTU, DL, TTI))
8506 return requestResimplify();
8507
8508 if (reduceSwitchRange(SI, Builder, DL, TTI))
8509 return requestResimplify();
8510
8511 if (HoistCommon &&
8512 hoistCommonCodeFromSuccessors(SI, !Options.HoistCommonInsts))
8513 return requestResimplify();
8514
8515 // We can merge identical switch arms early to enhance more aggressive
8516 // optimization on switch.
8517 if (simplifyDuplicateSwitchArms(SI, DTU))
8518 return requestResimplify();
8519
8520 if (simplifySwitchWhenUMin(SI, DTU))
8521 return requestResimplify();
8522
8523 if (simplifySwitchDefaultBranch(SI, DTU, DL, Options.AC))
8524 return requestResimplify();
8525
8526 return false;
8527}
8528
8529bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
8530 BasicBlock *BB = IBI->getParent();
8531 bool Changed = false;
8532 SmallVector<uint32_t> BranchWeights;
8533 const bool HasBranchWeights = !ProfcheckDisableMetadataFixes &&
8534 extractBranchWeights(*IBI, BranchWeights);
8535
8536 DenseMap<const BasicBlock *, uint64_t> TargetWeight;
8537 if (HasBranchWeights)
8538 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8539 TargetWeight[IBI->getDestination(I)] += BranchWeights[I];
8540
8541 // Eliminate redundant destinations.
8542 SmallPtrSet<Value *, 8> Succs;
8543 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
8544 for (unsigned I = 0, E = IBI->getNumDestinations(); I != E; ++I) {
8545 BasicBlock *Dest = IBI->getDestination(I);
8546 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
8547 if (!Dest->hasAddressTaken())
8548 RemovedSuccs.insert(Dest);
8549 Dest->removePredecessor(BB);
8550 IBI->removeDestination(I);
8551 --I;
8552 --E;
8553 Changed = true;
8554 }
8555 }
8556
8557 if (DTU) {
8558 std::vector<DominatorTree::UpdateType> Updates;
8559 Updates.reserve(RemovedSuccs.size());
8560 for (auto *RemovedSucc : RemovedSuccs)
8561 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
8562 DTU->applyUpdates(Updates);
8563 }
8564
8565 if (IBI->getNumDestinations() == 0) {
8566 // If the indirectbr has no successors, change it to unreachable.
8567 new UnreachableInst(IBI->getContext(), IBI->getIterator());
8569 return true;
8570 }
8571
8572 if (IBI->getNumDestinations() == 1) {
8573 // If the indirectbr has one successor, change it to a direct branch.
8576 return true;
8577 }
8578 if (HasBranchWeights) {
8579 SmallVector<uint64_t> NewBranchWeights(IBI->getNumDestinations());
8580 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8581 NewBranchWeights[I] += TargetWeight.find(IBI->getDestination(I))->second;
8582 setFittedBranchWeights(*IBI, NewBranchWeights, /*IsExpected=*/false);
8583 }
8584 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
8585 if (simplifyIndirectBrOnSelect(IBI, SI))
8586 return requestResimplify();
8587 }
8588 return Changed;
8589}
8590
8591/// Given an block with only a single landing pad and a unconditional branch
8592/// try to find another basic block which this one can be merged with. This
8593/// handles cases where we have multiple invokes with unique landing pads, but
8594/// a shared handler.
8595///
8596/// We specifically choose to not worry about merging non-empty blocks
8597/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
8598/// practice, the optimizer produces empty landing pad blocks quite frequently
8599/// when dealing with exception dense code. (see: instcombine, gvn, if-else
8600/// sinking in this file)
8601///
8602/// This is primarily a code size optimization. We need to avoid performing
8603/// any transform which might inhibit optimization (such as our ability to
8604/// specialize a particular handler via tail commoning). We do this by not
8605/// merging any blocks which require us to introduce a phi. Since the same
8606/// values are flowing through both blocks, we don't lose any ability to
8607/// specialize. If anything, we make such specialization more likely.
8608///
8609/// TODO - This transformation could remove entries from a phi in the target
8610/// block when the inputs in the phi are the same for the two blocks being
8611/// merged. In some cases, this could result in removal of the PHI entirely.
8613 BasicBlock *BB, DomTreeUpdater *DTU) {
8614 auto Succ = BB->getUniqueSuccessor();
8615 assert(Succ);
8616 // If there's a phi in the successor block, we'd likely have to introduce
8617 // a phi into the merged landing pad block.
8618 if (isa<PHINode>(*Succ->begin()))
8619 return false;
8620
8621 for (BasicBlock *OtherPred : predecessors(Succ)) {
8622 if (BB == OtherPred)
8623 continue;
8624 BasicBlock::iterator I = OtherPred->begin();
8626 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
8627 continue;
8628 ++I;
8630 if (!BI2 || !BI2->isIdenticalTo(BI))
8631 continue;
8632
8633 std::vector<DominatorTree::UpdateType> Updates;
8634
8635 // We've found an identical block. Update our predecessors to take that
8636 // path instead and make ourselves dead.
8638 for (BasicBlock *Pred : UniquePreds) {
8639 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
8640 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
8641 "unexpected successor");
8642 II->setUnwindDest(OtherPred);
8643 if (DTU) {
8644 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
8645 Updates.push_back({DominatorTree::Delete, Pred, BB});
8646 }
8647 }
8648
8650 for (BasicBlock *Succ : UniqueSuccs) {
8651 Succ->removePredecessor(BB);
8652 if (DTU)
8653 Updates.push_back({DominatorTree::Delete, BB, Succ});
8654 }
8655
8656 IRBuilder<> Builder(BI);
8657 Builder.CreateUnreachable();
8658 BI->eraseFromParent();
8659 if (DTU)
8660 DTU->applyUpdates(Updates);
8661 return true;
8662 }
8663 return false;
8664}
8665
8666bool SimplifyCFGOpt::simplifyUncondBranch(UncondBrInst *BI,
8667 IRBuilder<> &Builder) {
8668 BasicBlock *BB = BI->getParent();
8669 BasicBlock *Succ = BI->getSuccessor(0);
8670
8671 // If the Terminator is the only non-phi instruction, simplify the block.
8672 // If LoopHeader is provided, check if the block or its successor is a loop
8673 // header. (This is for early invocations before loop simplify and
8674 // vectorization to keep canonical loop forms for nested loops. These blocks
8675 // can be eliminated when the pass is invoked later in the back-end.)
8676 // Note that if BB has only one predecessor then we do not introduce new
8677 // backedge, so we can eliminate BB.
8678 bool NeedCanonicalLoop =
8679 Options.NeedCanonicalLoop &&
8680 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
8681 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
8683 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
8684 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
8685 return true;
8686
8687 // If the only instruction in the block is a seteq/setne comparison against a
8688 // constant, try to simplify the block.
8689 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
8690 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
8691 ++I;
8692 if (I->isTerminator() &&
8693 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
8694 return true;
8695 if (isa<SelectInst>(I) && I->getNextNode()->isTerminator() &&
8696 tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, cast<SelectInst>(I),
8697 Builder))
8698 return true;
8699 }
8700 }
8701
8702 // See if we can merge an empty landing pad block with another which is
8703 // equivalent.
8704 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
8705 ++I;
8706 if (I->isTerminator() && tryToMergeLandingPad(LPad, BI, BB, DTU))
8707 return true;
8708 }
8709
8710 return false;
8711}
8712
8714 BasicBlock *PredPred = nullptr;
8715 for (auto *P : predecessors(BB)) {
8716 BasicBlock *PPred = P->getSinglePredecessor();
8717 if (!PPred || (PredPred && PredPred != PPred))
8718 return nullptr;
8719 PredPred = PPred;
8720 }
8721 return PredPred;
8722}
8723
8724/// Fold the following pattern:
8725/// bb0:
8726/// br i1 %cond1, label %bb1, label %bb2
8727/// bb1:
8728/// br i1 %cond2, label %bb3, label %bb4
8729/// bb2:
8730/// br i1 %cond2, label %bb4, label %bb3
8731/// bb3:
8732/// ...
8733/// bb4:
8734/// ...
8735/// into
8736/// bb0:
8737/// %cond = xor i1 %cond1, %cond2
8738/// br i1 %cond, label %bb4, label %bb3
8739/// bb3:
8740/// ...
8741/// bb4:
8742/// ...
8743/// NOTE: %cond2 always dominates the terminator of bb0.
8745 BasicBlock *BB = BI->getParent();
8746 BasicBlock *BB1 = BI->getSuccessor(0);
8747 BasicBlock *BB2 = BI->getSuccessor(1);
8748 auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
8749 if (Succ == BB)
8750 return false;
8751 if (&Succ->front() != Succ->getTerminator())
8752 return false;
8753 SuccBI = dyn_cast<CondBrInst>(Succ->getTerminator());
8754 if (!SuccBI)
8755 return false;
8756 BasicBlock *Succ1 = SuccBI->getSuccessor(0);
8757 BasicBlock *Succ2 = SuccBI->getSuccessor(1);
8758 return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
8759 !isa<PHINode>(Succ1->front()) && !isa<PHINode>(Succ2->front());
8760 };
8761 CondBrInst *BB1BI, *BB2BI;
8762 if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
8763 return false;
8764
8765 if (BB1BI->getCondition() != BB2BI->getCondition() ||
8766 BB1BI->getSuccessor(0) != BB2BI->getSuccessor(1) ||
8767 BB1BI->getSuccessor(1) != BB2BI->getSuccessor(0))
8768 return false;
8769
8770 BasicBlock *BB3 = BB1BI->getSuccessor(0);
8771 BasicBlock *BB4 = BB1BI->getSuccessor(1);
8772 // Bail out on trivial cases to avoid bothering to handle the special case in
8773 // the code below.
8774 if (BB3 == BB4)
8775 return false;
8776 IRBuilder<> Builder(BI);
8777 BI->setCondition(
8778 Builder.CreateXor(BI->getCondition(), BB1BI->getCondition()));
8779 BB1->removePredecessor(BB);
8780 BI->setSuccessor(0, BB4);
8781 BB2->removePredecessor(BB);
8782 BI->setSuccessor(1, BB3);
8783 if (DTU) {
8785 Updates.push_back({DominatorTree::Delete, BB, BB1});
8786 Updates.push_back({DominatorTree::Insert, BB, BB4});
8787 Updates.push_back({DominatorTree::Delete, BB, BB2});
8788 Updates.push_back({DominatorTree::Insert, BB, BB3});
8789
8790 DTU->applyUpdates(Updates);
8791 }
8792 bool HasWeight = false;
8793 uint64_t BBTWeight, BBFWeight;
8794 if (extractBranchWeights(*BI, BBTWeight, BBFWeight))
8795 HasWeight = true;
8796 else
8797 BBTWeight = BBFWeight = 1;
8798 uint64_t BB1TWeight, BB1FWeight;
8799 if (extractBranchWeights(*BB1BI, BB1TWeight, BB1FWeight))
8800 HasWeight = true;
8801 else
8802 BB1TWeight = BB1FWeight = 1;
8803 uint64_t BB2TWeight, BB2FWeight;
8804 if (extractBranchWeights(*BB2BI, BB2TWeight, BB2FWeight))
8805 HasWeight = true;
8806 else
8807 BB2TWeight = BB2FWeight = 1;
8808 if (HasWeight) {
8809 uint64_t Weights[2] = {BBTWeight * BB1FWeight + BBFWeight * BB2TWeight,
8810 BBTWeight * BB1TWeight + BBFWeight * BB2FWeight};
8811 setFittedBranchWeights(*BI, Weights, /*IsExpected=*/false,
8812 /*ElideAllZero=*/true);
8813 }
8814 return true;
8815}
8816
8817bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
8818 assert(
8820 BI->getSuccessor(0) != BI->getSuccessor(1) &&
8821 "Tautological conditional branch should have been eliminated already.");
8822
8823 BasicBlock *BB = BI->getParent();
8824 if (!Options.SimplifyCondBranch ||
8825 BI->getFunction()->hasFnAttribute(Attribute::OptForFuzzing))
8826 return false;
8827
8828 // Conditional branch
8829 if (isValueEqualityComparison(BI)) {
8830 // If we only have one predecessor, and if it is a branch on this value,
8831 // see if that predecessor totally determines the outcome of this
8832 // switch.
8833 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8834 if (simplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
8835 return requestResimplify();
8836
8837 // This block must be empty, except for the setcond inst, if it exists.
8838 // Ignore pseudo intrinsics.
8839 for (auto &I : *BB) {
8840 if (isa<PseudoProbeInst>(I) ||
8841 &I == cast<Instruction>(BI->getCondition()))
8842 continue;
8843 if (&I == BI)
8844 if (foldValueComparisonIntoPredecessors(BI, Builder))
8845 return requestResimplify();
8846 break;
8847 }
8848 }
8849
8850 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
8851 if (simplifyBranchOnICmpChain(BI, Builder, DL))
8852 return true;
8853
8854 // If this basic block has dominating predecessor blocks and the dominating
8855 // blocks' conditions imply BI's condition, we know the direction of BI.
8856 std::optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
8857 if (Imp) {
8858 // Turn this into a branch on constant.
8859 auto *OldCond = BI->getCondition();
8860 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
8861 : ConstantInt::getFalse(BB->getContext());
8862 BI->setCondition(TorF);
8864 return requestResimplify();
8865 }
8866
8867 // If this basic block is ONLY a compare and a branch, and if a predecessor
8868 // branches to us and one of our successors, fold the comparison into the
8869 // predecessor and use logical operations to pick the right destination.
8870 if (Options.SpeculateBlocks &&
8871 foldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, Options.AC,
8872 Options.BonusInstThreshold))
8873 return requestResimplify();
8874
8875 // We have a conditional branch to two blocks that are only reachable
8876 // from BI. We know that the condbr dominates the two blocks, so see if
8877 // there is any identical code in the "then" and "else" blocks. If so, we
8878 // can hoist it up to the branching block.
8879 if (BI->getSuccessor(0)->getSinglePredecessor()) {
8880 if (BI->getSuccessor(1)->getSinglePredecessor()) {
8881 if (HoistCommon &&
8882 hoistCommonCodeFromSuccessors(BI, !Options.HoistCommonInsts))
8883 return requestResimplify();
8884
8885 if (BI && Options.HoistLoadsStoresWithCondFaulting &&
8886 isProfitableToSpeculate(BI, std::nullopt, TTI)) {
8887 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
8888 auto CanSpeculateConditionalLoadsStores = [&]() {
8889 for (auto *Succ : successors(BB)) {
8890 for (Instruction &I : *Succ) {
8891 if (I.isTerminator()) {
8892 if (I.getNumSuccessors() > 1)
8893 return false;
8894 continue;
8895 } else if (!isSafeCheapLoadStore(&I, TTI) ||
8896 SpeculatedConditionalLoadsStores.size() ==
8898 return false;
8899 }
8900 SpeculatedConditionalLoadsStores.push_back(&I);
8901 }
8902 }
8903 return !SpeculatedConditionalLoadsStores.empty();
8904 };
8905
8906 if (CanSpeculateConditionalLoadsStores()) {
8907 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores,
8908 std::nullopt, nullptr);
8909 return requestResimplify();
8910 }
8911 }
8912 } else {
8913 // If Successor #1 has multiple preds, we may be able to conditionally
8914 // execute Successor #0 if it branches to Successor #1.
8915 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
8916 if (Succ0TI->getNumSuccessors() == 1 &&
8917 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
8918 if (speculativelyExecuteBB(BI, BI->getSuccessor(0)))
8919 return requestResimplify();
8920 }
8921 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
8922 // If Successor #0 has multiple preds, we may be able to conditionally
8923 // execute Successor #1 if it branches to Successor #0.
8924 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
8925 if (Succ1TI->getNumSuccessors() == 1 &&
8926 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
8927 if (speculativelyExecuteBB(BI, BI->getSuccessor(1)))
8928 return requestResimplify();
8929 }
8930
8931 // If this is a branch on something for which we know the constant value in
8932 // predecessors (e.g. a phi node in the current block), thread control
8933 // through this block.
8934 if (foldCondBranchOnValueKnownInPredecessor(BI))
8935 return requestResimplify();
8936
8937 // Scan predecessor blocks for conditional branches.
8938 for (BasicBlock *Pred : predecessors(BB))
8939 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator()))
8940 if (PBI != BI)
8941 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
8942 return requestResimplify();
8943
8944 // Look for diamond patterns.
8945 if (MergeCondStores)
8946 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
8947 if (CondBrInst *PBI = dyn_cast<CondBrInst>(PrevBB->getTerminator()))
8948 if (PBI != BI)
8949 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
8950 return requestResimplify();
8951
8952 // Look for nested conditional branches.
8953 if (mergeNestedCondBranch(BI, DTU))
8954 return requestResimplify();
8955
8956 return false;
8957}
8958
8959/// Check if passing a value to an instruction will cause undefined behavior.
8960static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
8961 assert(V->getType() == I->getType() && "Mismatched types");
8963 if (!C)
8964 return false;
8965
8966 if (I->use_empty())
8967 return false;
8968
8969 if (C->isNullValue() || isa<UndefValue>(C)) {
8970 // Find the first same-block use with a UB-triggering opcode, skipping
8971 // cross-block or before-I uses.
8972 auto FindUse = llvm::find_if(I->uses(), [I](auto &U) {
8973 auto *Use = cast<Instruction>(U.getUser());
8974 // Only same-block uses after I can witness UB at I's program point.
8975 // Self-uses and before-I uses can occur when I is a PHI node.
8976 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
8977 return false;
8978 // Change this list when we want to add new instructions.
8979 switch (Use->getOpcode()) {
8980 default:
8981 return false;
8982 case Instruction::GetElementPtr:
8983 case Instruction::Ret:
8984 case Instruction::BitCast:
8985 case Instruction::Load:
8986 case Instruction::Store:
8987 case Instruction::Call:
8988 case Instruction::CallBr:
8989 case Instruction::Invoke:
8990 case Instruction::UDiv:
8991 case Instruction::URem:
8992 // Note: signed div/rem of INT_MIN / -1 is also immediate UB, not
8993 // implemented to avoid code complexity as it is unclear how useful such
8994 // logic is.
8995 case Instruction::SDiv:
8996 case Instruction::SRem:
8997 return true;
8998 }
8999 });
9000 if (FindUse == I->use_end())
9001 return false;
9002 auto &Use = *FindUse;
9003 auto *User = cast<Instruction>(Use.getUser());
9004
9005 // Now make sure that there are no instructions in between that can alter
9006 // control flow (eg. calls)
9007 auto InstrRange =
9008 make_range(std::next(I->getIterator()), User->getIterator());
9009 if (any_of(InstrRange, [](Instruction &I) {
9011 }))
9012 return false;
9013
9014 // Look through GEPs. A load from a GEP derived from NULL is still undefined
9016 if (GEP->getPointerOperand() == I) {
9017 // The type of GEP may differ from the type of base pointer.
9018 // Bail out on vector GEPs, as they are not handled by other checks.
9019 if (GEP->getType()->isVectorTy())
9020 return false;
9021 // The current base address is null, there are four cases to consider:
9022 // getelementptr (TY, null, 0) -> null
9023 // getelementptr (TY, null, not zero) -> may be modified
9024 // getelementptr inbounds (TY, null, 0) -> null
9025 // getelementptr inbounds (TY, null, not zero) -> poison iff null is
9026 // undefined?
9027 if (!GEP->hasAllZeroIndices() &&
9028 (!GEP->isInBounds() ||
9029 NullPointerIsDefined(GEP->getFunction(),
9030 GEP->getPointerAddressSpace())))
9031 PtrValueMayBeModified = true;
9032 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
9033 }
9034
9035 // Look through return.
9036 if (ReturnInst *Ret = dyn_cast<ReturnInst>(User)) {
9037 bool HasNoUndefAttr =
9038 Ret->getFunction()->hasRetAttribute(Attribute::NoUndef);
9039 // Return undefined to a noundef return value is undefined.
9040 if (isa<UndefValue>(C) && HasNoUndefAttr)
9041 return true;
9042 // Return null to a nonnull+noundef return value is undefined.
9043 if (C->isNullValue() && HasNoUndefAttr &&
9044 Ret->getFunction()->hasRetAttribute(Attribute::NonNull)) {
9045 return !PtrValueMayBeModified;
9046 }
9047 }
9048
9049 // Load from null is undefined.
9050 if (LoadInst *LI = dyn_cast<LoadInst>(User))
9051 if (!LI->isVolatile())
9052 return !NullPointerIsDefined(LI->getFunction(),
9053 LI->getPointerAddressSpace());
9054
9055 // Store to null is undefined.
9057 if (!SI->isVolatile())
9058 return (!NullPointerIsDefined(SI->getFunction(),
9059 SI->getPointerAddressSpace())) &&
9060 SI->getPointerOperand() == I;
9061
9062 // llvm.assume(false/undef) always triggers immediate UB.
9063 if (auto *Assume = dyn_cast<AssumeInst>(User)) {
9064 // Ignore assume operand bundles.
9065 if (I == Assume->getArgOperand(0))
9066 return true;
9067 }
9068
9069 if (auto *CB = dyn_cast<CallBase>(User)) {
9070 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
9071 return false;
9072 // A call to null is undefined.
9073 if (CB->getCalledOperand() == I)
9074 return true;
9075
9076 if (CB->isArgOperand(&Use)) {
9077 unsigned ArgIdx = CB->getArgOperandNo(&Use);
9078 // Passing null to a nonnnull+noundef argument is undefined.
9079 if (isa<ConstantPointerNull>(C) && C->getType()->isPointerTy() &&
9080 CB->paramHasNonNullAttr(ArgIdx, /*AllowUndefOrPoison=*/false))
9081 return !PtrValueMayBeModified;
9082 // Passing undef to a noundef argument is undefined.
9083 if (isa<UndefValue>(C) && CB->isPassingUndefUB(ArgIdx))
9084 return true;
9085 }
9086 }
9087 // Div/Rem by zero is immediate UB
9088 if (match(User, m_BinOp(m_Value(), m_Specific(I))) && User->isIntDivRem())
9089 return true;
9090 }
9091 return false;
9092}
9093
9094/// If BB has an incoming value that will always trigger undefined behavior
9095/// (eg. null pointer dereference), remove the branch leading here.
9097 DomTreeUpdater *DTU,
9098 AssumptionCache *AC) {
9099 for (PHINode &PHI : BB->phis())
9100 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
9101 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
9102 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
9103 Instruction *T = Predecessor->getTerminator();
9104 IRBuilder<> Builder(T);
9105 if (isa<UncondBrInst>(T)) {
9106 BB->removePredecessor(Predecessor);
9107 // Turn unconditional branches into unreachables.
9108 Builder.CreateUnreachable();
9109 T->eraseFromParent();
9110 if (DTU)
9111 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9112 return true;
9113 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(T)) {
9114 BB->removePredecessor(Predecessor);
9115 // Handle degenerate conditional branches.
9116 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
9117 // The only difference from the UncondBrInst path above is that it
9118 // has two edges in CFG.
9119 BB->removePredecessor(Predecessor);
9120 // Turn unconditional branches into unreachables.
9121 Builder.CreateUnreachable();
9122 } else {
9123 // Preserve guarding condition in assume, because it might not be
9124 // inferrable from any dominating condition.
9125 Value *Cond = BI->getCondition();
9126 CallInst *Assumption;
9127 if (BI->getSuccessor(0) == BB)
9128 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
9129 else
9130 Assumption = Builder.CreateAssumption(Cond);
9131 if (AC)
9132 AC->registerAssumption(cast<AssumeInst>(Assumption));
9133 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
9134 : BI->getSuccessor(0));
9135 }
9136 BI->eraseFromParent();
9137 if (DTU)
9138 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9139 return true;
9140 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
9141 // Redirect all branches leading to UB into
9142 // a newly created unreachable block.
9143 BasicBlock *Unreachable = BasicBlock::Create(
9144 Predecessor->getContext(), "unreachable", BB->getParent(), BB);
9145 Builder.SetInsertPoint(Unreachable);
9146 // The new block contains only one instruction: Unreachable
9147 Builder.CreateUnreachable();
9148 for (const auto &Case : SI->cases())
9149 if (Case.getCaseSuccessor() == BB) {
9150 BB->removePredecessor(Predecessor);
9151 Case.setSuccessor(Unreachable);
9152 }
9153 if (SI->getDefaultDest() == BB) {
9154 BB->removePredecessor(Predecessor);
9155 SI->setDefaultDest(Unreachable);
9156 }
9157
9158 if (DTU)
9159 DTU->applyUpdates(
9160 { { DominatorTree::Insert, Predecessor, Unreachable },
9161 { DominatorTree::Delete, Predecessor, BB } });
9162 return true;
9163 }
9164 }
9165
9166 return false;
9167}
9168
9169bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
9170 bool Changed = false;
9171
9172 assert(BB && BB->getParent() && "Block not embedded in function!");
9173 assert(BB->getTerminator() && "Degenerate basic block encountered!");
9174
9175 // Remove basic blocks that have no predecessors (except the entry block)...
9176 // or that just have themself as a predecessor. These are unreachable.
9177 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
9178 BB->getSinglePredecessor() == BB) {
9179 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
9180 DeleteDeadBlock(BB, DTU);
9181 return true;
9182 }
9183
9184 // Check to see if we can constant propagate this terminator instruction
9185 // away...
9186 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
9187 /*TLI=*/nullptr, DTU);
9188
9189 // Check for and eliminate duplicate PHI nodes in this block.
9191
9192 // Check for and remove branches that will always cause undefined behavior.
9194 return requestResimplify();
9195
9196 // Merge basic blocks into their predecessor if there is only one distinct
9197 // pred, and if there is only one distinct successor of the predecessor, and
9198 // if there are no PHI nodes.
9199 if (MergeBlockIntoPredecessor(BB, DTU))
9200 return true;
9201
9202 if (SinkCommon && Options.SinkCommonInsts) {
9203 if (sinkCommonCodeFromPredecessors(BB, DTU) ||
9204 mergeCompatibleInvokes(BB, DTU)) {
9205 // sinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
9206 // so we may now how duplicate PHI's.
9207 // Let's rerun EliminateDuplicatePHINodes() first,
9208 // before foldTwoEntryPHINode() potentially converts them into select's,
9209 // after which we'd need a whole EarlyCSE pass run to cleanup them.
9210 return true;
9211 }
9212 // Merge identical predecessors of this block.
9213 if (simplifyDuplicatePredecessors(BB, DTU))
9214 return true;
9215 }
9216
9217 if (Options.SpeculateBlocks &&
9218 !BB->getParent()->hasFnAttribute(Attribute::OptForFuzzing)) {
9219 // If there is a trivial two-entry PHI node in this basic block, and we can
9220 // eliminate it, do so now.
9221 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
9222 if (PN->getNumIncomingValues() == 2)
9223 if (foldTwoEntryPHINode(PN, TTI, DTU, Options.AC, DL,
9224 Options.SpeculateUnpredictables))
9225 return true;
9226 }
9227
9228 IRBuilder<> Builder(BB);
9230 Builder.SetInsertPoint(Terminator);
9231 switch (Terminator->getOpcode()) {
9232 case Instruction::UncondBr:
9233 Changed |= simplifyUncondBranch(cast<UncondBrInst>(Terminator), Builder);
9234 break;
9235 case Instruction::CondBr:
9236 Changed |= simplifyCondBranch(cast<CondBrInst>(Terminator), Builder);
9237 break;
9238 case Instruction::Resume:
9239 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
9240 break;
9241 case Instruction::CleanupRet:
9242 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
9243 break;
9244 case Instruction::Switch:
9245 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
9246 break;
9247 case Instruction::Unreachable:
9248 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
9249 break;
9250 case Instruction::IndirectBr:
9251 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
9252 break;
9253 }
9254
9255 return Changed;
9256}
9257
9258bool SimplifyCFGOpt::run(BasicBlock *BB) {
9259 bool Changed = false;
9260
9261 // Repeated simplify BB as long as resimplification is requested.
9262 do {
9263 Resimplify = false;
9264
9265 // Perform one round of simplifcation. Resimplify flag will be set if
9266 // another iteration is requested.
9267 Changed |= simplifyOnce(BB);
9268 } while (Resimplify);
9269
9270 return Changed;
9271}
9272
9275 ArrayRef<WeakVH> LoopHeaders) {
9276 return SimplifyCFGOpt(TTI, DTU, BB->getDataLayout(), LoopHeaders,
9277 Options)
9278 .run(BB);
9279}
#define Fail
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned 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:856
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...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
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.
const SmallVectorImpl< MachineOperand > & Cond
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:484
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 getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant * > > &Res, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to determine the resulting constant values in phi nodes at the common destination basic block,...
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 std::optional< bool > foldCondBranchOnValueKnownInPredecessorImpl(CondBrInst *BI, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL)
If we have a conditional branch on something for which we know the constant value in predecessors (e....
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 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 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 bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
If a switch is only used to initialize one or more phi nodes in a common successor block with only tw...
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 Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB)
Determine if we can hoist sink a sole store instruction out of a conditional 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 initializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, const TargetTransformInfo &TTI, uintptr_t MaxUniqueResults)
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 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 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 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:231
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1552
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
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:472
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1996
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1595
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1977
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:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
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 hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
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 InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
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:469
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 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:467
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:644
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
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
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.
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.
This is an important base class in LLVM.
Definition Constant.h:43
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:64
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:89
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:244
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:172
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:159
static DebugLoc getDropped()
Definition DebugLoc.h:155
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:268
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
unsigned size() const
Definition DenseMap.h:172
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:176
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
const BasicBlock & getEntryBlock() const
Definition Function.h:793
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:762
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:695
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:727
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.
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:114
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2391
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:1216
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:457
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:2728
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:221
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1532
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:1210
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1854
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:1239
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2375
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:1906
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:1422
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:462
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:2316
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2485
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1592
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1456
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:75
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
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.
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.
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()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
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
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 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:348
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:68
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:1069
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:67
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
Definition SmallPtrSet.h:99
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:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
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:1631
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:36
LLVM_ABI void set(Value *Val)
Definition Value.h:874
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:255
static constexpr uint64_t MaximumAlignment
Definition Value.h:799
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:54
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
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.
Changed
#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:81
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:205
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(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:315
@ Offset
Definition DWP.cpp:578
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:830
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:2180
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:1765
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
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:1739
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:535
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:134
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:1702
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:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
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:633
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:2134
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:1791
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.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
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"))
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
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:1746
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:1160
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:407
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:1636
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 void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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...
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:1753
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1399
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:2888
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:551
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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:3130
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:322
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"))
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
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:2012
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:1717
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.
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:1772
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:2192
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
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
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:1596
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:305
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:264
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:2146
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.
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 const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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:1514
@ Keep
No function return thunk.
Definition CodeGen.h:229
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:285
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
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