LLVM 24.0.0git
SimplifyCFG.cpp
Go to the documentation of this file.
1//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Peephole optimize the CFG.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
31#include "llvm/Analysis/Loads.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/NoFolder.h"
59#include "llvm/IR/Operator.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
66#include "llvm/IR/ValueHandle.h"
70#include "llvm/Support/Debug.h"
80#include <algorithm>
81#include <cassert>
82#include <climits>
83#include <cstddef>
84#include <cstdint>
85#include <iterator>
86#include <map>
87#include <optional>
88#include <set>
89#include <tuple>
90#include <utility>
91#include <vector>
92
93using namespace llvm;
94using namespace PatternMatch;
95
96#define DEBUG_TYPE "simplifycfg"
97
98namespace llvm {
99
101 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
102
103 cl::desc(
104 "Temporary development switch used to gradually uplift SimplifyCFG "
105 "into preserving DomTree,"));
106
107// Chosen as 2 so as to be cheap, but still to have enough power to fold
108// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
109// To catch this, we need to fold a compare and a select, hence '2' being the
110// minimum reasonable default.
112 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
113 cl::desc(
114 "Control the amount of phi node folding to perform (default = 2)"));
115
117 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
118 cl::desc("Control the maximal total instruction cost that we are willing "
119 "to speculatively execute to fold a 2-entry PHI node into a "
120 "select (default = 4)"));
121
122static cl::opt<bool>
123 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
124 cl::desc("Hoist common instructions up to the parent block"));
125
127 "simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true),
128 cl::desc("Hoist loads if the target supports conditional faulting"));
129
131 "simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true),
132 cl::desc("Hoist stores if the target supports conditional faulting"));
133
135 "hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6),
136 cl::desc("Control the maximal conditional load/store that we are willing "
137 "to speculatively execute to eliminate conditional branch "
138 "(default = 6)"));
139
141 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
142 cl::init(20),
143 cl::desc("Allow reordering across at most this many "
144 "instructions when hoisting"));
145
146static cl::opt<bool>
147 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
148 cl::desc("Sink common instructions down to the end block"));
149
151 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
152 cl::desc("Hoist conditional stores if an unconditional store precedes"));
153
155 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
156 cl::desc("Hoist conditional stores even if an unconditional store does not "
157 "precede - hoist multiple conditional stores into a single "
158 "predicated store"));
159
161 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
162 cl::desc("When merging conditional stores, do so even if the resultant "
163 "basic blocks are unlikely to be if-converted as a result"));
164
166 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
167 cl::desc("Allow exactly one expensive instruction to be speculatively "
168 "executed"));
169
171 "max-speculation-depth", cl::Hidden, cl::init(10),
172 cl::desc("Limit maximum recursion depth when calculating costs of "
173 "speculatively executed instructions"));
174
175static cl::opt<int>
176 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
177 cl::init(10),
178 cl::desc("Max size of a block which is still considered "
179 "small enough to thread through"));
180
181// Two is chosen to allow one negation and a logical combine.
183 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
184 cl::init(2),
185 cl::desc("Maximum cost of combining conditions when "
186 "folding branches"));
187
189 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
190 cl::init(2),
191 cl::desc("Multiplier to apply to threshold when determining whether or not "
192 "to fold branch to common destination when vector operations are "
193 "present"));
194
196 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
197 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
198
200 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
201 cl::desc("Limit cases to analyze when converting a switch to select"));
202
204 "simplifycfg-max-loop-header-threading-search", cl::Hidden, cl::init(1024),
205 cl::desc("Limit number of blocks searched to prove that threading through "
206 "a loop header keeps the loop canonical"));
207
209 "max-jump-threading-live-blocks", cl::Hidden, cl::init(24),
210 cl::desc("Limit number of blocks a define in a threaded block is allowed "
211 "to be live in"));
212
214
215} // end namespace llvm
216
217STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
218STATISTIC(NumLinearMaps,
219 "Number of switch instructions turned into linear mapping");
220STATISTIC(NumLookupTables,
221 "Number of switch instructions turned into lookup tables");
223 NumLookupTablesHoles,
224 "Number of switch instructions turned into lookup tables (holes checked)");
225STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
226STATISTIC(NumFoldValueComparisonIntoPredecessors,
227 "Number of value comparisons folded into predecessor basic blocks");
228STATISTIC(NumFoldBranchToCommonDest,
229 "Number of branches folded into predecessor basic block");
231 NumHoistCommonCode,
232 "Number of common instruction 'blocks' hoisted up to the begin block");
233STATISTIC(NumHoistCommonInstrs,
234 "Number of common instructions hoisted up to the begin block");
235STATISTIC(NumSinkCommonCode,
236 "Number of common instruction 'blocks' sunk down to the end block");
237STATISTIC(NumSinkCommonInstrs,
238 "Number of common instructions sunk down to the end block");
239STATISTIC(NumSpeculations, "Number of speculative executed instructions");
240STATISTIC(NumInvokes,
241 "Number of invokes with empty resume blocks simplified into calls");
242STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
243STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
244
245namespace {
246
247// The first field contains the value that the switch produces when a certain
248// case group is selected, and the second field is a vector containing the
249// cases composing the case group.
250using SwitchCaseResultVectorTy =
252
253// The first field contains the phi node that generates a result of the switch
254// and the second field contains the value generated for a certain case in the
255// switch for that PHI.
256using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
257
258/// Represents a case of a switch.
259struct ValueEqualityComparisonCase {
261 BasicBlock *Dest;
262
263 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
264 : Value(Value), Dest(Dest) {}
265
266 bool operator<(ValueEqualityComparisonCase RHS) const {
267 // Comparing pointers is ok as we only rely on the order for uniquing.
268 return Value < RHS.Value;
269 }
270
271 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
272};
273
274class SimplifyCFGOpt {
275 const TargetTransformInfo &TTI;
276 DomTreeUpdater *DTU;
277 const DataLayout &DL;
278 ArrayRef<WeakVH> LoopHeaders;
279 const SimplifyCFGOptions &Options;
280 bool Resimplify;
281
282 Value *isValueEqualityComparison(Instruction *TI);
283 BasicBlock *getValueEqualityComparisonCases(
284 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
285 bool simplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
286 BasicBlock *Pred,
287 IRBuilder<> &Builder);
288 bool performValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
289 Instruction *PTI,
290 IRBuilder<> &Builder);
291 bool foldValueComparisonIntoPredecessors(Instruction *TI,
292 IRBuilder<> &Builder);
293
294 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
295 bool simplifySingleResume(ResumeInst *RI);
296 bool simplifyCommonResume(ResumeInst *RI);
297 bool simplifyCleanupReturn(CleanupReturnInst *RI);
298 bool simplifyUnreachable(UnreachableInst *UI);
299 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
300 bool simplifyDuplicateSwitchArms(SwitchInst *SI, DomTreeUpdater *DTU);
301 bool simplifyIndirectBr(IndirectBrInst *IBI);
302 bool simplifyUncondBranch(UncondBrInst *BI, IRBuilder<> &Builder);
303 bool simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder);
304 bool foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI);
305
306 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
307 IRBuilder<> &Builder);
308 bool tryToSimplifyUncondBranchWithICmpSelectInIt(ICmpInst *ICI,
309 SelectInst *Select,
310 IRBuilder<> &Builder);
311 bool hoistCommonCodeFromSuccessors(Instruction *TI, bool AllInstsEqOnly);
312 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
313 Instruction *TI, Instruction *I1,
314 SmallVectorImpl<Instruction *> &OtherSuccTIs,
315 ArrayRef<BasicBlock *> UniqueSuccessors);
316 bool speculativelyExecuteBB(CondBrInst *BI, BasicBlock *ThenBB);
317 bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
318 BasicBlock *TrueBB, BasicBlock *FalseBB,
319 uint32_t TrueWeight, uint32_t FalseWeight);
320 bool simplifyBranchOnICmpChain(CondBrInst *BI, IRBuilder<> &Builder,
321 const DataLayout &DL);
322 bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
323 bool simplifySwitchOnSelectRemap(SwitchInst *SI, SelectInst *Select, Value *X,
324 ConstantInt *C, bool Negate);
325 bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
326 bool turnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
327 bool simplifyDuplicatePredecessors(BasicBlock *Succ, DomTreeUpdater *DTU);
328
329public:
330 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
331 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
332 const SimplifyCFGOptions &Opts)
333 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
334 assert((!DTU || !DTU->hasPostDomTree()) &&
335 "SimplifyCFG is not yet capable of maintaining validity of a "
336 "PostDomTree, so don't ask for it.");
337 }
338
339 bool simplifyOnce(BasicBlock *BB);
340 bool run(BasicBlock *BB);
341
342 // Helper to set Resimplify and return change indication.
343 bool requestResimplify() {
344 Resimplify = true;
345 return true;
346 }
347};
348
349// we synthesize a || b as select a, true, b
350// we synthesize a && b as select a, b, false
351// this function determines if SI is playing one of those roles.
352[[maybe_unused]] bool
353isSelectInRoleOfConjunctionOrDisjunction(const SelectInst *SI) {
354 return ((isa<ConstantInt>(SI->getTrueValue()) &&
355 (dyn_cast<ConstantInt>(SI->getTrueValue())->isOne())) ||
356 (isa<ConstantInt>(SI->getFalseValue()) &&
357 (dyn_cast<ConstantInt>(SI->getFalseValue())->isNullValue())));
358}
359
360} // end anonymous namespace
361
362/// Return true if all the PHI nodes in the basic block \p BB
363/// receive compatible (identical) incoming values when coming from
364/// all of the predecessor blocks that are specified in \p IncomingBlocks.
365///
366/// Note that if the values aren't exactly identical, but \p EquivalenceSet
367/// is provided, and *both* of the values are present in the set,
368/// then they are considered equal.
370 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
371 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
372 assert(IncomingBlocks.size() == 2 &&
373 "Only for a pair of incoming blocks at the time!");
374
375 // FIXME: it is okay if one of the incoming values is an `undef` value,
376 // iff the other incoming value is guaranteed to be a non-poison value.
377 // FIXME: it is okay if one of the incoming values is a `poison` value.
378 return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
379 Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
380 Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
381 if (IV0 == IV1)
382 return true;
383 if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
384 EquivalenceSet->contains(IV1))
385 return true;
386 return false;
387 });
388}
389
390/// Return true if it is safe to merge these two
391/// terminator instructions together.
392static bool
394 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
395 if (SI1 == SI2)
396 return false; // Can't merge with self!
397
398 // It is not safe to merge these two switch instructions if they have a common
399 // successor, and if that successor has a PHI node, and if *that* PHI node has
400 // conflicting incoming values from the two switch blocks.
401 BasicBlock *SI1BB = SI1->getParent();
402 BasicBlock *SI2BB = SI2->getParent();
403
405 bool Fail = false;
406 for (BasicBlock *Succ : successors(SI2BB)) {
407 if (!SI1Succs.count(Succ))
408 continue;
409 if (incomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
410 continue;
411 Fail = true;
412 if (FailBlocks)
413 FailBlocks->insert(Succ);
414 else
415 break;
416 }
417
418 return !Fail;
419}
420
421/// Update PHI nodes in Succ to indicate that there will now be entries in it
422/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
423/// will be the same as those coming in from ExistPred, an existing predecessor
424/// of Succ.
425static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
426 BasicBlock *ExistPred,
427 MemorySSAUpdater *MSSAU = nullptr) {
428 for (PHINode &PN : Succ->phis())
429 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
430 if (MSSAU)
431 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
432 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
433}
434
435/// Compute an abstract "cost" of speculating the given instruction,
436/// which is assumed to be safe to speculate. TCC_Free means cheap,
437/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
438/// expensive.
440 const TargetTransformInfo &TTI) {
441 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
442}
443
444/// If we have a merge point of an "if condition" as accepted above,
445/// return true if the specified value dominates the block. We don't handle
446/// the true generality of domination here, just a special case which works
447/// well enough for us.
448///
449/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
450/// see if V (which must be an instruction) and its recursive operands
451/// that do not dominate BB have a combined cost lower than Budget and
452/// are non-trapping. If both are true, the instruction is inserted into the
453/// set and true is returned.
454///
455/// The cost for most non-trapping instructions is defined as 1 except for
456/// Select whose cost is 2.
457///
458/// After this function returns, Cost is increased by the cost of
459/// V plus its non-dominating operands. If that cost is greater than
460/// Budget, false is returned and Cost is undefined.
462 Value *V, BasicBlock *BB, Instruction *InsertPt,
463 SmallPtrSetImpl<Instruction *> &AggressiveInsts, InstructionCost &Cost,
465 SmallPtrSetImpl<Instruction *> &ZeroCostInstructions, unsigned Depth = 0) {
466 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
467 // so limit the recursion depth.
468 // TODO: While this recursion limit does prevent pathological behavior, it
469 // would be better to track visited instructions to avoid cycles.
471 return false;
472
474 if (!I) {
475 // Non-instructions dominate all instructions and can be executed
476 // unconditionally.
477 return true;
478 }
479 BasicBlock *PBB = I->getParent();
480
481 // We don't want to allow weird loops that might have the "if condition" in
482 // the bottom of this block.
483 if (PBB == BB)
484 return false;
485
486 // If this instruction is defined in a block that contains an unconditional
487 // branch to BB, then it must be in the 'conditional' part of the "if
488 // statement". If not, it definitely dominates the region.
490 if (!BI || BI->getSuccessor() != BB)
491 return true;
492
493 // If we have seen this instruction before, don't count it again.
494 if (AggressiveInsts.count(I))
495 return true;
496
497 // Okay, it looks like the instruction IS in the "condition". Check to
498 // see if it's a cheap instruction to unconditionally compute, and if it
499 // only uses stuff defined outside of the condition. If so, hoist it out.
500 if (!isSafeToSpeculativelyExecute(I, InsertPt, AC))
501 return false;
502
503 // Overflow arithmetic instruction plus extract value are usually generated
504 // when a division is being replaced. But, in this case, the zero check may
505 // still be kept in the code. In that case it would be worth to hoist these
506 // two instruction out of the basic block. Let's treat this pattern as one
507 // single cheap instruction here!
508 WithOverflowInst *OverflowInst;
509 if (match(I, m_ExtractValue<1>(m_OneUse(m_WithOverflowInst(OverflowInst))))) {
510 ZeroCostInstructions.insert(OverflowInst);
511 Cost += 1;
512 } else if (!ZeroCostInstructions.contains(I))
513 Cost += computeSpeculationCost(I, TTI);
514
515 // Allow exactly one instruction to be speculated regardless of its cost
516 // (as long as it is safe to do so).
517 // This is intended to flatten the CFG even if the instruction is a division
518 // or other expensive operation. The speculation of an expensive instruction
519 // is expected to be undone in CodeGenPrepare if the speculation has not
520 // enabled further IR optimizations.
521 if (Cost > Budget &&
522 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
523 !Cost.isValid()))
524 return false;
525
526 // Okay, we can only really hoist these out if their operands do
527 // not take us over the cost threshold.
528 for (Use &Op : I->operands())
529 if (!dominatesMergePoint(Op, BB, InsertPt, AggressiveInsts, Cost, Budget,
530 TTI, AC, ZeroCostInstructions, Depth + 1))
531 return false;
532 // Okay, it's safe to do this! Remember this instruction.
533 AggressiveInsts.insert(I);
534 return true;
535}
536
537/// Extract ConstantInt from value, looking through IntToPtr
538/// and PointerNullValue. Return NULL if value is not a constant int.
540 // Normal constant int.
542 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
543 return CI;
544
545 // It is not safe to look through inttoptr or ptrtoint when using unstable
546 // pointer types.
547 if (DL.hasUnstableRepresentation(V->getType()))
548 return nullptr;
549
550 // This is some kind of pointer constant. Turn it into a pointer-sized
551 // ConstantInt if possible.
552 IntegerType *IntPtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
553
554 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
556 return ConstantInt::get(IntPtrTy, 0);
557
558 // IntToPtr const int, we can look through this if the semantics of
559 // inttoptr for this address space are a simple (truncating) bitcast.
561 if (CE->getOpcode() == Instruction::IntToPtr)
562 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
563 // The constant is very likely to have the right type already.
564 if (CI->getType() == IntPtrTy)
565 return CI;
566 else
567 return cast<ConstantInt>(
568 ConstantFoldIntegerCast(CI, IntPtrTy, /*isSigned=*/false, DL));
569 }
570 return nullptr;
571}
572
573namespace {
574
575/// Given a chain of or (||) or and (&&) comparison of a value against a
576/// constant, this will try to recover the information required for a switch
577/// structure.
578/// It will depth-first traverse the chain of comparison, seeking for patterns
579/// like %a == 12 or %a < 4 and combine them to produce a set of integer
580/// representing the different cases for the switch.
581/// Note that if the chain is composed of '||' it will build the set of elements
582/// that matches the comparisons (i.e. any of this value validate the chain)
583/// while for a chain of '&&' it will build the set elements that make the test
584/// fail.
585struct ConstantComparesGatherer {
586 const DataLayout &DL;
587
588 /// Value found for the switch comparison
589 Value *CompValue = nullptr;
590
591 /// Extra clause to be checked before the switch
592 Value *Extra = nullptr;
593
594 /// Set of integers to match in switch
596
597 /// Number of comparisons matched in the and/or chain
598 unsigned UsedICmps = 0;
599
600 /// If the elements in Vals matches the comparisons
601 bool IsEq = false;
602
603 // Used to check if the first matched CompValue shall be the Extra check.
604 bool IgnoreFirstMatch = false;
605 bool MultipleMatches = false;
606
607 /// Construct and compute the result for the comparison instruction Cond
608 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
609 gather(Cond);
610 if (CompValue || !MultipleMatches)
611 return;
612 Extra = nullptr;
613 Vals.clear();
614 UsedICmps = 0;
615 IgnoreFirstMatch = true;
616 gather(Cond);
617 }
618
619 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
620 ConstantComparesGatherer &
621 operator=(const ConstantComparesGatherer &) = delete;
622
623private:
624 /// Try to set the current value used for the comparison, it succeeds only if
625 /// it wasn't set before or if the new value is the same as the old one
626 bool setValueOnce(Value *NewVal) {
627 if (IgnoreFirstMatch) {
628 IgnoreFirstMatch = false;
629 return false;
630 }
631 if (CompValue && CompValue != NewVal) {
632 MultipleMatches = true;
633 return false;
634 }
635 CompValue = NewVal;
636 return true;
637 }
638
639 /// Try to match Instruction "I" as a comparison against a constant and
640 /// populates the array Vals with the set of values that match (or do not
641 /// match depending on isEQ).
642 /// Return false on failure. On success, the Value the comparison matched
643 /// against is placed in CompValue.
644 /// If CompValue is already set, the function is expected to fail if a match
645 /// is found but the value compared to is different.
646 bool matchInstruction(Instruction *I, bool isEQ) {
647 if (match(I, m_Not(m_Instruction(I))))
648 isEQ = !isEQ;
649
650 Value *Val;
651 if (match(I, m_NUWTrunc(m_Value(Val)))) {
652 // If we already have a value for the switch, it has to match!
653 if (!setValueOnce(Val))
654 return false;
655 UsedICmps++;
656 Vals.push_back(ConstantInt::get(cast<IntegerType>(Val->getType()), isEQ));
657 return true;
658 }
659 // If this is an icmp against a constant, handle this as one of the cases.
660 ICmpInst *ICI;
661 ConstantInt *C;
662 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
663 (C = getConstantInt(I->getOperand(1), DL)))) {
664 return false;
665 }
666
667 Value *RHSVal;
668 const APInt *RHSC;
669
670 // Pattern match a special case
671 // (x & ~2^z) == y --> x == y || x == y|2^z
672 // This undoes a transformation done by instcombine to fuse 2 compares.
673 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
674 // It's a little bit hard to see why the following transformations are
675 // correct. Here is a CVC3 program to verify them for 64-bit values:
676
677 /*
678 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
679 x : BITVECTOR(64);
680 y : BITVECTOR(64);
681 z : BITVECTOR(64);
682 mask : BITVECTOR(64) = BVSHL(ONE, z);
683 QUERY( (y & ~mask = y) =>
684 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
685 );
686 QUERY( (y | mask = y) =>
687 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
688 );
689 */
690
691 // Please note that each pattern must be a dual implication (<--> or
692 // iff). One directional implication can create spurious matches. If the
693 // implication is only one-way, an unsatisfiable condition on the left
694 // side can imply a satisfiable condition on the right side. Dual
695 // implication ensures that satisfiable conditions are transformed to
696 // other satisfiable conditions and unsatisfiable conditions are
697 // transformed to other unsatisfiable conditions.
698
699 // Here is a concrete example of a unsatisfiable condition on the left
700 // implying a satisfiable condition on the right:
701 //
702 // mask = (1 << z)
703 // (x & ~mask) == y --> (x == y || x == (y | mask))
704 //
705 // Substituting y = 3, z = 0 yields:
706 // (x & -2) == 3 --> (x == 3 || x == 2)
707
708 // Pattern match a special case:
709 /*
710 QUERY( (y & ~mask = y) =>
711 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
712 );
713 */
714 if (match(ICI->getOperand(0),
715 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
716 APInt Mask = ~*RHSC;
717 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
718 // If we already have a value for the switch, it has to match!
719 if (!setValueOnce(RHSVal))
720 return false;
721
722 Vals.push_back(C);
723 Vals.push_back(
724 ConstantInt::get(C->getContext(),
725 C->getValue() | Mask));
726 UsedICmps++;
727 return true;
728 }
729 }
730
731 // Pattern match a special case:
732 /*
733 QUERY( (y | mask = y) =>
734 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
735 );
736 */
737 if (match(ICI->getOperand(0),
738 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
739 APInt Mask = *RHSC;
740 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
741 // If we already have a value for the switch, it has to match!
742 if (!setValueOnce(RHSVal))
743 return false;
744
745 Vals.push_back(C);
746 Vals.push_back(ConstantInt::get(C->getContext(),
747 C->getValue() & ~Mask));
748 UsedICmps++;
749 return true;
750 }
751 }
752
753 // If we already have a value for the switch, it has to match!
754 if (!setValueOnce(ICI->getOperand(0)))
755 return false;
756
757 UsedICmps++;
758 Vals.push_back(C);
759 return true;
760 }
761
762 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
763 ConstantRange Span =
765
766 // Shift the range if the compare is fed by an add. This is the range
767 // compare idiom as emitted by instcombine.
768 Value *CandidateVal = I->getOperand(0);
769 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
770 Span = Span.subtract(*RHSC);
771 CandidateVal = RHSVal;
772 }
773
774 // If this is an and/!= check, then we are looking to build the set of
775 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
776 // x != 0 && x != 1.
777 if (!isEQ)
778 Span = Span.inverse();
779
780 // If there are a ton of values, we don't want to make a ginormous switch.
781 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
782 return false;
783 }
784
785 // If we already have a value for the switch, it has to match!
786 if (!setValueOnce(CandidateVal))
787 return false;
788
789 // Add all values from the range to the set
790 APInt Tmp = Span.getLower();
791 do
792 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
793 while (++Tmp != Span.getUpper());
794
795 UsedICmps++;
796 return true;
797 }
798
799 /// Given a potentially 'or'd or 'and'd together collection of icmp
800 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
801 /// the value being compared, and stick the list constants into the Vals
802 /// vector.
803 /// One "Extra" case is allowed to differ from the other.
804 void gather(Value *V) {
805 Value *Op0, *Op1;
806 if (match(V, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
807 IsEq = true;
808 else if (match(V, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
809 IsEq = false;
810 else
811 return;
812 // Keep a stack (SmallVector for efficiency) for depth-first traversal
813 SmallVector<Value *, 8> DFT{Op0, Op1};
814 SmallPtrSet<Value *, 8> Visited{V, Op0, Op1};
815
816 while (!DFT.empty()) {
817 V = DFT.pop_back_val();
818
819 if (Instruction *I = dyn_cast<Instruction>(V)) {
820 // If it is a || (or && depending on isEQ), process the operands.
821 if (IsEq ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
822 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
823 if (Visited.insert(Op1).second)
824 DFT.push_back(Op1);
825 if (Visited.insert(Op0).second)
826 DFT.push_back(Op0);
827
828 continue;
829 }
830
831 // Try to match the current instruction
832 if (matchInstruction(I, IsEq))
833 // Match succeed, continue the loop
834 continue;
835 }
836
837 // One element of the sequence of || (or &&) could not be match as a
838 // comparison against the same value as the others.
839 // We allow only one "Extra" case to be checked before the switch
840 if (!Extra) {
841 Extra = V;
842 continue;
843 }
844 // Failed to parse a proper sequence, abort now
845 CompValue = nullptr;
846 break;
847 }
848 }
849};
850
851} // end anonymous namespace
852
854 MemorySSAUpdater *MSSAU = nullptr) {
855 Instruction *Cond = nullptr;
857 Cond = dyn_cast<Instruction>(SI->getCondition());
858 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
859 Cond = dyn_cast<Instruction>(BI->getCondition());
860 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
861 Cond = dyn_cast<Instruction>(IBI->getAddress());
862 }
863
864 TI->eraseFromParent();
865 if (Cond)
867}
868
869/// If the terminator is an integer value check, return the value being checked.
870Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
871 Value *CV = nullptr;
872 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
873 CV = SI->getCondition();
874 else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI))
875 if (BI->getCondition()->hasOneUse()) {
876 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
877 if (ICI->isEquality() && getConstantInt(ICI->getOperand(1), DL))
878 CV = ICI->getOperand(0);
879 } else if (auto *Trunc = dyn_cast<TruncInst>(BI->getCondition())) {
880 if (Trunc->hasNoUnsignedWrap())
881 CV = Trunc->getOperand(0);
882 }
883 }
884
885 // Unwrap any lossless ptrtoint cast (except for unstable pointers).
886 if (CV) {
887 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
888 Value *Ptr = PTII->getPointerOperand();
889 if (DL.hasUnstableRepresentation(Ptr->getType()))
890 return CV;
891 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
892 CV = Ptr;
893 }
894 }
895 return CV;
896}
897
898/// Given a value comparison instruction,
899/// decode all of the 'cases' that it represents and return the 'default' block.
900BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
901 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
902 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
903 Cases.reserve(SI->getNumCases());
904 for (auto Case : SI->cases())
905 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
906 Case.getCaseSuccessor()));
907 return SI->getDefaultDest();
908 }
909
910 CondBrInst *BI = cast<CondBrInst>(TI);
911 Value *Cond = BI->getCondition();
912 ICmpInst::Predicate Pred;
913 ConstantInt *C;
914 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
915 Pred = ICI->getPredicate();
916 C = getConstantInt(ICI->getOperand(1), DL);
917 } else {
918 Pred = ICmpInst::ICMP_NE;
919 auto *Trunc = cast<TruncInst>(Cond);
920 C = ConstantInt::get(cast<IntegerType>(Trunc->getOperand(0)->getType()), 0);
921 }
922 BasicBlock *Succ = BI->getSuccessor(Pred == ICmpInst::ICMP_NE);
923 Cases.push_back(ValueEqualityComparisonCase(C, Succ));
924 return BI->getSuccessor(Pred == ICmpInst::ICMP_EQ);
925}
926
927/// Given a vector of bb/value pairs, remove any entries
928/// in the list that match the specified block.
929static void
931 std::vector<ValueEqualityComparisonCase> &Cases) {
932 llvm::erase(Cases, BB);
933}
934
935/// Return true if there are any keys in C1 that exist in C2 as well.
936static bool valuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
937 std::vector<ValueEqualityComparisonCase> &C2) {
938 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
939
940 // Make V1 be smaller than V2.
941 if (V1->size() > V2->size())
942 std::swap(V1, V2);
943
944 if (V1->empty())
945 return false;
946 if (V1->size() == 1) {
947 // Just scan V2.
948 ConstantInt *TheVal = (*V1)[0].Value;
949 for (const ValueEqualityComparisonCase &VECC : *V2)
950 if (TheVal == VECC.Value)
951 return true;
952 }
953
954 // Otherwise, just sort both lists and compare element by element.
955 array_pod_sort(V1->begin(), V1->end());
956 array_pod_sort(V2->begin(), V2->end());
957 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
958 while (i1 != e1 && i2 != e2) {
959 if ((*V1)[i1].Value == (*V2)[i2].Value)
960 return true;
961 if ((*V1)[i1].Value < (*V2)[i2].Value)
962 ++i1;
963 else
964 ++i2;
965 }
966 return false;
967}
968
969/// If TI is a terminator instruction and its block has a single predecessor,
970/// and that predecessor also compares the same value as TI, simplify the TI or
971/// its block based on the conditions that jump to TI's block:
972/// - Prune branches of TI based on the values handled in the predecessor.
973/// - If the predecessor jumps to TI's block on one value, or if TI is a
974/// conditional branch whose only case is ruled out by the predecessor,
975/// replace it with a jump to its only possible destination.
976bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
977 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
978 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
979 if (!PredVal)
980 return false; // Not a value comparison in predecessor.
981
982 Value *ThisVal = isValueEqualityComparison(TI);
983 assert(ThisVal && "This isn't a value comparison!!");
984 if (ThisVal != PredVal)
985 return false; // Different predicates.
986
987 // TODO: Preserve branch weight metadata, similarly to how
988 // foldValueComparisonIntoPredecessors preserves it.
989
990 // Find out information about when control will move from Pred to TI's block.
991 std::vector<ValueEqualityComparisonCase> PredCases;
992 BasicBlock *PredDef =
993 getValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
994 // Remove cases that branch to the default target.
995 eliminateBlockCases(PredDef, PredCases);
996
997 // Find information about how control leaves this block.
998 std::vector<ValueEqualityComparisonCase> ThisCases;
999 BasicBlock *ThisDef = getValueEqualityComparisonCases(TI, ThisCases);
1000 // Remove cases that branch to the default target.
1001 eliminateBlockCases(ThisDef, ThisCases);
1002
1003 BasicBlock *TIBB = TI->getParent();
1004
1005 // If TI's block is the default block from Pred's comparison, prune branches
1006 // of TI based on the values handled in the Pred's comparison.
1007 if (PredDef == TIBB) {
1008 // If we are here, we know that the value is none of those cases listed in
1009 // PredCases. If there are any cases in ThisCases that are in PredCases, we
1010 // can simplify TI.
1011 if (!valuesOverlap(PredCases, ThisCases))
1012 return false;
1013
1014 if (isa<CondBrInst>(TI)) {
1015 // TI checks for one value, which is already checked in the predecessor.
1016 // So we know which branch will be taken, convert it to an unconditional
1017 // br.
1018 assert(ThisCases.size() == 1 && "Branch can only have one case!");
1019 // Insert the new branch.
1020 Instruction *NI = Builder.CreateBr(ThisDef);
1021 (void)NI;
1022
1023 // Remove PHI node entries for the dead edge.
1024 ThisCases[0].Dest->removePredecessor(TIBB);
1025
1026 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1027 << "Through successor TI: " << *TI << "Leaving: " << *NI
1028 << "\n");
1029
1031
1032 if (DTU)
1033 DTU->applyUpdates({{DominatorTree::Delete, TIBB, ThisCases[0].Dest}});
1034
1035 return true;
1036 }
1037
1038 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
1039 // Okay, TI has cases that are statically dead, prune them away.
1040 SmallPtrSet<Constant *, 16> DeadCases;
1041 for (const ValueEqualityComparisonCase &Case : PredCases)
1042 DeadCases.insert(Case.Value);
1043
1044 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1045 << "Through successor TI: " << *TI);
1046
1047 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
1048 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
1049 --i;
1050 auto *Successor = i->getCaseSuccessor();
1051 if (DTU)
1052 ++NumPerSuccessorCases[Successor];
1053 if (DeadCases.count(i->getCaseValue())) {
1054 Successor->removePredecessor(PredDef);
1055 SI.removeCase(i);
1056 if (DTU)
1057 --NumPerSuccessorCases[Successor];
1058 }
1059 }
1060
1061 if (DTU) {
1062 std::vector<DominatorTree::UpdateType> Updates;
1063 for (const auto &I : NumPerSuccessorCases)
1064 if (I.second == 0)
1065 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
1066 DTU->applyUpdates(Updates);
1067 }
1068
1069 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
1070 return true;
1071 }
1072
1073 // Otherwise, TI's block must correspond to some matched value. Find out
1074 // which value (or set of values) this is.
1075 ConstantInt *TIV = nullptr;
1076 for (const auto &[Value, Dest] : PredCases)
1077 if (Dest == TIBB) {
1078 if (TIV)
1079 return false; // Cannot handle multiple values coming to this block.
1080 TIV = Value;
1081 }
1082 assert(TIV && "No edge from pred to succ?");
1083
1084 // Find out which successor will unconditionally be branched to.
1085 BasicBlock *TheRealDest = nullptr;
1086 for (const auto &[Value, Dest] : ThisCases)
1087 if (Value == TIV) {
1088 TheRealDest = Dest;
1089 break;
1090 }
1091
1092 // If not handled by any explicit cases, it is handled by the default case.
1093 if (!TheRealDest)
1094 TheRealDest = ThisDef;
1095
1096 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1097
1098 // Remove PHI node entries for dead edges.
1099 BasicBlock *CheckEdge = TheRealDest;
1100 for (BasicBlock *Succ : successors(TIBB))
1101 if (Succ != CheckEdge) {
1102 if (Succ != TheRealDest)
1103 RemovedSuccs.insert(Succ);
1104 Succ->removePredecessor(TIBB);
1105 } else
1106 CheckEdge = nullptr;
1107
1108 // Insert the new branch.
1109 Instruction *NI = Builder.CreateBr(TheRealDest);
1110 (void)NI;
1111
1112 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1113 << "Through successor TI: " << *TI << "Leaving: " << *NI
1114 << "\n");
1115
1117 if (DTU) {
1118 SmallVector<DominatorTree::UpdateType, 2> Updates;
1119 Updates.reserve(RemovedSuccs.size());
1120 for (auto *RemovedSucc : RemovedSuccs)
1121 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1122 DTU->applyUpdates(Updates);
1123 }
1124 return true;
1125}
1126
1127namespace {
1128
1129/// This class implements a stable ordering of constant
1130/// integers that does not depend on their address. This is important for
1131/// applications that sort ConstantInt's to ensure uniqueness.
1132struct ConstantIntOrdering {
1133 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1134 return LHS->getValue().ult(RHS->getValue());
1135 }
1136};
1137
1138} // end anonymous namespace
1139
1141 ConstantInt *const *P2) {
1142 const ConstantInt *LHS = *P1;
1143 const ConstantInt *RHS = *P2;
1144 if (LHS == RHS)
1145 return 0;
1146 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1147}
1148
1149/// Get Weights of a given terminator, the default weight is at the front
1150/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1151/// metadata.
1153 SmallVectorImpl<uint64_t> &Weights) {
1154 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1155 assert(MD && "Invalid branch-weight metadata");
1156 extractFromBranchWeightMD64(MD, Weights);
1157
1158 // If TI is a conditional eq, the default case is the false case,
1159 // and the corresponding branch-weight data is at index 2. We swap the
1160 // default weight to be the first entry.
1161 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
1162 assert(Weights.size() == 2);
1163 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
1164 if (!ICI)
1165 return;
1166
1167 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1168 std::swap(Weights.front(), Weights.back());
1169 }
1170}
1171
1173 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1174 Instruction *PTI = PredBlock->getTerminator();
1175
1176 // If we have bonus instructions, clone them into the predecessor block.
1177 // Note that there may be multiple predecessor blocks, so we cannot move
1178 // bonus instructions to a predecessor block.
1179 for (Instruction &BonusInst : *BB) {
1180 if (BonusInst.isTerminator())
1181 continue;
1182
1183 // Skip cloning pseudo probes into the predecessor, as it would overcount
1184 // otherwise.
1185 if (isa<PseudoProbeInst>(BonusInst))
1186 continue;
1187
1188 Instruction *NewBonusInst = BonusInst.clone();
1189 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1190
1191 if (!NewBonusInst->getDebugLoc().isSameSourceLocation(PTI->getDebugLoc())) {
1192 // Unless the instruction has the same !dbg location as the original
1193 // branch, drop it. When we fold the bonus instructions we want to make
1194 // sure we reset their debug locations in order to avoid stepping on
1195 // dead code caused by folding dead branches.
1196 NewBonusInst->dropLocation();
1197 } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
1198 mapAtomInstance(DL, VMap);
1199 }
1200
1201 RemapInstruction(NewBonusInst, VMap,
1203
1204 // If we speculated an instruction, we need to drop any metadata that may
1205 // result in undefined behavior, as the metadata might have been valid
1206 // only given the branch precondition.
1207 // Similarly strip attributes on call parameters that may cause UB in
1208 // location the call is moved to.
1209 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1210
1211 auto Range = NewBonusInst->cloneDebugInfoFrom(&BonusInst);
1212 RemapDbgRecordRange(NewBonusInst->getModule(), Range, VMap,
1214
1215 NewBonusInst->takeName(&BonusInst);
1216 BonusInst.setName(NewBonusInst->getName() + ".old");
1217 VMap[&BonusInst] = NewBonusInst;
1218
1219 // Update (liveout) uses of bonus instructions,
1220 // now that the bonus instruction has been cloned into predecessor.
1221 // Note that we expect to be in a block-closed SSA form for this to work!
1222 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1223 auto *UI = cast<Instruction>(U.getUser());
1224 auto *PN = dyn_cast<PHINode>(UI);
1225 if (!PN) {
1226 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1227 "If the user is not a PHI node, then it should be in the same "
1228 "block as, and come after, the original bonus instruction.");
1229 continue; // Keep using the original bonus instruction.
1230 }
1231 // Is this the block-closed SSA form PHI node?
1232 if (PN->getIncomingBlock(U) == BB)
1233 continue; // Great, keep using the original bonus instruction.
1234 // The only other alternative is an "use" when coming from
1235 // the predecessor block - here we should refer to the cloned bonus instr.
1236 assert(PN->getIncomingBlock(U) == PredBlock &&
1237 "Not in block-closed SSA form?");
1238 U.set(NewBonusInst);
1239 }
1240 }
1241
1242 // Key Instructions: We may have propagated atom info into the pred. If the
1243 // pred's terminator already has atom info do nothing as merging would drop
1244 // one atom group anyway. If it doesn't, propagte the remapped atom group
1245 // from BB's terminator.
1246 if (auto &PredDL = PTI->getDebugLoc()) {
1247 auto &DL = BB->getTerminator()->getDebugLoc();
1248 if (!PredDL->getAtomGroup() && DL && DL->getAtomGroup() &&
1249 PredDL.isSameSourceLocation(DL)) {
1250 PTI->setDebugLoc(DL);
1251 RemapSourceAtom(PTI, VMap);
1252 }
1253 }
1254}
1255
1256bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
1257 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1258 BasicBlock *BB = TI->getParent();
1259 BasicBlock *Pred = PTI->getParent();
1260
1262
1263 // Figure out which 'cases' to copy from SI to PSI.
1264 std::vector<ValueEqualityComparisonCase> BBCases;
1265 BasicBlock *BBDefault = getValueEqualityComparisonCases(TI, BBCases);
1266
1267 std::vector<ValueEqualityComparisonCase> PredCases;
1268 BasicBlock *PredDefault = getValueEqualityComparisonCases(PTI, PredCases);
1269
1270 // Based on whether the default edge from PTI goes to BB or not, fill in
1271 // PredCases and PredDefault with the new switch cases we would like to
1272 // build.
1273 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1274
1275 // Update the branch weight metadata along the way
1276 SmallVector<uint64_t, 8> Weights;
1277 bool PredHasWeights = hasBranchWeightMD(*PTI);
1278 bool SuccHasWeights = hasBranchWeightMD(*TI);
1279
1280 if (PredHasWeights) {
1281 getBranchWeights(PTI, Weights);
1282 // branch-weight metadata is inconsistent here.
1283 if (Weights.size() != 1 + PredCases.size())
1284 PredHasWeights = SuccHasWeights = false;
1285 } else if (SuccHasWeights)
1286 // If there are no predecessor weights but there are successor weights,
1287 // populate Weights with 1, which will later be scaled to the sum of
1288 // successor's weights
1289 Weights.assign(1 + PredCases.size(), 1);
1290
1291 SmallVector<uint64_t, 8> SuccWeights;
1292 if (SuccHasWeights) {
1293 getBranchWeights(TI, SuccWeights);
1294 // branch-weight metadata is inconsistent here.
1295 if (SuccWeights.size() != 1 + BBCases.size())
1296 PredHasWeights = SuccHasWeights = false;
1297 } else if (PredHasWeights)
1298 SuccWeights.assign(1 + BBCases.size(), 1);
1299
1300 if (PredDefault == BB) {
1301 // If this is the default destination from PTI, only the edges in TI
1302 // that don't occur in PTI, or that branch to BB will be activated.
1303 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1304 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1305 if (PredCases[i].Dest != BB)
1306 PTIHandled.insert(PredCases[i].Value);
1307 else {
1308 // The default destination is BB, we don't need explicit targets.
1309 std::swap(PredCases[i], PredCases.back());
1310
1311 if (PredHasWeights || SuccHasWeights) {
1312 // Increase weight for the default case.
1313 Weights[0] += Weights[i + 1];
1314 std::swap(Weights[i + 1], Weights.back());
1315 Weights.pop_back();
1316 }
1317
1318 PredCases.pop_back();
1319 --i;
1320 --e;
1321 }
1322
1323 // Reconstruct the new switch statement we will be building.
1324 if (PredDefault != BBDefault) {
1325 PredDefault->removePredecessor(Pred);
1326 if (DTU && PredDefault != BB)
1327 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1328 PredDefault = BBDefault;
1329 ++NewSuccessors[BBDefault];
1330 }
1331
1332 unsigned CasesFromPred = Weights.size();
1333 uint64_t ValidTotalSuccWeight = 0;
1334 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1335 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1336 PredCases.push_back(BBCases[i]);
1337 ++NewSuccessors[BBCases[i].Dest];
1338 if (SuccHasWeights || PredHasWeights) {
1339 // The default weight is at index 0, so weight for the ith case
1340 // should be at index i+1. Scale the cases from successor by
1341 // PredDefaultWeight (Weights[0]).
1342 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1343 ValidTotalSuccWeight += SuccWeights[i + 1];
1344 }
1345 }
1346
1347 if (SuccHasWeights || PredHasWeights) {
1348 ValidTotalSuccWeight += SuccWeights[0];
1349 // Scale the cases from predecessor by ValidTotalSuccWeight.
1350 for (unsigned i = 1; i < CasesFromPred; ++i)
1351 Weights[i] *= ValidTotalSuccWeight;
1352 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1353 Weights[0] *= SuccWeights[0];
1354 }
1355 } else {
1356 // If this is not the default destination from PSI, only the edges
1357 // in SI that occur in PSI with a destination of BB will be
1358 // activated.
1359 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1360 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1361 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1362 if (PredCases[i].Dest == BB) {
1363 PTIHandled.insert(PredCases[i].Value);
1364
1365 if (PredHasWeights || SuccHasWeights) {
1366 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1367 std::swap(Weights[i + 1], Weights.back());
1368 Weights.pop_back();
1369 }
1370
1371 std::swap(PredCases[i], PredCases.back());
1372 PredCases.pop_back();
1373 --i;
1374 --e;
1375 }
1376
1377 // Okay, now we know which constants were sent to BB from the
1378 // predecessor. Figure out where they will all go now.
1379 for (const ValueEqualityComparisonCase &Case : BBCases)
1380 if (PTIHandled.count(Case.Value)) {
1381 // If this is one we are capable of getting...
1382 if (PredHasWeights || SuccHasWeights)
1383 Weights.push_back(WeightsForHandled[Case.Value]);
1384 PredCases.push_back(Case);
1385 ++NewSuccessors[Case.Dest];
1386 PTIHandled.erase(Case.Value); // This constant is taken care of
1387 }
1388
1389 // If there are any constants vectored to BB that TI doesn't handle,
1390 // they must go to the default destination of TI.
1391 for (ConstantInt *I : PTIHandled) {
1392 if (PredHasWeights || SuccHasWeights)
1393 Weights.push_back(WeightsForHandled[I]);
1394 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1395 ++NewSuccessors[BBDefault];
1396 }
1397 }
1398
1399 // Okay, at this point, we know which new successor Pred will get. Make
1400 // sure we update the number of entries in the PHI nodes for these
1401 // successors.
1402 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1403 if (DTU) {
1404 SuccsOfPred = {llvm::from_range, successors(Pred)};
1405 Updates.reserve(Updates.size() + NewSuccessors.size());
1406 }
1407 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1408 NewSuccessors) {
1409 for (auto I : seq(NewSuccessor.second)) {
1410 (void)I;
1411 addPredecessorToBlock(NewSuccessor.first, Pred, BB);
1412 }
1413 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1414 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1415 }
1416
1417 Builder.SetInsertPoint(PTI);
1418 // Convert pointer to int before we switch.
1419 if (CV->getType()->isPointerTy()) {
1420 assert(!DL.hasUnstableRepresentation(CV->getType()) &&
1421 "Should not end up here with unstable pointers");
1422 CV =
1423 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1424 }
1425
1426 // Now that the successors are updated, create the new Switch instruction.
1427 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1428 NewSI->setDebugLoc(PTI->getDebugLoc());
1429 for (ValueEqualityComparisonCase &V : PredCases)
1430 NewSI->addCase(V.Value, V.Dest);
1431
1432 if (PredHasWeights || SuccHasWeights)
1433 setFittedBranchWeights(*NewSI, Weights, /*IsExpected=*/false,
1434 /*ElideAllZero=*/true);
1435 else
1437
1438 // The new switch is only known to be unpredictable if both of the comparisons
1439 // it was built from were unpredictable.
1440 if (MDNode *Unpredictable = PTI->getMetadata(LLVMContext::MD_unpredictable))
1441 if (TI->hasMetadata(LLVMContext::MD_unpredictable))
1442 NewSI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
1443
1445
1446 // Okay, last check. If BB is still a successor of PSI, then we must
1447 // have an infinite loop case. If so, add an infinitely looping block
1448 // to handle the case to preserve the behavior of the code.
1449 BasicBlock *InfLoopBlock = nullptr;
1450 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1451 if (NewSI->getSuccessor(i) == BB) {
1452 if (!InfLoopBlock) {
1453 // Insert it at the end of the function, because it's either code,
1454 // or it won't matter if it's hot. :)
1455 InfLoopBlock =
1456 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1457 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
1458 if (DTU)
1459 Updates.push_back(
1460 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1461 }
1462 NewSI->setSuccessor(i, InfLoopBlock);
1463 }
1464
1465 if (DTU) {
1466 if (InfLoopBlock)
1467 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1468
1469 Updates.push_back({DominatorTree::Delete, Pred, BB});
1470
1471 DTU->applyUpdates(Updates);
1472 }
1473
1474 ++NumFoldValueComparisonIntoPredecessors;
1475 return true;
1476}
1477
1478/// The specified terminator is a value equality comparison instruction
1479/// (either a switch or a branch on "X == c").
1480/// See if any of the predecessors of the terminator block are value comparisons
1481/// on the same value. If so, and if safe to do so, fold them together.
1482bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1483 IRBuilder<> &Builder) {
1484 BasicBlock *BB = TI->getParent();
1485 Value *CV = isValueEqualityComparison(TI); // CondVal
1486 assert(CV && "Not a comparison?");
1487
1488 // Limit `incoming_edges * outgoing_edges < 128` to avoid code size explosion
1489 // when we duplicate branches in multiple predecessors.
1490 if (!BB->getSinglePredecessor() &&
1492 return false;
1493
1494 bool Changed = false;
1495
1496 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1497 while (!Preds.empty()) {
1498 BasicBlock *Pred = Preds.pop_back_val();
1499 Instruction *PTI = Pred->getTerminator();
1500
1501 // Don't try to fold into itself.
1502 if (Pred == BB)
1503 continue;
1504
1505 // See if the predecessor is a comparison with the same value.
1506 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1507 if (PCV != CV)
1508 continue;
1509
1510 SmallSetVector<BasicBlock *, 4> FailBlocks;
1511 if (!safeToMergeTerminators(TI, PTI, &FailBlocks)) {
1512 for (auto *Succ : FailBlocks) {
1513 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1514 return false;
1515 }
1516 }
1517
1518 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1519 Changed = true;
1520 }
1521 return Changed;
1522}
1523
1524// If we would need to insert a select that uses the value of this invoke
1525// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1526// need to do this), we can't hoist the invoke, as there is nowhere to put the
1527// select in this case.
1529 Instruction *I1, Instruction *I2) {
1530 for (BasicBlock *Succ : successors(BB1)) {
1531 for (const PHINode &PN : Succ->phis()) {
1532 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1533 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1534 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1535 return false;
1536 }
1537 }
1538 }
1539 return true;
1540}
1541
1542// Get interesting characteristics of instructions that
1543// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1544// instructions can be reordered across.
1550
1552 // Pseudo probes don't constrain reordering of other instructions.
1554 return 0;
1555 unsigned Flags = 0;
1556 if (I->mayReadFromMemory())
1557 Flags |= SkipReadMem;
1558 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1559 // inalloca) across stacksave/stackrestore boundaries.
1560 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1561 Flags |= SkipSideEffect;
1563 Flags |= SkipImplicitControlFlow;
1564 return Flags;
1565}
1566
1567// Returns true if it is safe to reorder an instruction across preceding
1568// instructions in a basic block.
1569static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1570 // Don't reorder a store over a load.
1571 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1572 return false;
1573
1574 // If we have seen an instruction with side effects, it's unsafe to reorder an
1575 // instruction which reads memory or itself has side effects.
1576 if ((Flags & SkipSideEffect) &&
1577 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1578 return false;
1579
1580 // Reordering across an instruction which does not necessarily transfer
1581 // control to the next instruction is speculation.
1583 return false;
1584
1585 // Hoisting of llvm.deoptimize is only legal together with the next return
1586 // instruction, which this pass is not always able to do.
1587 if (auto *CB = dyn_cast<CallBase>(I))
1588 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1589 return false;
1590
1591 // It's also unsafe/illegal to hoist an instruction above its instruction
1592 // operands
1593 BasicBlock *BB = I->getParent();
1594 for (Value *Op : I->operands()) {
1595 if (auto *J = dyn_cast<Instruction>(Op))
1596 if (J->getParent() == BB)
1597 return false;
1598 }
1599
1600 return true;
1601}
1602
1603static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1604
1605/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1606/// instructions \p I1 and \p I2 can and should be hoisted.
1608 const TargetTransformInfo &TTI) {
1609 // If we're going to hoist a call, make sure that the two instructions
1610 // we're commoning/hoisting are both marked with musttail, or neither of
1611 // them is marked as such. Otherwise, we might end up in a situation where
1612 // we hoist from a block where the terminator is a `ret` to a block where
1613 // the terminator is a `br`, and `musttail` calls expect to be followed by
1614 // a return.
1615 auto *C1 = dyn_cast<CallInst>(I1);
1616 auto *C2 = dyn_cast<CallInst>(I2);
1617 if (C1 && C2)
1618 if (C1->isMustTailCall() != C2->isMustTailCall())
1619 return false;
1620
1621 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1622 return false;
1623
1624 // If any of the two call sites has nomerge or convergent attribute, stop
1625 // hoisting.
1626 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1627 if (CB1->cannotMerge() || CB1->isConvergent())
1628 return false;
1629 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1630 if (CB2->cannotMerge() || CB2->isConvergent())
1631 return false;
1632
1633 return true;
1634}
1635
1636/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1637/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1638/// hoistCommonCodeFromSuccessors. e.g. The input:
1639/// I1 DVRs: { x, z },
1640/// OtherInsts: { I2 DVRs: { x, y, z } }
1641/// would result in hoisting only DbgVariableRecord x.
1643 Instruction *TI, Instruction *I1,
1644 SmallVectorImpl<Instruction *> &OtherInsts) {
1645 if (!I1->hasDbgRecords())
1646 return;
1647 using CurrentAndEndIt =
1648 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1649 // Vector of {Current, End} iterators.
1651 Itrs.reserve(OtherInsts.size() + 1);
1652 // Helper lambdas for lock-step checks:
1653 // Return true if this Current == End.
1654 auto atEnd = [](const CurrentAndEndIt &Pair) {
1655 return Pair.first == Pair.second;
1656 };
1657 // Return true if all Current are identical.
1658 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1659 return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
1661 return Itrs[0].first->isIdenticalToWhenDefined(*I);
1662 });
1663 };
1664
1665 // Collect the iterators.
1666 Itrs.push_back(
1667 {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1668 for (Instruction *Other : OtherInsts) {
1669 if (!Other->hasDbgRecords())
1670 return;
1671 Itrs.push_back(
1672 {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1673 }
1674
1675 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1676 // the lock-step DbgRecord are identical, hoist all of them to TI.
1677 // This replicates the dbg.* intrinsic behaviour in
1678 // hoistCommonCodeFromSuccessors.
1679 while (none_of(Itrs, atEnd)) {
1680 bool HoistDVRs = allIdentical(Itrs);
1681 for (CurrentAndEndIt &Pair : Itrs) {
1682 // Increment Current iterator now as we may be about to move the
1683 // DbgRecord.
1684 DbgRecord &DR = *Pair.first++;
1685 if (HoistDVRs) {
1686 DR.removeFromParent();
1687 TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
1688 }
1689 }
1690 }
1691}
1692
1694 const Instruction *I2) {
1695 if (I1->isIdenticalToWhenDefined(I2, /*IntersectAttrs=*/true))
1696 return true;
1697
1698 if (auto *Cmp1 = dyn_cast<CmpInst>(I1))
1699 if (auto *Cmp2 = dyn_cast<CmpInst>(I2))
1700 return Cmp1->getPredicate() == Cmp2->getSwappedPredicate() &&
1701 Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
1702 Cmp1->getOperand(1) == Cmp2->getOperand(0);
1703
1704 if (I1->isCommutative() && I1->isSameOperationAs(I2)) {
1705 return I1->getOperand(0) == I2->getOperand(1) &&
1706 I1->getOperand(1) == I2->getOperand(0) &&
1707 equal(drop_begin(I1->operands(), 2), drop_begin(I2->operands(), 2));
1708 }
1709
1710 return false;
1711}
1712
1713/// If the target supports conditional faulting,
1714/// we look for the following pattern:
1715/// \code
1716/// BB:
1717/// ...
1718/// %cond = icmp ult %x, %y
1719/// br i1 %cond, label %TrueBB, label %FalseBB
1720/// FalseBB:
1721/// store i32 1, ptr %q, align 4
1722/// ...
1723/// TrueBB:
1724/// %maskedloadstore = load i32, ptr %b, align 4
1725/// store i32 %maskedloadstore, ptr %p, align 4
1726/// ...
1727/// \endcode
1728///
1729/// and transform it into:
1730///
1731/// \code
1732/// BB:
1733/// ...
1734/// %cond = icmp ult %x, %y
1735/// %maskedloadstore = cload i32, ptr %b, %cond
1736/// cstore i32 %maskedloadstore, ptr %p, %cond
1737/// cstore i32 1, ptr %q, ~%cond
1738/// br i1 %cond, label %TrueBB, label %FalseBB
1739/// FalseBB:
1740/// ...
1741/// TrueBB:
1742/// ...
1743/// \endcode
1744///
1745/// where cload/cstore are represented by llvm.masked.load/store intrinsics,
1746/// e.g.
1747///
1748/// \code
1749/// %vcond = bitcast i1 %cond to <1 x i1>
1750/// %v0 = call <1 x i32> @llvm.masked.load.v1i32.p0
1751/// (ptr %b, i32 4, <1 x i1> %vcond, <1 x i32> poison)
1752/// %maskedloadstore = bitcast <1 x i32> %v0 to i32
1753/// call void @llvm.masked.store.v1i32.p0
1754/// (<1 x i32> %v0, ptr %p, i32 4, <1 x i1> %vcond)
1755/// %cond.not = xor i1 %cond, true
1756/// %vcond.not = bitcast i1 %cond.not to <1 x i>
1757/// call void @llvm.masked.store.v1i32.p0
1758/// (<1 x i32> <i32 1>, ptr %q, i32 4, <1x i1> %vcond.not)
1759/// \endcode
1760///
1761/// So we need to turn hoisted load/store into cload/cstore.
1762///
1763/// \param BI The branch instruction.
1764/// \param SpeculatedConditionalLoadsStores The load/store instructions that
1765/// will be speculated.
1766/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
1768 CondBrInst *BI,
1769 SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
1770 std::optional<bool> Invert, Instruction *Sel) {
1771 auto &Context = BI->getParent()->getContext();
1772 auto *VCondTy = FixedVectorType::get(Type::getInt1Ty(Context), 1);
1773 auto *Cond = BI->getCondition();
1774 // Construct the condition if needed.
1775 BasicBlock *BB = BI->getParent();
1776 Value *Mask = nullptr;
1777 Value *MaskFalse = nullptr;
1778 Value *MaskTrue = nullptr;
1779 if (Invert.has_value()) {
1780 IRBuilder<> Builder(Sel ? Sel : SpeculatedConditionalLoadsStores.back());
1781 Mask = Builder.CreateBitCast(
1782 *Invert ? Builder.CreateXor(Cond, ConstantInt::getTrue(Context)) : Cond,
1783 VCondTy);
1784 } else {
1785 IRBuilder<> Builder(BI);
1786 MaskFalse = Builder.CreateBitCast(
1787 Builder.CreateXor(Cond, ConstantInt::getTrue(Context)), VCondTy);
1788 MaskTrue = Builder.CreateBitCast(Cond, VCondTy);
1789 }
1790 auto PeekThroughBitcasts = [](Value *V) {
1791 while (auto *BitCast = dyn_cast<BitCastInst>(V))
1792 V = BitCast->getOperand(0);
1793 return V;
1794 };
1795 for (auto *I : SpeculatedConditionalLoadsStores) {
1796 IRBuilder<> Builder(Invert.has_value() ? I : BI);
1797 if (!Invert.has_value())
1798 Mask = I->getParent() == BI->getSuccessor(0) ? MaskTrue : MaskFalse;
1799 // We currently assume conditional faulting load/store is supported for
1800 // scalar types only when creating new instructions. This can be easily
1801 // extended for vector types in the future.
1802 assert(!getLoadStoreType(I)->isVectorTy() && "not implemented");
1803 auto *Op0 = I->getOperand(0);
1804 CallInst *MaskedLoadStore = nullptr;
1805 if (auto *LI = dyn_cast<LoadInst>(I)) {
1806 // Handle Load.
1807 auto *Ty = I->getType();
1808 PHINode *PN = nullptr;
1809 Value *PassThru = nullptr;
1810 if (Invert.has_value())
1811 for (User *U : I->users()) {
1812 if ((PN = dyn_cast<PHINode>(U))) {
1813 PassThru = Builder.CreateBitCast(
1814 PeekThroughBitcasts(PN->getIncomingValueForBlock(BB)),
1815 FixedVectorType::get(Ty, 1));
1816 } else if (auto *Ins = cast<Instruction>(U);
1817 Sel && Ins->getParent() == BB) {
1818 // This happens when store or/and a speculative instruction between
1819 // load and store were hoisted to the BB. Make sure the masked load
1820 // inserted before its use.
1821 // We assume there's one of such use.
1822 Builder.SetInsertPoint(Ins);
1823 }
1824 }
1825 MaskedLoadStore = Builder.CreateMaskedLoad(
1826 FixedVectorType::get(Ty, 1), Op0, LI->getAlign(), Mask, PassThru);
1827 if (const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1829 if (PassThru && !isa<PoisonValue>(PassThru)) {
1830 auto *C = dyn_cast<Constant>(PassThru);
1831 CR = C ? CR.unionWith(C->toConstantRange())
1832 : ConstantRange::getFull(CR.getBitWidth());
1833 }
1834 MaskedLoadStore->addRangeRetAttr(CR);
1835 }
1836 Value *NewLoadStore = Builder.CreateBitCast(MaskedLoadStore, Ty);
1837 if (PN)
1838 PN->setIncomingValue(PN->getBasicBlockIndex(BB), NewLoadStore);
1839 I->replaceAllUsesWith(NewLoadStore);
1840 } else {
1841 // Handle Store.
1842 auto *StoredVal = Builder.CreateBitCast(
1843 PeekThroughBitcasts(Op0), FixedVectorType::get(Op0->getType(), 1));
1844 MaskedLoadStore = Builder.CreateMaskedStore(
1845 StoredVal, I->getOperand(1), cast<StoreInst>(I)->getAlign(), Mask);
1846 }
1847 // For non-debug metadata, only !annotation, !range, !nonnull and !align are
1848 // kept when hoisting (see Instruction::dropUBImplyingAttrsAndMetadata).
1849 //
1850 // !nonnull, !align : Not support pointer type, no need to keep.
1851 // !range: Kept as a return attribute, widened over PassThru (see above).
1852 // !annotation: Not impact semantics. Keep it.
1853 I->dropUBImplyingAttrsAndUnknownMetadata({LLVMContext::MD_annotation});
1854 // FIXME: DIAssignID is not supported for masked store yet.
1855 // (Verifier::visitDIAssignIDMetadata)
1857 I->eraseMetadataIf([](unsigned MDKind, MDNode *Node) {
1858 return Node->getMetadataID() == Metadata::DIAssignIDKind;
1859 });
1860 MaskedLoadStore->copyMetadata(*I);
1861 I->eraseFromParent();
1862 }
1863}
1864
1866 const TargetTransformInfo &TTI) {
1867 // Not handle volatile or atomic.
1868 bool IsStore = false;
1869 if (auto *L = dyn_cast<LoadInst>(I)) {
1870 if (!L->isSimple() || !HoistLoadsWithCondFaulting)
1871 return false;
1872 } else if (auto *S = dyn_cast<StoreInst>(I)) {
1873 if (!S->isSimple() || !HoistStoresWithCondFaulting)
1874 return false;
1875 IsStore = true;
1876 } else
1877 return false;
1878
1879 // llvm.masked.load/store use i32 for alignment while load/store use i64.
1880 // That's why we have the alignment limitation.
1881 // FIXME: Update the prototype of the intrinsics?
1882 return TTI.hasConditionalLoadStoreForType(getLoadStoreType(I), IsStore) &&
1884}
1885
1886/// Hoist any common code in the successor blocks up into the block. This
1887/// function guarantees that BB dominates all successors. If AllInstsEqOnly is
1888/// given, only perform hoisting in case all successors blocks contain matching
1889/// instructions only. In that case, all instructions can be hoisted and the
1890/// original branch will be replaced and selects for PHIs are added.
1891bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(Instruction *TI,
1892 bool AllInstsEqOnly) {
1893 // This does very trivial matching, with limited scanning, to find identical
1894 // instructions in the two blocks. In particular, we don't want to get into
1895 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1896 // such, we currently just scan for obviously identical instructions in an
1897 // identical order, possibly separated by the same number of non-identical
1898 // instructions.
1899 BasicBlock *BB = TI->getParent();
1900 unsigned int SuccSize = succ_size(BB);
1901 if (SuccSize < 2)
1902 return false;
1903
1904 // If either of the blocks has it's address taken, then we can't do this fold,
1905 // because the code we'd hoist would no longer run when we jump into the block
1906 // by it's address.
1907 SmallSetVector<BasicBlock *, 4> UniqueSuccessors(from_range, successors(BB));
1908 for (auto *Succ : UniqueSuccessors) {
1909 if (Succ->hasAddressTaken())
1910 return false;
1911 // Use getUniquePredecessor instead of getSinglePredecessor to support
1912 // multi-cases successors in switch.
1913 if (Succ->getUniquePredecessor())
1914 continue;
1915 // If Succ has >1 predecessors, continue to check if the Succ contains only
1916 // one `unreachable` inst. Since executing `unreachable` inst is an UB, we
1917 // can relax the condition based on the assumptiom that the program would
1918 // never enter Succ and trigger such an UB.
1919 if (isa<UnreachableInst>(*Succ->begin()))
1920 continue;
1921 return false;
1922 }
1923 // The second of pair is a SkipFlags bitmask.
1924 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1925 SmallVector<SuccIterPair, 8> SuccIterPairs;
1926 for (auto *Succ : UniqueSuccessors) {
1927 BasicBlock::iterator SuccItr = Succ->begin();
1928 if (isa<PHINode>(*SuccItr))
1929 return false;
1930 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1931 }
1932
1933 if (AllInstsEqOnly) {
1934 // Check if all instructions in the successor blocks match. This allows
1935 // hoisting all instructions and removing the blocks we are hoisting from,
1936 // so does not add any new instructions.
1937
1938 // Check if sizes and terminators of all successors match.
1939 unsigned Size0 = UniqueSuccessors[0]->size();
1940 Instruction *Term0 = UniqueSuccessors[0]->getTerminator();
1941 bool AllSame =
1942 all_of(drop_begin(UniqueSuccessors), [Term0, Size0](BasicBlock *Succ) {
1943 return Succ->getTerminator()->isIdenticalTo(Term0) &&
1944 Succ->size() == Size0;
1945 });
1946 if (!AllSame)
1947 return false;
1948 LockstepReverseIterator<true> LRI(UniqueSuccessors.getArrayRef());
1949 while (LRI.isValid()) {
1950 Instruction *I0 = (*LRI)[0];
1951 if (any_of(*LRI, [I0](Instruction *I) {
1952 return !areIdenticalUpToCommutativity(I0, I);
1953 })) {
1954 return false;
1955 }
1956 --LRI;
1957 }
1958 // Now we know that all instructions in all successors can be hoisted. Let
1959 // the loop below handle the hoisting.
1960 }
1961
1962 // Count how many instructions were not hoisted so far. There's a limit on how
1963 // many instructions we skip, serving as a compilation time control as well as
1964 // preventing excessive increase of life ranges.
1965 unsigned NumSkipped = 0;
1966 // If we find an unreachable instruction at the beginning of a basic block, we
1967 // can still hoist instructions from the rest of the basic blocks.
1968 if (SuccIterPairs.size() > 2) {
1969 erase_if(SuccIterPairs,
1970 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1971 if (SuccIterPairs.size() < 2)
1972 return false;
1973 }
1974
1975 bool Changed = false;
1976
1977 for (;;) {
1978 auto *SuccIterPairBegin = SuccIterPairs.begin();
1979 auto &BB1ItrPair = *SuccIterPairBegin++;
1980 auto OtherSuccIterPairRange =
1981 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1982 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1983
1984 Instruction *I1 = &*BB1ItrPair.first;
1985
1986 bool AllInstsAreIdentical = true;
1987 bool HasTerminator = I1->isTerminator();
1988 for (auto &SuccIter : OtherSuccIterRange) {
1989 Instruction *I2 = &*SuccIter;
1990 HasTerminator |= I2->isTerminator();
1991 if (AllInstsAreIdentical && (!areIdenticalUpToCommutativity(I1, I2) ||
1992 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1993 AllInstsAreIdentical = false;
1994 }
1995
1996 SmallVector<Instruction *, 8> OtherInsts;
1997 for (auto &SuccIter : OtherSuccIterRange)
1998 OtherInsts.push_back(&*SuccIter);
1999
2000 // If we are hoisting the terminator instruction, don't move one (making a
2001 // broken BB), instead clone it, and remove BI.
2002 if (HasTerminator) {
2003 // Even if BB, which contains only one unreachable instruction, is ignored
2004 // at the beginning of the loop, we can hoist the terminator instruction.
2005 // If any instructions remain in the block, we cannot hoist terminators.
2006 if (NumSkipped || !AllInstsAreIdentical) {
2007 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2008 return Changed;
2009 }
2010
2011 return hoistSuccIdenticalTerminatorToSwitchOrIf(
2012 TI, I1, OtherInsts, UniqueSuccessors.getArrayRef()) ||
2013 Changed;
2014 }
2015
2016 if (AllInstsAreIdentical) {
2017 unsigned SkipFlagsBB1 = BB1ItrPair.second;
2018 AllInstsAreIdentical =
2019 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
2020 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
2021 Instruction *I2 = &*Pair.first;
2022 unsigned SkipFlagsBB2 = Pair.second;
2023 // Even if the instructions are identical, it may not
2024 // be safe to hoist them if we have skipped over
2025 // instructions with side effects or their operands
2026 // weren't hoisted.
2027 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
2029 });
2030 }
2031
2032 // A musttail call must be immediately followed by a ret, so hoisting is
2033 // only legal if its ret is hoisted with it on the next iteration. That is,
2034 // no instruction has been skipped (the entire successor can be hoisted into
2035 // the predecessor) and the call is directly followed by a ret.
2036 if (auto *CI = dyn_cast<CallInst>(I1);
2037 AllInstsAreIdentical && CI && CI->isMustTailCall()) {
2038 AllInstsAreIdentical =
2039 NumSkipped == 0 && all_of(SuccIterPairs, [](const SuccIterPair &P) {
2040 return isa<ReturnInst>(*std::next(P.first));
2041 });
2042 }
2043
2044 if (AllInstsAreIdentical) {
2045 BB1ItrPair.first++;
2046 // For a normal instruction, we just move one to right before the
2047 // branch, then replace all uses of the other with the first. Finally,
2048 // we remove the now redundant second instruction.
2049 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2050 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
2051 // and leave any that were not hoisted behind (by calling moveBefore
2052 // rather than moveBeforePreserving).
2053 I1->moveBefore(TI->getIterator());
2054 for (auto &SuccIter : OtherSuccIterRange) {
2055 Instruction *I2 = &*SuccIter++;
2056 assert(I2 != I1);
2057 if (!I2->use_empty())
2058 I2->replaceAllUsesWith(I1);
2059 I1->andIRFlags(I2);
2060 if (auto *CB = dyn_cast<CallBase>(I1)) {
2061 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I2));
2062 assert(Success && "We should not be trying to hoist callbases "
2063 "with non-intersectable attributes");
2064 // For NDEBUG Compile.
2065 (void)Success;
2066 }
2067
2068 combineMetadataForCSE(I1, I2, true);
2069 // If we are combining select instructions, we mark the profile
2070 // explicitly unknown given we are hoisting the instruction across
2071 // control flow and we have no guarantee that the control flow condition
2072 // we are hoisting across is independent of the select condition.
2073 if (auto *SI = dyn_cast<SelectInst>(I1))
2075 // I1 and I2 are being combined into a single instruction. Its debug
2076 // location is the merged locations of the original instructions.
2077 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
2078 I2->eraseFromParent();
2079 }
2080 // I1 now executes before the instructions we skipped.
2081 unsigned SkippedFlags = 0;
2082 for (const SuccIterPair &P : SuccIterPairs)
2083 SkippedFlags |= P.second;
2084 if (SkippedFlags & SkipImplicitControlFlow) {
2085 // One of them may throw or not return, so I1 is speculated.
2086 I1->dropUBImplyingAttrsAndMetadata();
2087 }
2088 if (!Changed)
2089 NumHoistCommonCode += SuccIterPairs.size();
2090 Changed = true;
2091 NumHoistCommonInstrs += SuccIterPairs.size();
2092 } else {
2093 if (NumSkipped >= HoistCommonSkipLimit) {
2094 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2095 return Changed;
2096 }
2097 // We are about to skip over a pair of non-identical instructions. Record
2098 // if any have characteristics that would prevent reordering instructions
2099 // across them.
2100 for (auto &SuccIterPair : SuccIterPairs) {
2101 Instruction *I = &*SuccIterPair.first++;
2102 SuccIterPair.second |= skippedInstrFlags(I);
2103 }
2104 ++NumSkipped;
2105 }
2106 }
2107}
2108
2109bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
2110 Instruction *TI, Instruction *I1,
2111 SmallVectorImpl<Instruction *> &OtherSuccTIs,
2112 ArrayRef<BasicBlock *> UniqueSuccessors) {
2113
2114 auto *BI = dyn_cast<CondBrInst>(TI);
2115
2116 bool Changed = false;
2117 BasicBlock *TIParent = TI->getParent();
2118 BasicBlock *BB1 = I1->getParent();
2119
2120 // Use only for an if statement.
2121 auto *I2 = *OtherSuccTIs.begin();
2122 auto *BB2 = I2->getParent();
2123 if (BI) {
2124 assert(OtherSuccTIs.size() == 1);
2125 assert(BI->getSuccessor(0) == I1->getParent());
2126 assert(BI->getSuccessor(1) == I2->getParent());
2127 }
2128
2129 // In the case of an if statement, we try to hoist an invoke.
2130 // FIXME: Can we define a safety predicate for CallBr?
2131 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
2132 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
2133 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
2134 return false;
2135
2136 // TODO: callbr hoisting currently disabled pending further study.
2137 if (isa<CallBrInst>(I1))
2138 return false;
2139
2140 for (BasicBlock *Succ : successors(BB1)) {
2141 for (PHINode &PN : Succ->phis()) {
2142 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2143 for (Instruction *OtherSuccTI : OtherSuccTIs) {
2144 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
2145 if (BB1V == BB2V)
2146 continue;
2147
2148 // In the case of an if statement, check for
2149 // passingValueIsAlwaysUndefined here because we would rather eliminate
2150 // undefined control flow then converting it to a select.
2151 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
2153 return false;
2154 }
2155 }
2156 }
2157
2158 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
2159 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
2160 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
2161 // Clone the terminator and hoist it into the pred, without any debug info.
2162 Instruction *NT = I1->clone();
2163 NT->insertInto(TIParent, TI->getIterator());
2164 if (!NT->getType()->isVoidTy()) {
2165 I1->replaceAllUsesWith(NT);
2166 for (Instruction *OtherSuccTI : OtherSuccTIs)
2167 OtherSuccTI->replaceAllUsesWith(NT);
2168 NT->takeName(I1);
2169 }
2170 Changed = true;
2171 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
2172
2173 // Ensure terminator gets a debug location, even an unknown one, in case
2174 // it involves inlinable calls.
2176 Locs.push_back(I1->getDebugLoc());
2177 for (auto *OtherSuccTI : OtherSuccTIs)
2178 Locs.push_back(OtherSuccTI->getDebugLoc());
2179 NT->setDebugLoc(DebugLoc::getMergedLocations(Locs));
2180
2181 // PHIs created below will adopt NT's merged DebugLoc.
2182 IRBuilder<NoFolder> Builder(NT);
2183
2184 // In the case of an if statement, hoisting one of the terminators from our
2185 // successor is a great thing. Unfortunately, the successors of the if/else
2186 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
2187 // must agree for all PHI nodes, so we insert select instruction to compute
2188 // the final result.
2189 if (BI) {
2190 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
2191 for (BasicBlock *Succ : successors(BB1)) {
2192 for (PHINode &PN : Succ->phis()) {
2193 Value *BB1V = PN.getIncomingValueForBlock(BB1);
2194 Value *BB2V = PN.getIncomingValueForBlock(BB2);
2195 if (BB1V == BB2V)
2196 continue;
2197
2198 // These values do not agree. Insert a select instruction before NT
2199 // that determines the right value.
2200 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
2201 if (!SI) {
2202 // Propagate fast-math-flags from phi node to its replacement select.
2204 BI->getCondition(), BB1V, BB2V,
2205 isa<FPMathOperator>(PN) ? &PN : nullptr,
2206 BB1V->getName() + "." + BB2V->getName(), BI));
2207 }
2208
2209 // Make the PHI node use the select for all incoming values for BB1/BB2
2210 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2211 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
2212 PN.setIncomingValue(i, SI);
2213 }
2214 }
2215 }
2216
2218
2219 // Update any PHI nodes in our new successors.
2220 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
2221 for (BasicBlock *Succ : successors(BB1)) {
2222 addPredecessorToBlock(Succ, TIParent, BB1);
2223
2224 if (DTU && VisitedSuccs.insert(Succ).second)
2225 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
2226 }
2227
2228 if (DTU) {
2229 // TI might be a switch with multi-cases destination, so we need to care for
2230 // the duplication of successors.
2231 for (BasicBlock *Succ : UniqueSuccessors)
2232 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
2233 }
2234
2236 if (DTU)
2237 DTU->applyUpdates(Updates);
2238 return Changed;
2239}
2240
2241// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
2242// into variables.
2244 int OpIdx) {
2245 // Divide/Remainder by constant is typically much cheaper than by variable.
2246 if (I->isIntDivRem())
2247 return OpIdx != 1;
2248 return !isa<IntrinsicInst>(I);
2249}
2250
2251// All instructions in Insts belong to different blocks that all unconditionally
2252// branch to a common successor. Analyze each instruction and return true if it
2253// would be possible to sink them into their successor, creating one common
2254// instruction instead. For every value that would be required to be provided by
2255// PHI node (because an operand varies in each input block), add to PHIOperands.
2258 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
2259 // Prune out obviously bad instructions to move. Each instruction must have
2260 // the same number of uses, and we check later that the uses are consistent.
2261 std::optional<unsigned> NumUses;
2262 for (auto *I : Insts) {
2263 // These instructions may change or break semantics if moved.
2264 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
2265 I->getType()->isTokenTy())
2266 return false;
2267
2268 // Do not try to sink an instruction in an infinite loop - it can cause
2269 // this algorithm to infinite loop.
2270 if (I->getParent()->getSingleSuccessor() == I->getParent())
2271 return false;
2272
2273 // Conservatively return false if I is an inline-asm instruction. Sinking
2274 // and merging inline-asm instructions can potentially create arguments
2275 // that cannot satisfy the inline-asm constraints.
2276 // If the instruction has nomerge or convergent attribute, return false.
2277 if (const auto *C = dyn_cast<CallBase>(I))
2278 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
2279 return false;
2280
2281 if (!NumUses)
2282 NumUses = I->getNumUses();
2283 else if (NumUses != I->getNumUses())
2284 return false;
2285 }
2286
2287 const Instruction *I0 = Insts.front();
2288 const auto I0MMRA = MMRAMetadata(*I0);
2289 for (auto *I : Insts) {
2290 if (!I->isSameOperationAs(I0, Instruction::CompareUsingIntersectedAttrs))
2291 return false;
2292
2293 // Treat MMRAs conservatively. This pass can be quite aggressive and
2294 // could drop a lot of MMRAs otherwise.
2295 if (MMRAMetadata(*I) != I0MMRA)
2296 return false;
2297 }
2298
2299 // Uses must be consistent: If I0 is used in a phi node in the sink target,
2300 // then the other phi operands must match the instructions from Insts. This
2301 // also has to hold true for any phi nodes that would be created as a result
2302 // of sinking. Both of these cases are represented by PhiOperands.
2303 for (const Use &U : I0->uses()) {
2304 auto It = PHIOperands.find(&U);
2305 if (It == PHIOperands.end())
2306 // There may be uses in other blocks when sinking into a loop header.
2307 return false;
2308 if (!equal(Insts, It->second))
2309 return false;
2310 }
2311
2312 // For calls to be sinkable, they must all be indirect, or have same callee.
2313 // I.e. if we have two direct calls to different callees, we don't want to
2314 // turn that into an indirect call. Likewise, if we have an indirect call,
2315 // and a direct call, we don't actually want to have a single indirect call.
2316 if (isa<CallBase>(I0)) {
2317 auto IsIndirectCall = [](const Instruction *I) {
2318 return cast<CallBase>(I)->isIndirectCall();
2319 };
2320 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
2321 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
2322 if (HaveIndirectCalls) {
2323 if (!AllCallsAreIndirect)
2324 return false;
2325 } else {
2326 // All callees must be identical.
2327 Value *Callee = nullptr;
2328 for (const Instruction *I : Insts) {
2329 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
2330 if (!Callee)
2331 Callee = CurrCallee;
2332 else if (Callee != CurrCallee)
2333 return false;
2334 }
2335 }
2336 }
2337
2338 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2339 Value *Op = I0->getOperand(OI);
2340 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2341 assert(I->getNumOperands() == I0->getNumOperands());
2342 return I->getOperand(OI) == I0->getOperand(OI);
2343 };
2344 if (!all_of(Insts, SameAsI0)) {
2345 auto CanReplaceOperand = [OI](const Instruction *I) {
2346 return canReplaceOperandWithVariable(I, OI);
2347 };
2349 !all_of(Insts, CanReplaceOperand))
2350 // We can't create a PHI from this operand.
2351 return false;
2352 auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
2353 for (auto *I : Insts)
2354 Ops.push_back(I->getOperand(OI));
2355 }
2356 }
2357 return true;
2358}
2359
2360// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2361// instruction of every block in Blocks to their common successor, commoning
2362// into one instruction.
2364 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
2365
2366 // canSinkInstructions returning true guarantees that every block has at
2367 // least one non-terminator instruction.
2369 for (auto *BB : Blocks) {
2370 Instruction *I = BB->getTerminator();
2371 I = I->getPrevNode();
2372 Insts.push_back(I);
2373 }
2374
2375 // We don't need to do any more checking here; canSinkInstructions should
2376 // have done it all for us.
2377 SmallVector<Value*, 4> NewOperands;
2378 Instruction *I0 = Insts.front();
2379 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2380 // This check is different to that in canSinkInstructions. There, we
2381 // cared about the global view once simplifycfg (and instcombine) have
2382 // completed - it takes into account PHIs that become trivially
2383 // simplifiable. However here we need a more local view; if an operand
2384 // differs we create a PHI and rely on instcombine to clean up the very
2385 // small mess we may make.
2386 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2387 return I->getOperand(O) != I0->getOperand(O);
2388 });
2389 if (!NeedPHI) {
2390 NewOperands.push_back(I0->getOperand(O));
2391 continue;
2392 }
2393
2394 // Create a new PHI in the successor block and populate it.
2395 auto *Op = I0->getOperand(O);
2396 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2397 auto *PN =
2398 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2399 PN->insertBefore(BBEnd->begin());
2400 for (auto *I : Insts)
2401 PN->addIncoming(I->getOperand(O), I->getParent());
2402 NewOperands.push_back(PN);
2403 }
2404
2405 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2406 // and move it to the start of the successor block.
2407 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2408 I0->getOperandUse(O).set(NewOperands[O]);
2409
2410 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2411
2412 // Update metadata and IR flags, and merge debug locations.
2413 for (auto *I : Insts)
2414 if (I != I0) {
2415 // The debug location for the "common" instruction is the merged locations
2416 // of all the commoned instructions. We start with the original location
2417 // of the "common" instruction and iteratively merge each location in the
2418 // loop below.
2419 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2420 // However, as N-way merge for CallInst is rare, so we use simplified API
2421 // instead of using complex API for N-way merge.
2422 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2423 combineMetadataForCSE(I0, I, true);
2424 // We mark branch weights explicitly unknown for select instructions as we
2425 // might be sinking through control flow with conditions not independent
2426 // of the select condition, or pulling multiple conditions together
2427 // through a phi node.
2428 if (auto *SI = dyn_cast<SelectInst>(I0))
2430 I0->andIRFlags(I);
2431 if (auto *CB = dyn_cast<CallBase>(I0)) {
2432 bool Success = CB->tryIntersectAttributes(cast<CallBase>(I));
2433 assert(Success && "We should not be trying to sink callbases "
2434 "with non-intersectable attributes");
2435 // For NDEBUG Compile.
2436 (void)Success;
2437 }
2438 }
2439
2440 for (User *U : make_early_inc_range(I0->users())) {
2441 // canSinkLastInstruction checked that all instructions are only used by
2442 // phi nodes in a way that allows replacing the phi node with the common
2443 // instruction.
2444 auto *PN = cast<PHINode>(U);
2445 PN->replaceAllUsesWith(I0);
2446 PN->eraseFromParent();
2447 }
2448
2449 // Finally nuke all instructions apart from the common instruction.
2450 for (auto *I : Insts) {
2451 if (I == I0)
2452 continue;
2453 // The remaining uses are debug users, replace those with the common inst.
2454 // In most (all?) cases this just introduces a use-before-def.
2455 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2456 I->replaceAllUsesWith(I0);
2457 I->eraseFromParent();
2458 }
2459}
2460
2461/// Check whether BB's predecessors end with unconditional branches. If it is
2462/// true, sink any common code from the predecessors to BB.
2464 DomTreeUpdater *DTU) {
2465 // We support two situations:
2466 // (1) all incoming arcs are unconditional
2467 // (2) there are non-unconditional incoming arcs
2468 //
2469 // (2) is very common in switch defaults and
2470 // else-if patterns;
2471 //
2472 // if (a) f(1);
2473 // else if (b) f(2);
2474 //
2475 // produces:
2476 //
2477 // [if]
2478 // / \
2479 // [f(1)] [if]
2480 // | | \
2481 // | | |
2482 // | [f(2)]|
2483 // \ | /
2484 // [ end ]
2485 //
2486 // [end] has two unconditional predecessor arcs and one conditional. The
2487 // conditional refers to the implicit empty 'else' arc. This conditional
2488 // arc can also be caused by an empty default block in a switch.
2489 //
2490 // In this case, we attempt to sink code from all *unconditional* arcs.
2491 // If we can sink instructions from these arcs (determined during the scan
2492 // phase below) we insert a common successor for all unconditional arcs and
2493 // connect that to [end], to enable sinking:
2494 //
2495 // [if]
2496 // / \
2497 // [x(1)] [if]
2498 // | | \
2499 // | | \
2500 // | [x(2)] |
2501 // \ / |
2502 // [sink.split] |
2503 // \ /
2504 // [ end ]
2505 //
2506 SmallVector<BasicBlock*,4> UnconditionalPreds;
2507 bool HaveNonUnconditionalPredecessors = false;
2508 for (auto *PredBB : predecessors(BB)) {
2509 auto *PredBr = dyn_cast<UncondBrInst>(PredBB->getTerminator());
2510 if (PredBr)
2511 UnconditionalPreds.push_back(PredBB);
2512 else
2513 HaveNonUnconditionalPredecessors = true;
2514 }
2515 if (UnconditionalPreds.size() < 2)
2516 return false;
2517
2518 // We take a two-step approach to tail sinking. First we scan from the end of
2519 // each block upwards in lockstep. If the n'th instruction from the end of each
2520 // block can be sunk, those instructions are added to ValuesToSink and we
2521 // carry on. If we can sink an instruction but need to PHI-merge some operands
2522 // (because they're not identical in each instruction) we add these to
2523 // PHIOperands.
2524 // We prepopulate PHIOperands with the phis that already exist in BB.
2526 for (PHINode &PN : BB->phis()) {
2528 for (const Use &U : PN.incoming_values())
2529 IncomingVals.insert({PN.getIncomingBlock(U), &U});
2530 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2531 for (BasicBlock *Pred : UnconditionalPreds)
2532 Ops.push_back(*IncomingVals[Pred]);
2533 }
2534
2535 int ScanIdx = 0;
2536 SmallPtrSet<Value*,4> InstructionsToSink;
2537 LockstepReverseIterator<true> LRI(UnconditionalPreds);
2538 while (LRI.isValid() &&
2539 canSinkInstructions(*LRI, PHIOperands)) {
2540 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2541 << "\n");
2542 InstructionsToSink.insert_range(*LRI);
2543 ++ScanIdx;
2544 --LRI;
2545 }
2546
2547 // If no instructions can be sunk, early-return.
2548 if (ScanIdx == 0)
2549 return false;
2550
2551 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2552
2553 if (!followedByDeoptOrUnreachable) {
2554 // Check whether this is the pointer operand of a load/store.
2555 auto IsMemOperand = [](Use &U) {
2556 auto *I = cast<Instruction>(U.getUser());
2557 if (isa<LoadInst>(I))
2558 return U.getOperandNo() == LoadInst::getPointerOperandIndex();
2559 if (isa<StoreInst>(I))
2560 return U.getOperandNo() == StoreInst::getPointerOperandIndex();
2561 return false;
2562 };
2563
2564 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2565 // actually sink before encountering instruction that is unprofitable to
2566 // sink?
2567 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator<true> &LRI) {
2568 unsigned NumPHIInsts = 0;
2569 for (Use &U : (*LRI)[0]->operands()) {
2570 auto It = PHIOperands.find(&U);
2571 if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2572 return InstructionsToSink.contains(V);
2573 })) {
2574 ++NumPHIInsts;
2575 // Do not separate a load/store from the gep producing the address.
2576 // The gep can likely be folded into the load/store as an addressing
2577 // mode. Additionally, a load of a gep is easier to analyze than a
2578 // load of a phi.
2579 if (IsMemOperand(U) &&
2580 any_of(It->second, [](Value *V) { return isa<GEPOperator>(V); }))
2581 return false;
2582 // FIXME: this check is overly optimistic. We may end up not sinking
2583 // said instruction, due to the very same profitability check.
2584 // See @creating_too_many_phis in sink-common-code.ll.
2585 }
2586 }
2587 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2588 return NumPHIInsts <= 1;
2589 };
2590
2591 // We've determined that we are going to sink last ScanIdx instructions,
2592 // and recorded them in InstructionsToSink. Now, some instructions may be
2593 // unprofitable to sink. But that determination depends on the instructions
2594 // that we are going to sink.
2595
2596 // First, forward scan: find the first instruction unprofitable to sink,
2597 // recording all the ones that are profitable to sink.
2598 // FIXME: would it be better, after we detect that not all are profitable.
2599 // to either record the profitable ones, or erase the unprofitable ones?
2600 // Maybe we need to choose (at runtime) the one that will touch least
2601 // instrs?
2602 LRI.reset();
2603 int Idx = 0;
2604 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2605 while (Idx < ScanIdx) {
2606 if (!ProfitableToSinkInstruction(LRI)) {
2607 // Too many PHIs would be created.
2608 LLVM_DEBUG(
2609 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2610 break;
2611 }
2612 InstructionsProfitableToSink.insert_range(*LRI);
2613 --LRI;
2614 ++Idx;
2615 }
2616
2617 // If no instructions can be sunk, early-return.
2618 if (Idx == 0)
2619 return false;
2620
2621 // Did we determine that (only) some instructions are unprofitable to sink?
2622 if (Idx < ScanIdx) {
2623 // Okay, some instructions are unprofitable.
2624 ScanIdx = Idx;
2625 InstructionsToSink = InstructionsProfitableToSink;
2626
2627 // But, that may make other instructions unprofitable, too.
2628 // So, do a backward scan, do any earlier instructions become
2629 // unprofitable?
2630 assert(
2631 !ProfitableToSinkInstruction(LRI) &&
2632 "We already know that the last instruction is unprofitable to sink");
2633 ++LRI;
2634 --Idx;
2635 while (Idx >= 0) {
2636 // If we detect that an instruction becomes unprofitable to sink,
2637 // all earlier instructions won't be sunk either,
2638 // so preemptively keep InstructionsProfitableToSink in sync.
2639 // FIXME: is this the most performant approach?
2640 for (auto *I : *LRI)
2641 InstructionsProfitableToSink.erase(I);
2642 if (!ProfitableToSinkInstruction(LRI)) {
2643 // Everything starting with this instruction won't be sunk.
2644 ScanIdx = Idx;
2645 InstructionsToSink = InstructionsProfitableToSink;
2646 }
2647 ++LRI;
2648 --Idx;
2649 }
2650 }
2651
2652 // If no instructions can be sunk, early-return.
2653 if (ScanIdx == 0)
2654 return false;
2655 }
2656
2657 bool Changed = false;
2658
2659 if (HaveNonUnconditionalPredecessors) {
2660 if (!followedByDeoptOrUnreachable) {
2661 // It is always legal to sink common instructions from unconditional
2662 // predecessors. However, if not all predecessors are unconditional,
2663 // this transformation might be pessimizing. So as a rule of thumb,
2664 // don't do it unless we'd sink at least one non-speculatable instruction.
2665 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2666 LRI.reset();
2667 int Idx = 0;
2668 bool Profitable = false;
2669 while (Idx < ScanIdx) {
2670 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2671 Profitable = true;
2672 break;
2673 }
2674 --LRI;
2675 ++Idx;
2676 }
2677 if (!Profitable)
2678 return false;
2679 }
2680
2681 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2682 // We have a conditional edge and we're going to sink some instructions.
2683 // Insert a new block postdominating all blocks we're going to sink from.
2684 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2685 // Edges couldn't be split.
2686 return false;
2687 Changed = true;
2688 }
2689
2690 // Now that we've analyzed all potential sinking candidates, perform the
2691 // actual sink. We iteratively sink the last non-terminator of the source
2692 // blocks into their common successor unless doing so would require too
2693 // many PHI instructions to be generated (currently only one PHI is allowed
2694 // per sunk instruction).
2695 //
2696 // We can use InstructionsToSink to discount values needing PHI-merging that will
2697 // actually be sunk in a later iteration. This allows us to be more
2698 // aggressive in what we sink. This does allow a false positive where we
2699 // sink presuming a later value will also be sunk, but stop half way through
2700 // and never actually sink it which means we produce more PHIs than intended.
2701 // This is unlikely in practice though.
2702 int SinkIdx = 0;
2703 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2704 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2705 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2706 << "\n");
2707
2708 // Because we've sunk every instruction in turn, the current instruction to
2709 // sink is always at index 0.
2710 LRI.reset();
2711
2712 sinkLastInstruction(UnconditionalPreds);
2713 NumSinkCommonInstrs++;
2714 Changed = true;
2715 }
2716 if (SinkIdx != 0)
2717 ++NumSinkCommonCode;
2718 return Changed;
2719}
2720
2721namespace {
2722
2723struct CompatibleSets {
2724 using SetTy = SmallVector<InvokeInst *, 2>;
2725
2727
2728 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2729
2730 SetTy &getCompatibleSet(InvokeInst *II);
2731
2732 void insert(InvokeInst *II);
2733};
2734
2735CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2736 // Perform a linear scan over all the existing sets, see if the new `invoke`
2737 // is compatible with any particular set. Since we know that all the `invokes`
2738 // within a set are compatible, only check the first `invoke` in each set.
2739 // WARNING: at worst, this has quadratic complexity.
2740 for (CompatibleSets::SetTy &Set : Sets) {
2741 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2742 return Set;
2743 }
2744
2745 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2746 return Sets.emplace_back();
2747}
2748
2749void CompatibleSets::insert(InvokeInst *II) {
2750 getCompatibleSet(II).emplace_back(II);
2751}
2752
2753bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2754 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2755
2756 // Can we theoretically merge these `invoke`s?
2757 auto IsIllegalToMerge = [](InvokeInst *II) {
2758 return II->cannotMerge() || II->isInlineAsm();
2759 };
2760 if (any_of(Invokes, IsIllegalToMerge))
2761 return false;
2762
2763 // Either both `invoke`s must be direct,
2764 // or both `invoke`s must be indirect.
2765 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2766 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2767 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2768 if (HaveIndirectCalls) {
2769 if (!AllCallsAreIndirect)
2770 return false;
2771 } else {
2772 // All callees must be identical.
2773 Value *Callee = nullptr;
2774 for (InvokeInst *II : Invokes) {
2775 Value *CurrCallee = II->getCalledOperand();
2776 assert(CurrCallee && "There is always a called operand.");
2777 if (!Callee)
2778 Callee = CurrCallee;
2779 else if (Callee != CurrCallee)
2780 return false;
2781 }
2782 }
2783
2784 // Either both `invoke`s must not have a normal destination,
2785 // or both `invoke`s must have a normal destination,
2786 auto HasNormalDest = [](InvokeInst *II) {
2787 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIIt());
2788 };
2789 if (any_of(Invokes, HasNormalDest)) {
2790 // Do not merge `invoke` that does not have a normal destination with one
2791 // that does have a normal destination, even though doing so would be legal.
2792 if (!all_of(Invokes, HasNormalDest))
2793 return false;
2794
2795 // All normal destinations must be identical.
2796 BasicBlock *NormalBB = nullptr;
2797 for (InvokeInst *II : Invokes) {
2798 BasicBlock *CurrNormalBB = II->getNormalDest();
2799 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2800 if (!NormalBB)
2801 NormalBB = CurrNormalBB;
2802 else if (NormalBB != CurrNormalBB)
2803 return false;
2804 }
2805
2806 // In the normal destination, the incoming values for these two `invoke`s
2807 // must be compatible.
2808 SmallPtrSet<Value *, 16> EquivalenceSet(llvm::from_range, Invokes);
2810 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2811 &EquivalenceSet))
2812 return false;
2813 }
2814
2815#ifndef NDEBUG
2816 // All unwind destinations must be identical.
2817 // We know that because we have started from said unwind destination.
2818 BasicBlock *UnwindBB = nullptr;
2819 for (InvokeInst *II : Invokes) {
2820 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2821 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2822 if (!UnwindBB)
2823 UnwindBB = CurrUnwindBB;
2824 else
2825 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2826 }
2827#endif
2828
2829 // In the unwind destination, the incoming values for these two `invoke`s
2830 // must be compatible.
2832 Invokes.front()->getUnwindDest(),
2833 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2834 return false;
2835
2836 // Ignoring arguments, these `invoke`s must be identical,
2837 // including operand bundles.
2838 const InvokeInst *II0 = Invokes.front();
2839 for (auto *II : Invokes.drop_front())
2840 if (!II->isSameOperationAs(II0, Instruction::CompareUsingIntersectedAttrs))
2841 return false;
2842
2843 // Can we theoretically form the data operands for the merged `invoke`?
2844 auto IsIllegalToMergeArguments = [](auto Ops) {
2845 Use &U0 = std::get<0>(Ops);
2846 Use &U1 = std::get<1>(Ops);
2847 if (U0 == U1)
2848 return false;
2850 U0.getOperandNo());
2851 };
2852 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2853 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2854 IsIllegalToMergeArguments))
2855 return false;
2856
2857 return true;
2858}
2859
2860} // namespace
2861
2862// Merge all invokes in the provided set, all of which are compatible
2863// as per the `CompatibleSets::shouldBelongToSameSet()`.
2865 DomTreeUpdater *DTU) {
2866 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2867
2869 if (DTU)
2870 Updates.reserve(2 + 3 * Invokes.size());
2871
2872 bool HasNormalDest =
2873 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIIt());
2874
2875 // Clone one of the invokes into a new basic block.
2876 // Since they are all compatible, it doesn't matter which invoke is cloned.
2877 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2878 InvokeInst *II0 = Invokes.front();
2879 BasicBlock *II0BB = II0->getParent();
2880 BasicBlock *InsertBeforeBlock =
2881 II0->getParent()->getIterator()->getNextNode();
2882 Function *Func = II0BB->getParent();
2883 LLVMContext &Ctx = II0->getContext();
2884
2885 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2886 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2887
2888 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2889 // NOTE: all invokes have the same attributes, so no handling needed.
2890 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2891
2892 if (!HasNormalDest) {
2893 // This set does not have a normal destination,
2894 // so just form a new block with unreachable terminator.
2895 BasicBlock *MergedNormalDest = BasicBlock::Create(
2896 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2897 auto *UI = new UnreachableInst(Ctx, MergedNormalDest);
2898 UI->setDebugLoc(DebugLoc::getTemporary());
2899 MergedInvoke->setNormalDest(MergedNormalDest);
2900 }
2901
2902 // The unwind destination, however, remainds identical for all invokes here.
2903
2904 return MergedInvoke;
2905 }();
2906
2907 if (DTU) {
2908 // Predecessor blocks that contained these invokes will now branch to
2909 // the new block that contains the merged invoke, ...
2910 for (InvokeInst *II : Invokes)
2911 Updates.push_back(
2912 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2913
2914 // ... which has the new `unreachable` block as normal destination,
2915 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2916 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2917 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2918 SuccBBOfMergedInvoke});
2919
2920 // Since predecessor blocks now unconditionally branch to a new block,
2921 // they no longer branch to their original successors.
2922 for (InvokeInst *II : Invokes)
2923 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2924 Updates.push_back(
2925 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2926 }
2927
2928 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2929
2930 // Form the merged operands for the merged invoke.
2931 for (Use &U : MergedInvoke->operands()) {
2932 // Only PHI together the indirect callees and data operands.
2933 if (MergedInvoke->isCallee(&U)) {
2934 if (!IsIndirectCall)
2935 continue;
2936 } else if (!MergedInvoke->isDataOperand(&U))
2937 continue;
2938
2939 // Don't create trivial PHI's with all-identical incoming values.
2940 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2941 return II->getOperand(U.getOperandNo()) != U.get();
2942 });
2943 if (!NeedPHI)
2944 continue;
2945
2946 // Form a PHI out of all the data ops under this index.
2948 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
2949 for (InvokeInst *II : Invokes)
2950 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2951
2952 U.set(PN);
2953 }
2954
2955 // We've ensured that each PHI node has compatible (identical) incoming values
2956 // when coming from each of the `invoke`s in the current merge set,
2957 // so update the PHI nodes accordingly.
2958 for (BasicBlock *Succ : successors(MergedInvoke))
2959 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2960 /*ExistPred=*/Invokes.front()->getParent());
2961
2962 // And finally, replace the original `invoke`s with an unconditional branch
2963 // to the block with the merged `invoke`. Also, give that merged `invoke`
2964 // the merged debugloc of all the original `invoke`s.
2965 DILocation *MergedDebugLoc = nullptr;
2966 for (InvokeInst *II : Invokes) {
2967 // Compute the debug location common to all the original `invoke`s.
2968 if (!MergedDebugLoc)
2969 MergedDebugLoc = II->getDebugLoc();
2970 else
2971 MergedDebugLoc =
2972 DebugLoc::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2973
2974 // And replace the old `invoke` with an unconditionally branch
2975 // to the block with the merged `invoke`.
2976 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2977 OrigSuccBB->removePredecessor(II->getParent());
2978 auto *BI = UncondBrInst::Create(MergedInvoke->getParent(), II->getParent());
2979 // The unconditional branch is part of the replacement for the original
2980 // invoke, so should use its DebugLoc.
2981 BI->setDebugLoc(II->getDebugLoc());
2982 bool Success = MergedInvoke->tryIntersectAttributes(II);
2983 assert(Success && "Merged invokes with incompatible attributes");
2984 // For NDEBUG Compile
2985 (void)Success;
2986 II->replaceAllUsesWith(MergedInvoke);
2987 II->eraseFromParent();
2988 ++NumInvokesMerged;
2989 }
2990 MergedInvoke->setDebugLoc(MergedDebugLoc);
2991 ++NumInvokeSetsFormed;
2992
2993 if (DTU)
2994 DTU->applyUpdates(Updates);
2995}
2996
2997/// If this block is a `landingpad` exception handling block, categorize all
2998/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2999/// being "mergeable" together, and then merge invokes in each set together.
3000///
3001/// This is a weird mix of hoisting and sinking. Visually, it goes from:
3002/// [...] [...]
3003/// | |
3004/// [invoke0] [invoke1]
3005/// / \ / \
3006/// [cont0] [landingpad] [cont1]
3007/// to:
3008/// [...] [...]
3009/// \ /
3010/// [invoke]
3011/// / \
3012/// [cont] [landingpad]
3013///
3014/// But of course we can only do that if the invokes share the `landingpad`,
3015/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
3016/// and the invoked functions are "compatible".
3019 return false;
3020
3021 bool Changed = false;
3022
3023 // FIXME: generalize to all exception handling blocks?
3024 if (!BB->isLandingPad())
3025 return Changed;
3026
3027 CompatibleSets Grouper;
3028
3029 // Record all the predecessors of this `landingpad`. As per verifier,
3030 // the only allowed predecessor is the unwind edge of an `invoke`.
3031 // We want to group "compatible" `invokes` into the same set to be merged.
3032 for (BasicBlock *PredBB : predecessors(BB))
3033 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
3034
3035 // And now, merge `invoke`s that were grouped togeter.
3036 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
3037 if (Invokes.size() < 2)
3038 continue;
3039 Changed = true;
3040 mergeCompatibleInvokesImpl(Invokes, DTU);
3041 }
3042
3043 return Changed;
3044}
3045
3046namespace {
3047/// Track ephemeral values, which should be ignored for cost-modelling
3048/// purposes. Requires walking instructions in reverse order.
3049class EphemeralValueTracker {
3050 SmallPtrSet<const Instruction *, 32> EphValues;
3051
3052 bool isEphemeral(const Instruction *I) {
3053 if (isa<AssumeInst>(I))
3054 return true;
3055 return !I->mayHaveSideEffects() && !I->isTerminator() &&
3056 all_of(I->users(), [&](const User *U) {
3057 return EphValues.count(cast<Instruction>(U));
3058 });
3059 }
3060
3061public:
3062 bool track(const Instruction *I) {
3063 if (isEphemeral(I)) {
3064 EphValues.insert(I);
3065 return true;
3066 }
3067 return false;
3068 }
3069
3070 bool contains(const Instruction *I) const { return EphValues.contains(I); }
3071};
3072} // namespace
3073
3074/// Determine if we can hoist sink a sole store instruction out of a
3075/// conditional block.
3076///
3077/// We are looking for code like the following:
3078/// BrBB:
3079/// store i32 %add, i32* %arrayidx2
3080/// ... // No other stores or function calls (we could be calling a memory
3081/// ... // function).
3082/// %cmp = icmp ult %x, %y
3083/// br i1 %cmp, label %EndBB, label %ThenBB
3084/// ThenBB:
3085/// store i32 %add5, i32* %arrayidx2
3086/// br label EndBB
3087/// EndBB:
3088/// ...
3089/// We are going to transform this into:
3090/// BrBB:
3091/// store i32 %add, i32* %arrayidx2
3092/// ... //
3093/// %cmp = icmp ult %x, %y
3094/// %add.add5 = select i1 %cmp, i32 %add, %add5
3095/// store i32 %add.add5, i32* %arrayidx2
3096/// ...
3097///
3098/// \return The value from the previous access if the store can be hoisted into
3099/// the predecessor block. PreviousAccess is set to that access. Return
3100/// null otherwise.
3102 BasicBlock *StoreBB, BasicBlock *EndBB,
3103 Instruction *&PreviousAccess) {
3104 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
3105 if (!StoreToHoist)
3106 return nullptr;
3107
3108 // Volatile or atomic.
3109 if (!StoreToHoist->isSimple())
3110 return nullptr;
3111
3112 Value *StorePtr = StoreToHoist->getPointerOperand();
3113 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
3114
3115 // Look for a store to the same pointer in BrBB.
3116 unsigned MaxNumInstToLookAt = 9;
3117 // Skip pseudo probe intrinsic calls which are not really killing any memory
3118 // accesses.
3119 for (Instruction &CurI : reverse(*BrBB)) {
3120 if (!MaxNumInstToLookAt)
3121 break;
3122 --MaxNumInstToLookAt;
3123
3124 if (isa<PseudoProbeInst>(CurI))
3125 continue;
3126
3127 // Could be calling an instruction that affects memory like free().
3128 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
3129 return nullptr;
3130
3131 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
3132 // Found the previous store to same location and type. Make sure it is
3133 // simple, to avoid introducing a spurious non-atomic write after an
3134 // atomic write.
3135 if (SI->getPointerOperand() == StorePtr &&
3136 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
3137 SI->getAlign() >= StoreToHoist->getAlign()) {
3138 // Found the previous store, return its value operand.
3139 PreviousAccess = SI;
3140 return SI->getValueOperand();
3141 }
3142 return nullptr; // Unknown store.
3143 }
3144
3145 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
3146 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
3147 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
3148 Value *Obj = getUnderlyingObject(StorePtr);
3149 bool ExplicitlyDereferenceableOnly;
3150 // The dereferenceability query here is only required to satisfy the
3151 // writable contract, actual dereferenceability is proven by the
3152 // presence of an access. As such, we can ignore frees.
3153 if (isWritableObject(Obj, ExplicitlyDereferenceableOnly) &&
3156 .WithoutRet) &&
3157 (!ExplicitlyDereferenceableOnly ||
3158 isDereferenceablePointer(StorePtr, StoreTy, LI->getDataLayout(),
3159 /*IgnoreFree=*/true))) {
3160 // Found a previous load, return it.
3161 PreviousAccess = LI;
3162 return LI;
3163 }
3164 }
3165 // The load didn't work out, but we may still find a store.
3166 }
3167 }
3168
3169 return nullptr;
3170}
3171
3172/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
3173/// converted to selects.
3175 BasicBlock *EndBB,
3176 unsigned &SpeculatedInstructions,
3177 InstructionCost &Cost,
3178 const TargetTransformInfo &TTI) {
3180 BB->getParent()->hasMinSize()
3183
3184 bool HaveRewritablePHIs = false;
3185 for (PHINode &PN : EndBB->phis()) {
3186 Value *OrigV = PN.getIncomingValueForBlock(BB);
3187 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
3188
3189 // FIXME: Try to remove some of the duplication with
3190 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
3191 if (ThenV == OrigV)
3192 continue;
3193
3194 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(),
3195 Type::getInt1Ty(PN.getContext()),
3196 CmpInst::BAD_ICMP_PREDICATE, CostKind);
3197
3198 // Don't convert to selects if we could remove undefined behavior instead.
3199 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
3201 return false;
3202
3203 HaveRewritablePHIs = true;
3204 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
3205 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
3206 if (!OrigCE && !ThenCE)
3207 continue; // Known cheap (FIXME: Maybe not true for aggregates).
3208
3209 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
3210 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
3211 InstructionCost MaxCost =
3213 if (OrigCost + ThenCost > MaxCost)
3214 return false;
3215
3216 // Account for the cost of an unfolded ConstantExpr which could end up
3217 // getting expanded into Instructions.
3218 // FIXME: This doesn't account for how many operations are combined in the
3219 // constant expression.
3220 ++SpeculatedInstructions;
3221 if (SpeculatedInstructions > 1)
3222 return false;
3223 }
3224
3225 return HaveRewritablePHIs;
3226}
3227
3229 std::optional<bool> Invert,
3230 const TargetTransformInfo &TTI) {
3231 // If the branch is non-unpredictable, and is predicted to *not* branch to
3232 // the `then` block, then avoid speculating it.
3233 if (BI->getMetadata(LLVMContext::MD_unpredictable))
3234 return true;
3235
3236 uint64_t TWeight, FWeight;
3237 if (!extractBranchWeights(*BI, TWeight, FWeight) || (TWeight + FWeight) == 0)
3238 return true;
3239
3240 if (!Invert.has_value())
3241 return false;
3242
3243 uint64_t EndWeight = *Invert ? TWeight : FWeight;
3244 BranchProbability BIEndProb =
3245 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
3246 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3247 return BIEndProb < Likely;
3248}
3249
3250/// Speculate a conditional basic block flattening the CFG.
3251///
3252/// Note that this is a very risky transform currently. Speculating
3253/// instructions like this is most often not desirable. Instead, there is an MI
3254/// pass which can do it with full awareness of the resource constraints.
3255/// However, some cases are "obvious" and we should do directly. An example of
3256/// this is speculating a single, reasonably cheap instruction.
3257///
3258/// There is only one distinct advantage to flattening the CFG at the IR level:
3259/// it makes very common but simplistic optimizations such as are common in
3260/// instcombine and the DAG combiner more powerful by removing CFG edges and
3261/// modeling their effects with easier to reason about SSA value graphs.
3262///
3263///
3264/// An illustration of this transform is turning this IR:
3265/// \code
3266/// BB:
3267/// %cmp = icmp ult %x, %y
3268/// br i1 %cmp, label %EndBB, label %ThenBB
3269/// ThenBB:
3270/// %sub = sub %x, %y
3271/// br label BB2
3272/// EndBB:
3273/// %phi = phi [ %sub, %ThenBB ], [ 0, %BB ]
3274/// ...
3275/// \endcode
3276///
3277/// Into this IR:
3278/// \code
3279/// BB:
3280/// %cmp = icmp ult %x, %y
3281/// %sub = sub %x, %y
3282/// %cond = select i1 %cmp, 0, %sub
3283/// ...
3284/// \endcode
3285///
3286/// \returns true if the conditional block is removed.
3287bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
3288 BasicBlock *ThenBB) {
3289 if (!Options.SpeculateBlocks)
3290 return false;
3291
3292 BasicBlock *BB = BI->getParent();
3293 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
3294 InstructionCost Budget =
3296
3297 // If ThenBB is actually on the false edge of the conditional branch, remember
3298 // to swap the select operands later.
3299 bool Invert = false;
3300 if (ThenBB != BI->getSuccessor(0)) {
3301 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3302 Invert = true;
3303 }
3304 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3305
3306 if (!isProfitableToSpeculate(BI, Invert, TTI))
3307 return false;
3308
3309 // Keep a count of how many times instructions are used within ThenBB when
3310 // they are candidates for sinking into ThenBB. Specifically:
3311 // - They are defined in BB, and
3312 // - They have no side effects, and
3313 // - All of their uses are in ThenBB.
3314 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3315
3316 SmallVector<Instruction *, 4> SpeculatedPseudoProbes;
3317
3318 unsigned SpeculatedInstructions = 0;
3319 bool HoistLoadsStores = Options.HoistLoadsStoresWithCondFaulting;
3320 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
3321 Value *SpeculatedStoreValue = nullptr;
3322 StoreInst *SpeculatedStore = nullptr;
3323 Instruction *PreviousStoreAccess = nullptr;
3324 EphemeralValueTracker EphTracker;
3325 for (Instruction &I : reverse(drop_end(*ThenBB))) {
3326 // Skip pseudo probes. The consequence is we lose track of the branch
3327 // probability for ThenBB, which is fine since the optimization here takes
3328 // place regardless of the branch probability.
3329 if (isa<PseudoProbeInst>(I)) {
3330 // The probe should be deleted so that it will not be over-counted when
3331 // the samples collected on the non-conditional path are counted towards
3332 // the conditional path. We leave it for the counts inference algorithm to
3333 // figure out a proper count for an unknown probe.
3334 SpeculatedPseudoProbes.push_back(&I);
3335 continue;
3336 }
3337
3338 // Ignore ephemeral values, they will be dropped by the transform.
3339 if (EphTracker.track(&I))
3340 continue;
3341
3342 // Only speculatively execute a single instruction (not counting the
3343 // terminator) for now.
3344 bool IsSafeCheapLoadStore = HoistLoadsStores &&
3346 SpeculatedConditionalLoadsStores.size() <
3348 // Not count load/store into cost if target supports conditional faulting
3349 // b/c it's cheap to speculate it.
3350 if (IsSafeCheapLoadStore)
3351 SpeculatedConditionalLoadsStores.push_back(&I);
3352 else
3353 ++SpeculatedInstructions;
3354
3355 if (SpeculatedInstructions > 1)
3356 return false;
3357
3358 // Don't hoist the instruction if it's unsafe or expensive.
3359 if (!IsSafeCheapLoadStore &&
3361 !(HoistCondStores && !SpeculatedStoreValue &&
3362 (SpeculatedStoreValue = isSafeToSpeculateStore(&I, BB, ThenBB, EndBB,
3363 PreviousStoreAccess))))
3364 return false;
3365 if (!IsSafeCheapLoadStore && !SpeculatedStoreValue &&
3368 return false;
3369
3370 // Store the store speculation candidate.
3371 if (!SpeculatedStore && SpeculatedStoreValue)
3372 SpeculatedStore = cast<StoreInst>(&I);
3373
3374 // Do not hoist the instruction if any of its operands are defined but not
3375 // used in BB. The transformation will prevent the operand from
3376 // being sunk into the use block.
3377 for (Use &Op : I.operands()) {
3379 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3380 continue; // Not a candidate for sinking.
3381
3382 ++SinkCandidateUseCounts[OpI];
3383 }
3384 }
3385
3386 // Consider any sink candidates which are only used in ThenBB as costs for
3387 // speculation. Note, while we iterate over a DenseMap here, we are summing
3388 // and so iteration order isn't significant.
3389 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3390 if (Inst->hasNUses(Count)) {
3391 ++SpeculatedInstructions;
3392 if (SpeculatedInstructions > 1)
3393 return false;
3394 }
3395
3396 // Check that we can insert the selects and that it's not too expensive to do
3397 // so.
3398 bool Convert =
3399 SpeculatedStore != nullptr || !SpeculatedConditionalLoadsStores.empty();
3401 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3402 SpeculatedInstructions, Cost, TTI);
3403 if (!Convert || Cost > Budget)
3404 return false;
3405
3406 // If we get here, we can hoist the instruction and if-convert.
3407 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3408
3409 Instruction *Sel = nullptr;
3410 Value *BrCond = BI->getCondition();
3411 // Insert a select of the value of the speculated store.
3412 if (SpeculatedStoreValue) {
3413 IRBuilder<NoFolder> Builder(BI);
3414 Value *OrigV = SpeculatedStore->getValueOperand();
3415 Value *TrueV = SpeculatedStore->getValueOperand();
3416 Value *FalseV = SpeculatedStoreValue;
3417 if (Invert)
3418 std::swap(TrueV, FalseV);
3419 Value *S = Builder.CreateSelect(
3420 BrCond, TrueV, FalseV, "spec.store.select", BI);
3421 Sel = cast<Instruction>(S);
3422 SpeculatedStore->setOperand(0, S);
3423 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3424 SpeculatedStore->getDebugLoc());
3425 // The value stored is still conditional, but the store itself is now
3426 // unconditionally executed, so we must be sure that any linked dbg.assign
3427 // intrinsics are tracking the new stored value (the result of the
3428 // select). If we don't, and the store were to be removed by another pass
3429 // (e.g. DSE), then we'd eventually end up emitting a location describing
3430 // the conditional value, unconditionally.
3431 //
3432 // === Before this transformation ===
3433 // pred:
3434 // store %one, %x.dest, !DIAssignID !1
3435 // dbg.assign %one, "x", ..., !1, ...
3436 // br %cond if.then
3437 //
3438 // if.then:
3439 // store %two, %x.dest, !DIAssignID !2
3440 // dbg.assign %two, "x", ..., !2, ...
3441 //
3442 // === After this transformation ===
3443 // pred:
3444 // store %one, %x.dest, !DIAssignID !1
3445 // dbg.assign %one, "x", ..., !1
3446 /// ...
3447 // %merge = select %cond, %two, %one
3448 // store %merge, %x.dest, !DIAssignID !2
3449 // dbg.assign %merge, "x", ..., !2
3450 for (DbgVariableRecord *DbgAssign :
3451 at::getDVRAssignmentMarkers(SpeculatedStore))
3452 if (llvm::is_contained(DbgAssign->location_ops(), OrigV))
3453 DbgAssign->replaceVariableLocationOp(OrigV, S);
3454 }
3455
3456 // Metadata can be dependent on the condition we are hoisting above.
3457 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3458 // to avoid making it appear as if the condition is a constant, which would
3459 // be misleading while debugging.
3460 // Similarly strip attributes that maybe dependent on condition we are
3461 // hoisting above.
3462 for (auto &I : make_early_inc_range(*ThenBB)) {
3463 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3464 I.dropLocation();
3465 I.dropUBImplyingAttrsAndMetadata();
3466 } else {
3467 assert(PreviousStoreAccess && "Missing previous store access");
3468 AAMDNodes MergedAA = SpeculatedStore->getAAMetadata().merge(
3469 PreviousStoreAccess->getAAMetadata());
3470 I.dropUBImplyingAttrsAndMetadata();
3471 I.setAAMetadata(MergedAA);
3472 }
3473
3474 // Drop ephemeral values.
3475 if (EphTracker.contains(&I)) {
3476 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3477 I.eraseFromParent();
3478 }
3479 }
3480
3481 // Hoist the instructions.
3482 // Drop DbgVariableRecords attached to these instructions.
3483 for (auto &It : *ThenBB)
3484 for (DbgRecord &DR : make_early_inc_range(It.getDbgRecordRange()))
3485 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3486 // equivalent).
3487 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
3488 !DVR || !DVR->isDbgAssign())
3489 It.dropOneDbgRecord(&DR);
3490 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3491 std::prev(ThenBB->end()));
3492
3493 if (!SpeculatedConditionalLoadsStores.empty())
3494 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores, Invert,
3495 Sel);
3496
3497 // Insert selects and rewrite the PHI operands.
3498 IRBuilder<NoFolder> Builder(BI);
3499 for (PHINode &PN : EndBB->phis()) {
3500 unsigned OrigI = PN.getBasicBlockIndex(BB);
3501 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3502 Value *OrigV = PN.getIncomingValue(OrigI);
3503 Value *ThenV = PN.getIncomingValue(ThenI);
3504
3505 // Skip PHIs which are trivial.
3506 if (OrigV == ThenV)
3507 continue;
3508
3509 // Create a select whose true value is the speculatively executed value and
3510 // false value is the pre-existing value. Swap them if the branch
3511 // destinations were inverted.
3512 Value *TrueV = ThenV, *FalseV = OrigV;
3513 if (Invert)
3514 std::swap(TrueV, FalseV);
3515 // Propagate fast-math flags from the phi node to the replacement select.
3516 Value *V = Builder.CreateSelectFMF(
3517 BrCond, TrueV, FalseV, PN.getFastMathFlagsOrNone(), "spec.select", BI);
3518 PN.setIncomingValue(OrigI, V);
3519 PN.setIncomingValue(ThenI, V);
3520 }
3521
3522 // Remove speculated pseudo probes.
3523 for (Instruction *I : SpeculatedPseudoProbes)
3524 I->eraseFromParent();
3525
3526 ++NumSpeculations;
3527 return true;
3528}
3529
3531
3532// Return false if number of blocks searched is too much.
3533static bool findReaching(BasicBlock *BB, BasicBlock *DefBB,
3534 BlocksSet &ReachesNonLocalUses) {
3535 if (BB == DefBB)
3536 return true;
3537 if (!ReachesNonLocalUses.insert(BB).second)
3538 return true;
3539
3540 if (ReachesNonLocalUses.size() > MaxJumpThreadingLiveBlocks)
3541 return false;
3542 for (BasicBlock *Pred : predecessors(BB))
3543 if (!findReaching(Pred, DefBB, ReachesNonLocalUses))
3544 return false;
3545 return true;
3546}
3547
3548/// Return true if threading \p PredBBs through \p Header to \p RealDest
3549/// eliminates the loop's single backedge. \p Header must have two predecessors
3550/// (one entry and one backedge), the threaded predecessor must be dominated by
3551/// \p Header, and \p RealDest must not reach it without passing through
3552/// \p Header.
3554 ArrayRef<BasicBlock *> PredBBs,
3555 BasicBlock *RealDest) {
3556 if (!Header->hasNPredecessors(2))
3557 return false;
3558 BlocksSet Visited;
3559 SmallVector<BasicBlock *, 8> Worklist(PredBBs);
3560 while (!Worklist.empty()) {
3561 BasicBlock *BB = Worklist.pop_back_val();
3562 if (BB == Header || !Visited.insert(BB).second)
3563 continue;
3564 if (BB == RealDest)
3565 return false;
3567 return false;
3568 if (pred_empty(BB))
3569 return false;
3570 append_range(Worklist, predecessors(BB));
3571 }
3572 return true;
3573}
3574
3575/// Return true if we can thread a branch across this block.
3577 BlocksSet &NonLocalUseBlocks) {
3578 int Size = 0;
3579 EphemeralValueTracker EphTracker;
3580
3581 // Walk the loop in reverse so that we can identify ephemeral values properly
3582 // (values only feeding assumes).
3583 for (Instruction &I : reverse(*BB)) {
3584 // Can't fold blocks that contain noduplicate or convergent calls.
3585 if (CallInst *CI = dyn_cast<CallInst>(&I))
3586 if (CI->cannotDuplicate() || CI->isConvergent())
3587 return false;
3588
3589 // Ignore ephemeral values which are deleted during codegen.
3590 // We will delete Phis while threading, so Phis should not be accounted in
3591 // block's size.
3592 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3593 if (Size++ > MaxSmallBlockSize)
3594 return false; // Don't clone large BB's.
3595 }
3596
3597 // Record blocks with non-local uses of values defined in the current basic
3598 // block.
3599 for (User *U : I.users()) {
3601 BasicBlock *UsedInBB = UI->getParent();
3602 if (UsedInBB == BB) {
3603 if (isa<PHINode>(UI))
3604 return false;
3605 } else
3606 NonLocalUseBlocks.insert(UsedInBB);
3607 }
3608
3609 // Looks ok, continue checking.
3610 }
3611
3612 return true;
3613}
3614
3616 BasicBlock *To) {
3617 // Don't look past the block defining the value, we might get the value from
3618 // a previous loop iteration.
3619 auto *I = dyn_cast<Instruction>(V);
3620 if (I && I->getParent() == To)
3621 return nullptr;
3622
3623 // We know the value if the From block branches on it.
3624 auto *BI = dyn_cast<CondBrInst>(From->getTerminator());
3625 if (BI && BI->getCondition() == V &&
3626 BI->getSuccessor(0) != BI->getSuccessor(1))
3627 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3629
3630 return nullptr;
3631}
3632
3634 return CB->isConvergent() && !isa<ConvergenceControlInst>(CB) &&
3636}
3637
3639 BasicBlock *StopBB) {
3640 static constexpr unsigned MaxInstructionsToScan = 512;
3641
3642 // Walk predecessors of StopBB to find blocks that can reach it. Only
3643 // convergent calls on a cycle with StopBB matter - a convergent call on a
3644 // path to function exit cannot have its dynamic instance changed by
3645 // threading.
3646 SmallPtrSet<BasicBlock *, 8> CanReachStop;
3647 SmallPtrSet<BasicBlock *, 8> BlocksWithUncontrolledConvergentCalls;
3649 for (BasicBlock *Pred : predecessors(StopBB))
3650 Worklist.push_back(Pred);
3651
3652 // Cache blocks with relevant calls while building CanReachStop. This keeps
3653 // the instruction scan bounded without a separate block limit.
3654 unsigned NumScannedInstructions = 0;
3655 while (!Worklist.empty()) {
3656 BasicBlock *BB = Worklist.pop_back_val();
3657 if (BB == StopBB)
3658 continue;
3659 if (!CanReachStop.insert(BB).second)
3660 continue;
3661
3662 for (Instruction &I : *BB) {
3663 if (++NumScannedInstructions > MaxInstructionsToScan)
3664 return true;
3665 auto *CB = dyn_cast<CallBase>(&I);
3666 if (CB && isUncontrolledConvergentCall(CB)) {
3667 BlocksWithUncontrolledConvergentCalls.insert(BB);
3668 break;
3669 }
3670 }
3671
3672 append_range(Worklist, predecessors(BB));
3673 }
3674
3675 if (!CanReachStop.contains(From))
3676 return false;
3677
3679 Worklist.push_back(From);
3680
3681 while (!Worklist.empty()) {
3682 BasicBlock *BB = Worklist.pop_back_val();
3683 if (BB == StopBB || !CanReachStop.contains(BB))
3684 continue;
3685
3686 if (!Visited.insert(BB).second)
3687 continue;
3688
3689 if (BlocksWithUncontrolledConvergentCalls.contains(BB))
3690 return true;
3691
3692 append_range(Worklist, successors(BB));
3693 }
3694
3695 return false;
3696}
3697
3698/// If we have a conditional branch on something for which we know the constant
3699/// value in predecessors (e.g. a phi node in the current block), thread edges
3700/// from the predecessor to their ultimate destination.
3703 AssumptionCache *AC, const DataLayout &DL, bool KeepCanonicalLoop) {
3705 BasicBlock *BB = BI->getParent();
3706 Value *Cond = BI->getCondition();
3708 if (PN && PN->getParent() == BB) {
3709 // Degenerate case of a single entry PHI.
3710 if (PN->getNumIncomingValues() == 1) {
3712 return true;
3713 }
3714
3715 for (Use &U : PN->incoming_values())
3716 if (auto *CB = dyn_cast<ConstantInt>(U))
3717 KnownValues[CB].insert(PN->getIncomingBlock(U));
3718 } else {
3719 for (BasicBlock *Pred : predecessors(BB)) {
3720 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3721 KnownValues[CB].insert(Pred);
3722 }
3723 }
3724
3725 if (KnownValues.empty())
3726 return false;
3727
3728 // Now we know that this block has multiple preds and two succs.
3729 // Check that the block is small enough and record which non-local blocks use
3730 // values defined in the block.
3731
3732 BlocksSet NonLocalUseBlocks;
3733 BlocksSet ReachesNonLocalUseBlocks;
3734 if (!blockIsSimpleEnoughToThreadThrough(BB, NonLocalUseBlocks))
3735 return false;
3736
3737 // Jump-threading can only be done to destinations where no values defined
3738 // in BB are live.
3739
3740 // Quickly check if both destinations have uses. If so, jump-threading cannot
3741 // be done.
3742 if (NonLocalUseBlocks.contains(BI->getSuccessor(0)) &&
3743 NonLocalUseBlocks.contains(BI->getSuccessor(1)))
3744 return false;
3745
3746 // Search backward from NonLocalUseBlocks to find which blocks
3747 // reach non-local uses.
3748 for (BasicBlock *UseBB : NonLocalUseBlocks)
3749 // Give up if too many blocks are searched.
3750 if (!findReaching(UseBB, BB, ReachesNonLocalUseBlocks))
3751 return false;
3752
3753 for (const auto &Pair : KnownValues) {
3754 ConstantInt *CB = Pair.first;
3755 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3756 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3757
3758 // Okay, we now know that all edges from PredBB should be revectored to
3759 // branch to RealDest.
3760 if (RealDest == BB)
3761 continue; // Skip self loops.
3762
3763 // Skip if the predecessor's terminator is an indirect branch.
3764 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3765 return isa<IndirectBrInst>(PredBB->getTerminator());
3766 }))
3767 continue;
3768
3769 // Only revector to RealDest if no values defined in BB are live.
3770 if (ReachesNonLocalUseBlocks.contains(RealDest))
3771 continue;
3772
3773 if (KeepCanonicalLoop &&
3774 !isSafeToThreadThroughLoopHeader(BB, PredBBs, RealDest))
3775 continue;
3776
3777 // Threading through a branch can bypass a reconvergence point. If the
3778 // destination can execute an uncontrolled convergent operation before
3779 // returning to this block, this may change the dynamic instance of that
3780 // operation.
3781 if (TTI.hasBranchDivergence(BB->getParent()) &&
3783 continue;
3784
3785 LLVM_DEBUG({
3786 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3787 << " has value " << *Pair.first << " in predecessors:\n";
3788 for (const BasicBlock *PredBB : Pair.second)
3789 dbgs() << " " << PredBB->getName() << "\n";
3790 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3791 });
3792
3793 // Split the predecessors we are threading into a new edge block. We'll
3794 // clone the instructions into this block, and then redirect it to RealDest.
3795 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3796 if (!EdgeBB)
3797 continue;
3798
3799 // TODO: These just exist to reduce test diff, we can drop them if we like.
3800 EdgeBB->setName(RealDest->getName() + ".critedge");
3801 EdgeBB->moveBefore(RealDest);
3802
3803 // Update PHI nodes.
3804 addPredecessorToBlock(RealDest, EdgeBB, BB);
3805
3806 // BB may have instructions that are being threaded over. Clone these
3807 // instructions into EdgeBB. We know that there will be no uses of the
3808 // cloned instructions outside of EdgeBB.
3809 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3810 ValueToValueMapTy TranslateMap; // Track translated values.
3811 TranslateMap[Cond] = CB;
3812
3813 // RemoveDIs: track instructions that we optimise away while folding, so
3814 // that we can copy DbgVariableRecords from them later.
3815 BasicBlock::iterator SrcDbgCursor = BB->begin();
3816 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3817 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3818 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3819 continue;
3820 }
3821 // Clone the instruction.
3822 Instruction *N = BBI->clone();
3823 // Insert the new instruction into its new home.
3824 N->insertInto(EdgeBB, InsertPt);
3825
3826 if (BBI->hasName())
3827 N->setName(BBI->getName() + ".c");
3828
3829 // Update operands due to translation.
3830 // Key Instructions: Remap all the atom groups.
3831 if (const DebugLoc &DL = BBI->getDebugLoc())
3832 mapAtomInstance(DL, TranslateMap);
3833 RemapInstruction(N, TranslateMap,
3835
3836 // Check for trivial simplification.
3837 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3838 if (!BBI->use_empty())
3839 TranslateMap[&*BBI] = V;
3840 if (!N->mayHaveSideEffects()) {
3841 N->eraseFromParent(); // Instruction folded away, don't need actual
3842 // inst
3843 N = nullptr;
3844 }
3845 } else {
3846 if (!BBI->use_empty())
3847 TranslateMap[&*BBI] = N;
3848 }
3849 if (N) {
3850 // Copy all debug-info attached to instructions from the last we
3851 // successfully clone, up to this instruction (they might have been
3852 // folded away).
3853 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3854 N->cloneDebugInfoFrom(&*SrcDbgCursor);
3855 SrcDbgCursor = std::next(BBI);
3856 // Clone debug-info on this instruction too.
3857 N->cloneDebugInfoFrom(&*BBI);
3858
3859 // Register the new instruction with the assumption cache if necessary.
3860 if (auto *Assume = dyn_cast<AssumeInst>(N))
3861 if (AC)
3862 AC->registerAssumption(Assume);
3863 }
3864 }
3865
3866 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3867 InsertPt->cloneDebugInfoFrom(&*SrcDbgCursor);
3868 InsertPt->cloneDebugInfoFrom(BI);
3869
3870 BB->removePredecessor(EdgeBB);
3871 UncondBrInst *EdgeBI = cast<UncondBrInst>(EdgeBB->getTerminator());
3872 EdgeBI->setSuccessor(0, RealDest);
3873 EdgeBI->setDebugLoc(BI->getDebugLoc());
3874
3875 if (DTU) {
3877 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3878 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3879 DTU->applyUpdates(Updates);
3880 }
3881
3882 // For simplicity, we created a separate basic block for the edge. Merge
3883 // it back into the predecessor if possible. This not only avoids
3884 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3885 // bypass the check for trivial cycles above.
3886 MergeBlockIntoPredecessor(EdgeBB, DTU);
3887
3888 // Signal repeat, simplifying any other constants.
3889 return std::nullopt;
3890 }
3891
3892 return false;
3893}
3894
3895bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
3896 // Threading through a loop header can introduce a cycle that bypasses the
3897 // header.
3898 bool KeepCanonicalLoop =
3899 Options.NeedCanonicalLoop && is_contained(LoopHeaders, BI->getParent());
3900
3901 std::optional<bool> Result;
3902 bool EverChanged = false;
3903 do {
3904 // Note that None means "we changed things, but recurse further."
3906 BI, TTI, DTU, Options.AC, DL, KeepCanonicalLoop);
3907 EverChanged |= Result == std::nullopt || *Result;
3908 } while (Result == std::nullopt);
3909 return EverChanged;
3910}
3911
3912/// Given a BB that starts with the specified two-entry PHI node,
3913/// see if we can eliminate it.
3916 const DataLayout &DL,
3917 bool SpeculateUnpredictables) {
3918 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3919 // statement", which has a very simple dominance structure. Basically, we
3920 // are trying to find the condition that is being branched on, which
3921 // subsequently causes this merge to happen. We really want control
3922 // dependence information for this check, but simplifycfg can't keep it up
3923 // to date, and this catches most of the cases we care about anyway.
3924 BasicBlock *BB = PN->getParent();
3925
3926 BasicBlock *IfTrue, *IfFalse;
3927 CondBrInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3928 if (!DomBI)
3929 return false;
3930 Value *IfCond = DomBI->getCondition();
3931 // Don't bother if the branch will be constant folded trivially.
3932 if (isa<ConstantInt>(IfCond))
3933 return false;
3934
3935 BasicBlock *DomBlock = DomBI->getParent();
3937 llvm::copy_if(PN->blocks(), std::back_inserter(IfBlocks),
3938 [](BasicBlock *IfBlock) {
3939 return isa<UncondBrInst>(IfBlock->getTerminator());
3940 });
3941 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3942 "Will have either one or two blocks to speculate.");
3943
3944 // If the branch is non-unpredictable, see if we either predictably jump to
3945 // the merge bb (if we have only a single 'then' block), or if we predictably
3946 // jump to one specific 'then' block (if we have two of them).
3947 // It isn't beneficial to speculatively execute the code
3948 // from the block that we know is predictably not entered.
3949 bool IsUnpredictable = DomBI->getMetadata(LLVMContext::MD_unpredictable);
3950 if (!IsUnpredictable) {
3951 uint64_t TWeight, FWeight;
3952 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3953 (TWeight + FWeight) != 0) {
3954 BranchProbability BITrueProb =
3955 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3956 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3957 BranchProbability BIFalseProb = BITrueProb.getCompl();
3958 if (IfBlocks.size() == 1) {
3959 BranchProbability BIBBProb =
3960 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3961 if (BIBBProb >= Likely)
3962 return false;
3963 } else {
3964 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3965 return false;
3966 }
3967 }
3968 }
3969
3970 // Don't try to fold an unreachable block. For example, the phi node itself
3971 // can't be the candidate if-condition for a select that we want to form.
3972 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3973 if (IfCondPhiInst->getParent() == BB)
3974 return false;
3975
3976 // Okay, we found that we can merge this two-entry phi node into a select.
3977 // Doing so would require us to fold *all* two entry phi nodes in this block.
3978 // At some point this becomes non-profitable (particularly if the target
3979 // doesn't support cmov's). Only do this transformation if there are two or
3980 // fewer PHI nodes in this block.
3981 unsigned NumPhis = 0;
3982 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3983 if (NumPhis > 2)
3984 return false;
3985
3986 // Loop over the PHI's seeing if we can promote them all to select
3987 // instructions. While we are at it, keep track of the instructions
3988 // that need to be moved to the dominating block.
3989 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3990 SmallPtrSet<Instruction *, 2> ZeroCostInstructions;
3991 InstructionCost Cost = 0;
3992 InstructionCost Budget =
3994 if (SpeculateUnpredictables && IsUnpredictable)
3995 Budget += TTI.getBranchMispredictPenalty();
3996
3997 bool Changed = false;
3998 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3999 PHINode *PN = cast<PHINode>(II++);
4000 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
4001 PN->replaceAllUsesWith(V);
4002 PN->eraseFromParent();
4003 Changed = true;
4004 continue;
4005 }
4006
4007 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, DomBI,
4008 AggressiveInsts, Cost, Budget, TTI, AC,
4009 ZeroCostInstructions) ||
4010 !dominatesMergePoint(PN->getIncomingValue(1), BB, DomBI,
4011 AggressiveInsts, Cost, Budget, TTI, AC,
4012 ZeroCostInstructions))
4013 return Changed;
4014 }
4015
4016 // If we folded the first phi, PN dangles at this point. Refresh it. If
4017 // we ran out of PHIs then we simplified them all.
4018 PN = dyn_cast<PHINode>(BB->begin());
4019 if (!PN)
4020 return true;
4021
4022 // Don't fold i1 branches on PHIs which contain binary operators or
4023 // (possibly inverted) select form of or/ands if their parameters are
4024 // an equality test.
4025 auto IsBinOpOrAndEq = [](Value *V) {
4027 if (match(V, m_CombineOr(
4032 m_Cmp(Pred, m_Value(), m_Value()))))) {
4033 return CmpInst::isEquality(Pred);
4034 }
4035 return false;
4036 };
4037 if (PN->getType()->isIntegerTy(1) &&
4038 (IsBinOpOrAndEq(PN->getIncomingValue(0)) ||
4039 IsBinOpOrAndEq(PN->getIncomingValue(1)) || IsBinOpOrAndEq(IfCond)))
4040 return Changed;
4041
4042 // If all PHI nodes are promotable, check to make sure that all instructions
4043 // in the predecessor blocks can be promoted as well. If not, we won't be able
4044 // to get rid of the control flow, so it's not worth promoting to select
4045 // instructions.
4046 for (BasicBlock *IfBlock : IfBlocks)
4047 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
4048 if (!AggressiveInsts.count(&*I) && !isa<PseudoProbeInst>(I)) {
4049 // This is not an aggressive instruction that we can promote.
4050 // Because of this, we won't be able to get rid of the control flow, so
4051 // the xform is not worth it.
4052 return Changed;
4053 }
4054
4055 // If either of the blocks has it's address taken, we can't do this fold.
4056 if (any_of(IfBlocks,
4057 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
4058 return Changed;
4059
4060 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
4061 if (IsUnpredictable) dbgs() << " (unpredictable)";
4062 dbgs() << " T: " << IfTrue->getName()
4063 << " F: " << IfFalse->getName() << "\n");
4064
4065 // If we can still promote the PHI nodes after this gauntlet of tests,
4066 // do all of the PHI's now.
4067
4068 // Move all 'aggressive' instructions, which are defined in the
4069 // conditional parts of the if's up to the dominating block.
4070 for (BasicBlock *IfBlock : IfBlocks)
4071 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
4072
4073 IRBuilder<NoFolder> Builder(DomBI);
4074 // Propagate fast-math-flags from phi nodes to replacement selects.
4075 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
4076 // Change the PHI node into a select instruction.
4077 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
4078 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
4079
4080 Value *Sel = Builder.CreateSelectFMF(IfCond, TrueVal, FalseVal,
4081 isa<FPMathOperator>(PN) ? PN : nullptr,
4082 "", DomBI);
4083 PN->replaceAllUsesWith(Sel);
4084 Sel->takeName(PN);
4085 PN->eraseFromParent();
4086 }
4087
4088 // At this point, all IfBlocks are empty, so our if statement
4089 // has been flattened. Change DomBlock to jump directly to our new block to
4090 // avoid other simplifycfg's kicking in on the diamond.
4091 Builder.CreateBr(BB);
4092
4094 if (DTU) {
4095 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
4096 for (auto *Successor : successors(DomBlock))
4097 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
4098 }
4099
4100 DomBI->eraseFromParent();
4101 if (DTU)
4102 DTU->applyUpdates(Updates);
4103
4104 return true;
4105}
4106
4109 Value *RHS, const Twine &Name = "") {
4110 // Try to relax logical op to binary op.
4111 if (impliesPoison(RHS, LHS))
4112 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
4113 if (Opc == Instruction::And)
4114 return Builder.CreateLogicalAnd(LHS, RHS, Name);
4115 if (Opc == Instruction::Or)
4116 return Builder.CreateLogicalOr(LHS, RHS, Name);
4117 llvm_unreachable("Invalid logical opcode");
4118}
4119
4120/// Return true if either PBI or BI has branch weight available, and store
4121/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
4122/// not have branch weight, use 1:1 as its weight.
4124 uint64_t &PredTrueWeight,
4125 uint64_t &PredFalseWeight,
4126 uint64_t &SuccTrueWeight,
4127 uint64_t &SuccFalseWeight) {
4128 bool PredHasWeights =
4129 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
4130 bool SuccHasWeights =
4131 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
4132 if (PredHasWeights || SuccHasWeights) {
4133 if (!PredHasWeights)
4134 PredTrueWeight = PredFalseWeight = 1;
4135 if (!SuccHasWeights)
4136 SuccTrueWeight = SuccFalseWeight = 1;
4137 return true;
4138 } else {
4139 return false;
4140 }
4141}
4142
4143/// Determine if the two branches share a common destination and deduce a glue
4144/// that joins the branches' conditions to arrive at the common destination if
4145/// that would be profitable.
4146static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
4148 const TargetTransformInfo *TTI) {
4149 assert(BI && PBI && "Both blocks must end with a conditional branches.");
4151 "PredBB must be a predecessor of BB.");
4152
4153 // We have the potential to fold the conditions together, but if the
4154 // predecessor branch is predictable, we may not want to merge them.
4155 uint64_t PTWeight, PFWeight;
4156 BranchProbability PBITrueProb, Likely;
4157 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4158 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
4159 (PTWeight + PFWeight) != 0) {
4160 PBITrueProb =
4161 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
4162 Likely = TTI->getPredictableBranchThreshold();
4163 }
4164
4165 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4166 // Speculate the 2nd condition unless the 1st is probably true.
4167 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4168 return {{BI->getSuccessor(0), Instruction::Or, false}};
4169 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4170 // Speculate the 2nd condition unless the 1st is probably false.
4171 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4172 return {{BI->getSuccessor(1), Instruction::And, false}};
4173 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4174 // Speculate the 2nd condition unless the 1st is probably true.
4175 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4176 return {{BI->getSuccessor(1), Instruction::And, true}};
4177 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4178 // Speculate the 2nd condition unless the 1st is probably false.
4179 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4180 return {{BI->getSuccessor(0), Instruction::Or, true}};
4181 }
4182 return std::nullopt;
4183}
4184
4186 DomTreeUpdater *DTU,
4187 MemorySSAUpdater *MSSAU,
4188 const TargetTransformInfo *TTI) {
4189 BasicBlock *BB = BI->getParent();
4190 BasicBlock *PredBlock = PBI->getParent();
4191
4192 // Determine if the two branches share a common destination.
4193 BasicBlock *CommonSucc;
4195 bool InvertPredCond;
4196 std::tie(CommonSucc, Opc, InvertPredCond) =
4198
4199 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
4200
4202 *BB->getModule(), ConstantFolder{},
4204 // The builder is used to create instructions to eliminate the branch in
4205 // BB. If BB's terminator has !annotation metadata, add it to the new
4206 // instructions.
4207 I->copyMetadata(*BB->getTerminator(), LLVMContext::MD_annotation);
4208 }));
4209 Builder.SetInsertPoint(PBI);
4210
4211 // If we need to invert the condition in the pred block to match, do so now.
4212 if (InvertPredCond) {
4213 InvertBranch(PBI, Builder);
4214 }
4215
4216 BasicBlock *UniqueSucc =
4217 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
4218
4219 // Before cloning instructions, notify the successor basic block that it
4220 // is about to have a new predecessor. This will update PHI nodes,
4221 // which will allow us to update live-out uses of bonus instructions.
4222 addPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
4223
4224 // Try to update branch weights.
4225 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4226 SmallVector<uint64_t, 2> MDWeights;
4227 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4228 SuccTrueWeight, SuccFalseWeight)) {
4229
4230 if (PBI->getSuccessor(0) == BB) {
4231 // PBI: br i1 %x, BB, FalseDest
4232 // BI: br i1 %y, UniqueSucc, FalseDest
4233 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
4234 MDWeights.push_back(PredTrueWeight * SuccTrueWeight);
4235 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
4236 // TrueWeight for PBI * FalseWeight for BI.
4237 // We assume that total weights of a CondBrInst can fit into 32 bits.
4238 // Therefore, we will not have overflow using 64-bit arithmetic.
4239 MDWeights.push_back(PredFalseWeight * (SuccFalseWeight + SuccTrueWeight) +
4240 PredTrueWeight * SuccFalseWeight);
4241 } else {
4242 // PBI: br i1 %x, TrueDest, BB
4243 // BI: br i1 %y, TrueDest, UniqueSucc
4244 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
4245 // FalseWeight for PBI * TrueWeight for BI.
4246 MDWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
4247 PredFalseWeight * SuccTrueWeight);
4248 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
4249 MDWeights.push_back(PredFalseWeight * SuccFalseWeight);
4250 }
4251
4252 setFittedBranchWeights(*PBI, MDWeights, /*IsExpected=*/false,
4253 /*ElideAllZero=*/true);
4254
4255 // TODO: If BB is reachable from all paths through PredBlock, then we
4256 // could replace PBI's branch probabilities with BI's.
4257 } else {
4258 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
4260 }
4261
4262 // Now, update the CFG.
4263 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
4264
4265 if (DTU)
4266 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
4267 {DominatorTree::Delete, PredBlock, BB}});
4268
4269 // If BI was a loop latch, it may have had associated loop metadata.
4270 // We need to copy it to the new latch, that is, PBI.
4271 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
4272 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
4273
4274 ValueToValueMapTy VMap; // maps original values to cloned values
4276
4277 Module *M = BB->getModule();
4278
4279 PredBlock->getTerminator()->cloneDebugInfoFrom(BB->getTerminator());
4280 for (DbgVariableRecord &DVR :
4282 RemapDbgRecord(M, &DVR, VMap,
4284 }
4285
4286 // Now that the Cond was cloned into the predecessor basic block,
4287 // or/and the two conditions together.
4288 Value *BICond = VMap[BI->getCondition()];
4289 PBI->setCondition(
4290 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
4291 if (auto *SI = dyn_cast<SelectInst>(PBI->getCondition())) {
4292 if (!MDWeights.empty()) {
4293 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4294 setFittedBranchWeights(*SI, {MDWeights[0], MDWeights[1]},
4295 /*IsExpected=*/false, /*ElideAllZero=*/true);
4296 } else {
4298 }
4299 }
4300
4301 ++NumFoldBranchToCommonDest;
4302 return true;
4303}
4304
4305/// Return if an instruction's type or any of its operands' types are a vector
4306/// type.
4307static bool isVectorOp(Instruction &I) {
4308 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
4309 return U->getType()->isVectorTy();
4310 });
4311}
4312
4313/// If this basic block is simple enough, and if a predecessor branches to us
4314/// and one of our successors, fold the block into the predecessor and use
4315/// logical operations to pick the right destination.
4317 MemorySSAUpdater *MSSAU,
4318 const TargetTransformInfo *TTI,
4319 AssumptionCache *AC,
4320 unsigned BonusInstThreshold) {
4321 BasicBlock *BB = BI->getParent();
4325
4327
4329 Cond->getParent() != BB || !Cond->hasOneUse())
4330 return false;
4331
4332 // Finally, don't infinitely unroll conditional loops.
4333 if (is_contained(successors(BB), BB))
4334 return false;
4335
4336 // With which predecessors will we want to deal with?
4338 for (BasicBlock *PredBlock : predecessors(BB)) {
4339 CondBrInst *PBI = dyn_cast<CondBrInst>(PredBlock->getTerminator());
4340
4341 // Check that we have two conditional branches. If there is a PHI node in
4342 // the common successor, verify that the same value flows in from both
4343 // blocks.
4344 if (!PBI || !safeToMergeTerminators(BI, PBI))
4345 continue;
4346
4347 // Determine if the two branches share a common destination.
4348 BasicBlock *CommonSucc;
4350 bool InvertPredCond;
4351 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
4352 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
4353 else
4354 continue;
4355
4356 // Check the cost of inserting the necessary logic before performing the
4357 // transformation.
4358 if (TTI) {
4359 Type *Ty = BI->getCondition()->getType();
4360 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
4361 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
4362 !isa<CmpInst>(PBI->getCondition())))
4363 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
4364
4366 continue;
4367 }
4368
4369 // Ok, we do want to deal with this predecessor. Record it.
4370 Preds.emplace_back(PredBlock);
4371 }
4372
4373 // If there aren't any predecessors into which we can fold,
4374 // don't bother checking the cost.
4375 if (Preds.empty())
4376 return false;
4377
4378 // Only allow this transformation if computing the condition doesn't involve
4379 // too many instructions and these involved instructions can be executed
4380 // unconditionally. We denote all involved instructions except the condition
4381 // as "bonus instructions", and only allow this transformation when the
4382 // number of the bonus instructions we'll need to create when cloning into
4383 // each predecessor does not exceed a certain threshold.
4384 unsigned NumBonusInsts = 0;
4385 bool SawVectorOp = false;
4386 const unsigned PredCount = Preds.size();
4387 // Speculated instructions will be inserted before the terminator of the
4388 // predecessor. Only handle the simple case of one predecessor.
4389 const Instruction *CtxI =
4390 PredCount == 1 ? Preds[0]->getTerminator() : nullptr;
4391 for (Instruction &I : *BB) {
4392 // Don't check the branch condition comparison itself.
4393 if (&I == Cond)
4394 continue;
4395 // Ignore the terminator.
4397 continue;
4398 // Pseudo probes aren't speculatable but can be dropped on fold.
4400 continue;
4401 // I must be safe to execute unconditionally.
4402 if (!isSafeToSpeculativelyExecute(&I, CtxI, AC))
4403 return false;
4404 SawVectorOp |= isVectorOp(I);
4405
4406 // Account for the cost of duplicating this instruction into each
4407 // predecessor. Ignore free instructions.
4408 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
4410 NumBonusInsts += PredCount;
4411
4412 // Early exits once we reach the limit.
4413 if (NumBonusInsts >
4414 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
4415 return false;
4416 }
4417
4418 auto IsBCSSAUse = [BB, &I](Use &U) {
4419 auto *UI = cast<Instruction>(U.getUser());
4420 if (auto *PN = dyn_cast<PHINode>(UI))
4421 return PN->getIncomingBlock(U) == BB;
4422 return UI->getParent() == BB && I.comesBefore(UI);
4423 };
4424
4425 // Does this instruction require rewriting of uses?
4426 if (!all_of(I.uses(), IsBCSSAUse))
4427 return false;
4428 }
4429 if (NumBonusInsts >
4430 BonusInstThreshold *
4431 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
4432 return false;
4433
4434 // Ok, we have the budget. Perform the transformation.
4435 for (BasicBlock *PredBlock : Preds) {
4436 auto *PBI = cast<CondBrInst>(PredBlock->getTerminator());
4437 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4438 }
4439 return false;
4440}
4441
4442// If there is only one store in BB1 and BB2, return it, otherwise return
4443// nullptr.
4445 StoreInst *S = nullptr;
4446 for (auto *BB : {BB1, BB2}) {
4447 if (!BB)
4448 continue;
4449 for (auto &I : *BB)
4450 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4451 if (S)
4452 // Multiple stores seen.
4453 return nullptr;
4454 else
4455 S = SI;
4456 }
4457 }
4458 return S;
4459}
4460
4462 Value *AlternativeV = nullptr) {
4463 // PHI is going to be a PHI node that allows the value V that is defined in
4464 // BB to be referenced in BB's only successor.
4465 //
4466 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4467 // doesn't matter to us what the other operand is (it'll never get used). We
4468 // could just create a new PHI with an undef incoming value, but that could
4469 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4470 // other PHI. So here we directly look for some PHI in BB's successor with V
4471 // as an incoming operand. If we find one, we use it, else we create a new
4472 // one.
4473 //
4474 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4475 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4476 // where OtherBB is the single other predecessor of BB's only successor.
4477 PHINode *PHI = nullptr;
4478 BasicBlock *Succ = BB->getSingleSuccessor();
4479
4480 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
4481 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
4482 PHI = cast<PHINode>(I);
4483 if (!AlternativeV)
4484 break;
4485
4486 assert(Succ->hasNPredecessors(2));
4487 auto PredI = pred_begin(Succ);
4488 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4489 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
4490 break;
4491 PHI = nullptr;
4492 }
4493 if (PHI)
4494 return PHI;
4495
4496 // If V is not an instruction defined in BB, just return it.
4497 if (!AlternativeV &&
4499 return V;
4500
4501 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
4502 PHI->insertBefore(Succ->begin());
4503 PHI->addIncoming(V, BB);
4504 for (BasicBlock *PredBB : predecessors(Succ))
4505 if (PredBB != BB)
4506 PHI->addIncoming(
4507 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
4508 return PHI;
4509}
4510
4512 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4513 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4514 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4515 // For every pointer, there must be exactly two stores, one coming from
4516 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4517 // store (to any address) in PTB,PFB or QTB,QFB.
4518 // FIXME: We could relax this restriction with a bit more work and performance
4519 // testing.
4520 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
4521 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
4522 if (!PStore || !QStore)
4523 return false;
4524
4525 // Now check the stores are compatible.
4526 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4527 PStore->getOrdering() != QStore->getOrdering() ||
4528 PStore->getSyncScopeID() != QStore->getSyncScopeID() ||
4529 PStore->getValueOperand()->getType() !=
4530 QStore->getValueOperand()->getType())
4531 return false;
4532
4533 // Check that sinking the store won't cause program behavior changes. Sinking
4534 // the store out of the Q blocks won't change any behavior as we're sinking
4535 // from a block to its unconditional successor. But we're moving a store from
4536 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4537 // So we need to check that there are no aliasing loads or stores in
4538 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4539 // operations between PStore and the end of its parent block.
4540 //
4541 // The ideal way to do this is to query AliasAnalysis, but we don't
4542 // preserve AA currently so that is dangerous. Be super safe and just
4543 // check there are no other memory operations at all.
4544 for (auto &I : *QFB->getSinglePredecessor())
4545 if (I.mayReadOrWriteMemory())
4546 return false;
4547 for (auto &I : *QFB)
4548 if (&I != QStore && I.mayReadOrWriteMemory())
4549 return false;
4550 if (QTB)
4551 for (auto &I : *QTB)
4552 if (&I != QStore && I.mayReadOrWriteMemory())
4553 return false;
4554 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4555 I != E; ++I)
4556 if (&*I != PStore && I->mayReadOrWriteMemory())
4557 return false;
4558
4559 // If we're not in aggressive mode, we only optimize if we have some
4560 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4561 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4562 if (!BB)
4563 return true;
4564 // Heuristic: if the block can be if-converted/phi-folded and the
4565 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4566 // thread this store.
4567 InstructionCost Cost = 0;
4568 InstructionCost Budget =
4570 for (auto &I : *BB) {
4571 // Consider terminator instruction to be free.
4572 if (I.isTerminator())
4573 continue;
4574 // If this is one the stores that we want to speculate out of this BB,
4575 // then don't count it's cost, consider it to be free.
4576 if (auto *S = dyn_cast<StoreInst>(&I))
4577 if (llvm::find(FreeStores, S))
4578 continue;
4579 // Else, we have a white-list of instructions that we are ak speculating.
4581 return false; // Not in white-list - not worthwhile folding.
4582 // And finally, if this is a non-free instruction that we are okay
4583 // speculating, ensure that we consider the speculation budget.
4584 Cost +=
4585 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
4586 if (Cost > Budget)
4587 return false; // Eagerly refuse to fold as soon as we're out of budget.
4588 }
4589 assert(Cost <= Budget &&
4590 "When we run out of budget we will eagerly return from within the "
4591 "per-instruction loop.");
4592 return true;
4593 };
4594
4595 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4597 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4598 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4599 return false;
4600
4601 // If PostBB has more than two predecessors, we need to split it so we can
4602 // sink the store.
4603 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4604 // We know that QFB's only successor is PostBB. And QFB has a single
4605 // predecessor. If QTB exists, then its only successor is also PostBB.
4606 // If QTB does not exist, then QFB's only predecessor has a conditional
4607 // branch to QFB and PostBB.
4608 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4609 BasicBlock *NewBB =
4610 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4611 if (!NewBB)
4612 return false;
4613 PostBB = NewBB;
4614 }
4615
4616 // OK, we're going to sink the stores to PostBB. The store has to be
4617 // conditional though, so first create the predicate.
4618 CondBrInst *PBranch =
4620 CondBrInst *QBranch =
4622 Value *PCond = PBranch->getCondition();
4623 Value *QCond = QBranch->getCondition();
4624
4626 PStore->getParent());
4628 QStore->getParent(), PPHI);
4629
4630 IRBuilder<> QB(PostBB->getFirstInsertionPt());
4631
4632 InvertPCond ^= (PStore->getParent() != PTB);
4633 InvertQCond ^= (QStore->getParent() != QTB);
4634 Value *PPred = InvertPCond ? QB.CreateNot(PCond) : PCond;
4635 Value *QPred = InvertQCond ? QB.CreateNot(QCond) : QCond;
4636
4637 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4638
4639 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4640 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4641 /*Unreachable=*/false,
4642 /*BranchWeights=*/nullptr, DTU);
4643 if (hasBranchWeightMD(*PBranch) && hasBranchWeightMD(*QBranch)) {
4644 SmallVector<uint32_t, 2> PWeights, QWeights;
4645 extractBranchWeights(*PBranch, PWeights);
4646 extractBranchWeights(*QBranch, QWeights);
4647 if (InvertPCond)
4648 std::swap(PWeights[0], PWeights[1]);
4649 if (InvertQCond)
4650 std::swap(QWeights[0], QWeights[1]);
4651 auto CombinedWeights = getDisjunctionWeights(PWeights, QWeights);
4653 {CombinedWeights[0], CombinedWeights[1]},
4654 /*IsExpected=*/false, /*ElideAllZero=*/true);
4655 }
4656
4657 QB.SetInsertPoint(T);
4658 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4659 combineMetadataForCSE(QStore, PStore, true);
4660 SI->copyMetadata(*QStore);
4661 // Update any dbg.assign intrinsics to track the merged value (QPHI) instead
4662 // of the original constant values, likely making these identical.
4663 for (auto *DbgAssign : at::getDVRAssignmentMarkers(SI)) {
4664 if (llvm::is_contained(DbgAssign->location_ops(),
4665 PStore->getValueOperand()))
4666 DbgAssign->replaceVariableLocationOp(PStore->getValueOperand(), QPHI);
4667 if (llvm::is_contained(DbgAssign->location_ops(),
4668 QStore->getValueOperand()))
4669 DbgAssign->replaceVariableLocationOp(QStore->getValueOperand(), QPHI);
4670 }
4671
4672 // Choose the minimum alignment. If we could prove both stores execute, we
4673 // could use biggest one. In this case, though, we only know that one of the
4674 // stores executes. And we don't know it's safe to take the alignment from a
4675 // store that doesn't execute.
4676 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4677
4678 if (QStore->isAtomic())
4679 SI->setAtomic(QStore->getOrdering(), QStore->getSyncScopeID());
4680
4681 QStore->eraseFromParent();
4682 PStore->eraseFromParent();
4683
4684 return true;
4685}
4686
4688 DomTreeUpdater *DTU, const DataLayout &DL,
4689 const TargetTransformInfo &TTI) {
4690 // The intention here is to find diamonds or triangles (see below) where each
4691 // conditional block contains a store to the same address. Both of these
4692 // stores are conditional, so they can't be unconditionally sunk. But it may
4693 // be profitable to speculatively sink the stores into one merged store at the
4694 // end, and predicate the merged store on the union of the two conditions of
4695 // PBI and QBI.
4696 //
4697 // This can reduce the number of stores executed if both of the conditions are
4698 // true, and can allow the blocks to become small enough to be if-converted.
4699 // This optimization will also chain, so that ladders of test-and-set
4700 // sequences can be if-converted away.
4701 //
4702 // We only deal with simple diamonds or triangles:
4703 //
4704 // PBI or PBI or a combination of the two
4705 // / \ | \
4706 // PTB PFB | PFB
4707 // \ / | /
4708 // QBI QBI
4709 // / \ | \
4710 // QTB QFB | QFB
4711 // \ / | /
4712 // PostBB PostBB
4713 //
4714 // We model triangles as a type of diamond with a nullptr "true" block.
4715 // Triangles are canonicalized so that the fallthrough edge is represented by
4716 // a true condition, as in the diagram above.
4717 BasicBlock *PTB = PBI->getSuccessor(0);
4718 BasicBlock *PFB = PBI->getSuccessor(1);
4719 BasicBlock *QTB = QBI->getSuccessor(0);
4720 BasicBlock *QFB = QBI->getSuccessor(1);
4721 BasicBlock *PostBB = QFB->getSingleSuccessor();
4722
4723 // Make sure we have a good guess for PostBB. If QTB's only successor is
4724 // QFB, then QFB is a better PostBB.
4725 if (QTB->getSingleSuccessor() == QFB)
4726 PostBB = QFB;
4727
4728 // If we couldn't find a good PostBB, stop.
4729 if (!PostBB)
4730 return false;
4731
4732 bool InvertPCond = false, InvertQCond = false;
4733 // Canonicalize fallthroughs to the true branches.
4734 if (PFB == QBI->getParent()) {
4735 std::swap(PFB, PTB);
4736 InvertPCond = true;
4737 }
4738 if (QFB == PostBB) {
4739 std::swap(QFB, QTB);
4740 InvertQCond = true;
4741 }
4742
4743 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4744 // and QFB may not. Model fallthroughs as a nullptr block.
4745 if (PTB == QBI->getParent())
4746 PTB = nullptr;
4747 if (QTB == PostBB)
4748 QTB = nullptr;
4749
4750 // Legality bailouts. We must have at least the non-fallthrough blocks and
4751 // the post-dominating block, and the non-fallthroughs must only have one
4752 // predecessor.
4753 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4754 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4755 };
4756 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4757 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4758 return false;
4759 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4760 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4761 return false;
4762 if (!QBI->getParent()->hasNUses(2))
4763 return false;
4764
4765 // OK, this is a sequence of two diamonds or triangles.
4766 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4767 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4768 for (auto *BB : {PTB, PFB}) {
4769 if (!BB)
4770 continue;
4771 for (auto &I : *BB)
4773 PStoreAddresses.insert(SI->getPointerOperand());
4774 }
4775 for (auto *BB : {QTB, QFB}) {
4776 if (!BB)
4777 continue;
4778 for (auto &I : *BB)
4780 QStoreAddresses.insert(SI->getPointerOperand());
4781 }
4782
4783 set_intersect(PStoreAddresses, QStoreAddresses);
4784 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4785 // clear what it contains.
4786 auto &CommonAddresses = PStoreAddresses;
4787
4788 bool Changed = false;
4789 for (auto *Address : CommonAddresses)
4790 Changed |=
4791 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4792 InvertPCond, InvertQCond, DTU, DL, TTI);
4793 return Changed;
4794}
4795
4796/// If the previous block ended with a widenable branch, determine if reusing
4797/// the target block is profitable and legal. This will have the effect of
4798/// "widening" PBI, but doesn't require us to reason about hosting safety.
4800 DomTreeUpdater *DTU) {
4801 // TODO: This can be generalized in two important ways:
4802 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4803 // values from the PBI edge.
4804 // 2) We can sink side effecting instructions into BI's fallthrough
4805 // successor provided they doesn't contribute to computation of
4806 // BI's condition.
4807 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4808 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4809 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4810 !BI->getParent()->getSinglePredecessor())
4811 return false;
4812 if (!IfFalseBB->phis().empty())
4813 return false; // TODO
4814 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4815 // may undo the transform done here.
4816 // TODO: There might be a more fine-grained solution to this.
4817 if (!llvm::succ_empty(IfFalseBB))
4818 return false;
4819 // Use lambda to lazily compute expensive condition after cheap ones.
4820 auto NoSideEffects = [](BasicBlock &BB) {
4821 return llvm::none_of(BB, [](const Instruction &I) {
4822 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4823 });
4824 };
4825 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4826 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4827 NoSideEffects(*BI->getParent())) {
4828 auto *OldSuccessor = BI->getSuccessor(1);
4829 OldSuccessor->removePredecessor(BI->getParent());
4830 BI->setSuccessor(1, IfFalseBB);
4831 if (DTU)
4832 DTU->applyUpdates(
4833 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4834 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4835 return true;
4836 }
4837 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4838 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4839 NoSideEffects(*BI->getParent())) {
4840 auto *OldSuccessor = BI->getSuccessor(0);
4841 OldSuccessor->removePredecessor(BI->getParent());
4842 BI->setSuccessor(0, IfFalseBB);
4843 if (DTU)
4844 DTU->applyUpdates(
4845 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4846 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4847 return true;
4848 }
4849 return false;
4850}
4851
4852/// If we have a conditional branch as a predecessor of another block,
4853/// this function tries to simplify it. We know
4854/// that PBI and BI are both conditional branches, and BI is in one of the
4855/// successor blocks of PBI - PBI branches to BI.
4857 DomTreeUpdater *DTU,
4858 const DataLayout &DL,
4859 const TargetTransformInfo &TTI) {
4860 BasicBlock *BB = BI->getParent();
4861
4862 // If this block ends with a branch instruction, and if there is a
4863 // predecessor that ends on a branch of the same condition, make
4864 // this conditional branch redundant.
4865 if (PBI->getCondition() == BI->getCondition() &&
4866 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4867 // Okay, the outcome of this conditional branch is statically
4868 // knowable. If this block had a single pred, handle specially, otherwise
4869 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4870 if (BB->getSinglePredecessor()) {
4871 // Turn this into a branch on constant.
4872 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4873 BI->setCondition(
4874 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4875 return true; // Nuke the branch on constant.
4876 }
4877 }
4878
4879 // If the previous block ended with a widenable branch, determine if reusing
4880 // the target block is profitable and legal. This will have the effect of
4881 // "widening" PBI, but doesn't require us to reason about hosting safety.
4882 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4883 return true;
4884
4885 // If both branches are conditional and both contain stores to the same
4886 // address, remove the stores from the conditionals and create a conditional
4887 // merged store at the end.
4888 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4889 return true;
4890
4891 // If this is a conditional branch in an empty block, and if any
4892 // predecessors are a conditional branch to one of our destinations,
4893 // fold the conditions into logical ops and one cond br.
4894
4895 // Ignore dbg intrinsics.
4896 if (&*BB->begin() != BI)
4897 return false;
4898
4899 int PBIOp, BIOp;
4900 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4901 PBIOp = 0;
4902 BIOp = 0;
4903 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4904 PBIOp = 0;
4905 BIOp = 1;
4906 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4907 PBIOp = 1;
4908 BIOp = 0;
4909 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4910 PBIOp = 1;
4911 BIOp = 1;
4912 } else {
4913 return false;
4914 }
4915
4916 // Check to make sure that the other destination of this branch
4917 // isn't BB itself. If so, this is an infinite loop that will
4918 // keep getting unwound.
4919 if (PBI->getSuccessor(PBIOp) == BB)
4920 return false;
4921
4922 // If predecessor's branch probability to BB is too low don't merge branches.
4923 SmallVector<uint32_t, 2> PredWeights;
4924 if (!PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4925 extractBranchWeights(*PBI, PredWeights) &&
4926 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4927
4929 PredWeights[PBIOp],
4930 static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4931
4932 BranchProbability Likely = TTI.getPredictableBranchThreshold();
4933 if (CommonDestProb >= Likely)
4934 return false;
4935 }
4936
4937 // Do not perform this transformation if it would require
4938 // insertion of a large number of select instructions. For targets
4939 // without predication/cmovs, this is a big pessimization.
4940
4941 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4942 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4943 unsigned NumPhis = 0;
4944 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4945 ++II, ++NumPhis) {
4946 if (NumPhis > 2) // Disable this xform.
4947 return false;
4948 }
4949
4950 // Finally, if everything is ok, fold the branches to logical ops.
4951 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4952
4953 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4954 << "AND: " << *BI->getParent());
4955
4957
4958 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4959 // branch in it, where one edge (OtherDest) goes back to itself but the other
4960 // exits. We don't *know* that the program avoids the infinite loop
4961 // (even though that seems likely). If we do this xform naively, we'll end up
4962 // recursively unpeeling the loop. Since we know that (after the xform is
4963 // done) that the block *is* infinite if reached, we just make it an obviously
4964 // infinite loop with no cond branch.
4965 if (OtherDest == BB) {
4966 // Insert it at the end of the function, because it's either code,
4967 // or it won't matter if it's hot. :)
4968 BasicBlock *InfLoopBlock =
4969 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4970 UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
4971 if (DTU)
4972 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4973 OtherDest = InfLoopBlock;
4974 }
4975
4976 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4977
4978 // BI may have other predecessors. Because of this, we leave
4979 // it alone, but modify PBI.
4980
4981 // Make sure we get to CommonDest on True&True directions.
4982 Value *PBICond = PBI->getCondition();
4983 IRBuilder<NoFolder> Builder(PBI);
4984 if (PBIOp)
4985 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4986
4987 Value *BICond = BI->getCondition();
4988 if (BIOp)
4989 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4990
4991 // Merge the conditions.
4992 Value *Cond =
4993 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4994
4995 // Modify PBI to branch on the new condition to the new dests.
4996 PBI->setCondition(Cond);
4997 PBI->setSuccessor(0, CommonDest);
4998 PBI->setSuccessor(1, OtherDest);
4999
5000 if (DTU) {
5001 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
5002 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
5003
5004 DTU->applyUpdates(Updates);
5005 }
5006
5007 // Update branch weight for PBI.
5008 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
5009 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
5010 bool HasWeights =
5011 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
5012 SuccTrueWeight, SuccFalseWeight);
5013 if (HasWeights) {
5014 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
5015 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
5016 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
5017 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
5018 // The weight to CommonDest should be PredCommon * SuccTotal +
5019 // PredOther * SuccCommon.
5020 // The weight to OtherDest should be PredOther * SuccOther.
5021 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
5022 PredOther * SuccCommon,
5023 PredOther * SuccOther};
5024
5025 setFittedBranchWeights(*PBI, NewWeights, /*IsExpected=*/false,
5026 /*ElideAllZero=*/true);
5027 // Cond may be a select instruction with the first operand set to "true", or
5028 // the second to "false" (see how createLogicalOp works for `and` and `or`)
5029 if (auto *SI = dyn_cast<SelectInst>(Cond)) {
5030 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
5031 // The select is predicated on PBICond
5032 assert(SI->getCondition() == PBICond);
5033 // The corresponding probabilities are what was referred to above as
5034 // PredCommon and PredOther.
5035 setFittedBranchWeights(*SI, {PredCommon, PredOther},
5036 /*IsExpected=*/false, /*ElideAllZero=*/true);
5037 }
5038 }
5039
5040 // OtherDest may have phi nodes. If so, add an entry from PBI's
5041 // block that are identical to the entries for BI's block.
5042 addPredecessorToBlock(OtherDest, PBI->getParent(), BB);
5043
5044 // We know that the CommonDest already had an edge from PBI to
5045 // it. If it has PHIs though, the PHIs may have different
5046 // entries for BB and PBI's BB. If so, insert a select to make
5047 // them agree.
5048 for (PHINode &PN : CommonDest->phis()) {
5049 Value *BIV = PN.getIncomingValueForBlock(BB);
5050 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
5051 Value *PBIV = PN.getIncomingValue(PBBIdx);
5052 if (BIV != PBIV) {
5053 // Insert a select in PBI to pick the right value.
5055 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
5056 PN.setIncomingValue(PBBIdx, NV);
5057 // The select has the same condition as PBI, in the same BB. The
5058 // probabilities don't change.
5059 if (HasWeights) {
5060 uint64_t TrueWeight = PBIOp ? PredFalseWeight : PredTrueWeight;
5061 uint64_t FalseWeight = PBIOp ? PredTrueWeight : PredFalseWeight;
5062 setFittedBranchWeights(*NV, {TrueWeight, FalseWeight},
5063 /*IsExpected=*/false, /*ElideAllZero=*/true);
5064 }
5065 }
5066 }
5067
5068 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
5069 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
5070
5071 // This basic block is probably dead. We know it has at least
5072 // one fewer predecessor.
5073 return true;
5074}
5075
5076// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
5077// true or to FalseBB if Cond is false.
5078// Takes care of updating the successors and removing the old terminator.
5079// Also makes sure not to introduce new successors by assuming that edges to
5080// non-successor TrueBBs and FalseBBs aren't reachable.
5081bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
5082 Value *Cond, BasicBlock *TrueBB,
5083 BasicBlock *FalseBB,
5084 uint32_t TrueWeight,
5085 uint32_t FalseWeight) {
5086 auto *BB = OldTerm->getParent();
5087 // Remove any superfluous successor edges from the CFG.
5088 // First, figure out which successors to preserve.
5089 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
5090 // successor.
5091 BasicBlock *KeepEdge1 = TrueBB;
5092 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
5093
5094 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
5095
5096 // Then remove the rest.
5097 for (BasicBlock *Succ : successors(OldTerm)) {
5098 // Make sure only to keep exactly one copy of each edge.
5099 if (Succ == KeepEdge1)
5100 KeepEdge1 = nullptr;
5101 else if (Succ == KeepEdge2)
5102 KeepEdge2 = nullptr;
5103 else {
5104 Succ->removePredecessor(BB,
5105 /*KeepOneInputPHIs=*/true);
5106
5107 if (Succ != TrueBB && Succ != FalseBB)
5108 RemovedSuccessors.insert(Succ);
5109 }
5110 }
5111
5112 IRBuilder<> Builder(OldTerm);
5113 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
5114
5115 // Insert an appropriate new terminator.
5116 if (!KeepEdge1 && !KeepEdge2) {
5117 if (TrueBB == FalseBB) {
5118 // We were only looking for one successor, and it was present.
5119 // Create an unconditional branch to it.
5120 Builder.CreateBr(TrueBB);
5121 } else {
5122 // We found both of the successors we were looking for.
5123 // Create a conditional branch sharing the condition of the select.
5124 CondBrInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
5125 setBranchWeights(*NewBI, {TrueWeight, FalseWeight},
5126 /*IsExpected=*/false, /*ElideAllZero=*/true);
5127 }
5128 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
5129 // Neither of the selected blocks were successors, so this
5130 // terminator must be unreachable.
5131 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
5132 } else {
5133 // One of the selected values was a successor, but the other wasn't.
5134 // Insert an unconditional branch to the one that was found;
5135 // the edge to the one that wasn't must be unreachable.
5136 if (!KeepEdge1) {
5137 // Only TrueBB was found.
5138 Builder.CreateBr(TrueBB);
5139 } else {
5140 // Only FalseBB was found.
5141 Builder.CreateBr(FalseBB);
5142 }
5143 }
5144
5146
5147 if (DTU) {
5148 SmallVector<DominatorTree::UpdateType, 2> Updates;
5149 Updates.reserve(RemovedSuccessors.size());
5150 for (auto *RemovedSuccessor : RemovedSuccessors)
5151 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
5152 DTU->applyUpdates(Updates);
5153 }
5154
5155 return true;
5156}
5157
5158// Folds switch(select(icmp eq X, C, K, X)) into switch(X), retargeting
5159// (or adding) the case for C to wherever K currently dispatches to:
5160// %cmp = icmp eq T %x, C
5161// %key = select i1 %cmp, T K, T %x
5162// switch T %key, label %default [ T K, label %case_k ... ]
5163// becomes
5164// switch T %x, label %default [ T C, label %case_k
5165// T K, label %case_k ... ]
5166bool SimplifyCFGOpt::simplifySwitchOnSelectRemap(SwitchInst *SI,
5167 SelectInst *Select, Value *X,
5168 ConstantInt *C, bool Negate) {
5169 Value *TrueVal = Select->getTrueValue();
5170 Value *FalseVal = Select->getFalseValue();
5171 if (Negate)
5172 std::swap(TrueVal, FalseVal);
5173 if (FalseVal != X)
5174 return false;
5175 auto *K = dyn_cast<ConstantInt>(TrueVal);
5176 if (!K)
5177 return false;
5178
5179 BasicBlock *DestFork = SI->findCaseValue(K)->getCaseSuccessor();
5180 auto CaseC = SI->findCaseValue(C);
5181 bool IsDefault = CaseC == SI->case_default();
5182 // Save before setSuccessor()/addCase() change it.
5183 BasicBlock *OldDest = CaseC->getCaseSuccessor();
5184 BasicBlock *BB = SI->getParent();
5185
5186 // Switch on X first: removePredecessor() below may fold X away if it is a
5187 // PHI in OldDest, and the RAUW must update the switch condition too.
5188 SI->setCondition(X);
5189
5190 if (OldDest != DestFork) {
5191 if (!IsDefault)
5192 OldDest->removePredecessor(BB);
5193 if (IsDefault)
5194 SI->addCase(C, DestFork);
5195 else
5196 CaseC->setSuccessor(DestFork);
5197 // Not a new edge (BB->DestFork exists via K), just adding the PHI
5198 // entry.
5199 addPredecessorToBlock(DestFork, BB, BB);
5200
5201 if (!IsDefault) {
5202 // Edge to OldDest is gone only if nothing else still uses it.
5203 bool OldDestStillTargeted = any_of(
5204 successors(SI), [&](BasicBlock *Succ) { return Succ == OldDest; });
5205 if (DTU && !OldDestStillTargeted)
5206 DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
5207 }
5208
5209 // Update the profile information on the switch if we had a profile
5210 // for both it and the select instruction.
5211 SmallVector<uint32_t> SwitchWeights;
5212 bool SwitchHasBranchWeights = extractBranchWeights(*SI, SwitchWeights);
5213 // If we add a case, ensure the length of the branch weights list matches
5214 // to make iterating over them easier later.
5215 if (IsDefault)
5216 SwitchWeights.push_back(0);
5219 bool SelectHasBranchWeights =
5221 uint64_t SelectTotalWeight = SelectTrueWeight + SelectFalseWeight;
5222 if (Negate)
5224 if (SwitchHasBranchWeights && SelectHasBranchWeights &&
5226 // We update the branch weights by subtracting P(x=C) from the probability
5227 // of case K in the switch (what C redirect to before the transformation),
5228 // plugging the probability for case C into the switch (which we derive
5229 // from the select), and ensuring everything is scaled to have a common
5230 // denominator.
5231 uint64_t SwitchTotalWeight = sum_of(SwitchWeights, uint64_t{0});
5232 SmallVector<uint64_t> NewSwitchWeights;
5233 NewSwitchWeights.reserve(SwitchWeights.size());
5234 NewSwitchWeights.push_back(SwitchWeights[0] * SelectTotalWeight);
5235 for (const auto &[SwitchCase, SwitchWeight] :
5236 zip(SI->cases(), drop_begin(SwitchWeights))) {
5237 if (SwitchCase.getCaseValue() == C) {
5238 NewSwitchWeights.push_back(SwitchTotalWeight * SelectTrueWeight);
5239 } else if (SwitchCase.getCaseValue() == K) {
5240 // In reality, P(key=K) > P(x=C) should always hold, but explicitly
5241 // guard against bad profiles here to prevent underflow by saturating
5242 // to zero.
5243 uint64_t ProbabilityKeyEqualsK = SwitchWeight * SelectTotalWeight;
5244 uint64_t ProbabilityXEqualsC = SelectTrueWeight * SwitchTotalWeight;
5245 uint64_t ProbabilityXEqualsK =
5246 ProbabilityKeyEqualsK > ProbabilityXEqualsC
5247 ? ProbabilityKeyEqualsK - ProbabilityXEqualsC
5248 : 0;
5249 NewSwitchWeights.push_back(ProbabilityXEqualsK);
5250 } else {
5251 NewSwitchWeights.push_back(SwitchWeight * SelectTotalWeight);
5252 }
5253 }
5254 setFittedBranchWeights(*SI, NewSwitchWeights, /*IsExpected=*/false);
5255 } else if (SwitchHasBranchWeights) {
5256 // If we only have branch weights on the switch, we cannot reconstruct
5257 // branch weights correctly, so mark them as unknown if the function has
5258 // a profile count. Reset the branch weights first to ensure we remove
5259 // the now invalid branch weights if the function is not otherwise
5260 // profiled.
5261 SI->setMetadata(LLVMContext::MD_prof, nullptr);
5263 }
5264 }
5265
5266 // The compare/select are now dead.
5268 return true;
5269}
5270
5271// Replaces
5272// (switch (select cond, X, Y)) on constant X, Y
5273// with a branch - conditional if X and Y lead to distinct BBs,
5274// unconditional otherwise.
5275bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
5276 SelectInst *Select) {
5277 CmpPredicate Pred;
5278 Value *X;
5279 ConstantInt *C;
5280 if (Select->hasOneUse() &&
5281 match(Select->getCondition(),
5284 simplifySwitchOnSelectRemap(SI, Select, X, C, Pred == ICmpInst::ICMP_NE))
5285 return true;
5286
5287 // Check for constant integer values in the select.
5288 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
5289 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
5290 if (!TrueVal || !FalseVal)
5291 return false;
5292
5293 // Find the relevant condition and destinations.
5294 Value *Condition = Select->getCondition();
5295 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
5296 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
5297
5298 // Get weight for TrueBB and FalseBB.
5299 uint32_t TrueWeight = 0, FalseWeight = 0;
5300 SmallVector<uint64_t, 8> Weights;
5301 bool HasWeights = hasBranchWeightMD(*SI);
5302 if (HasWeights) {
5303 getBranchWeights(SI, Weights);
5304 if (Weights.size() == 1 + SI->getNumCases()) {
5305 TrueWeight =
5306 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
5307 FalseWeight =
5308 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
5309 }
5310 }
5311
5312 // Perform the actual simplification.
5313 return simplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
5314 FalseWeight);
5315}
5316
5317// Replaces
5318// (indirectbr (select cond, blockaddress(@fn, BlockA),
5319// blockaddress(@fn, BlockB)))
5320// with
5321// (br cond, BlockA, BlockB).
5322bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
5323 SelectInst *SI) {
5324 // Check that both operands of the select are block addresses.
5325 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
5326 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
5327 if (!TBA || !FBA)
5328 return false;
5329
5330 // Extract the actual blocks.
5331 BasicBlock *TrueBB = TBA->getBasicBlock();
5332 BasicBlock *FalseBB = FBA->getBasicBlock();
5333
5334 // The select's profile becomes the profile of the conditional branch that
5335 // replaces the indirect branch.
5336 SmallVector<uint32_t> SelectBranchWeights(2);
5337 extractBranchWeights(*SI, SelectBranchWeights);
5338 // Perform the actual simplification.
5339 return simplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
5340 SelectBranchWeights[0],
5341 SelectBranchWeights[1]);
5342}
5343
5344/// This is called when we find an icmp instruction
5345/// (a seteq/setne with a constant) as the only instruction in a
5346/// block that ends with an uncond branch. We are looking for a very specific
5347/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
5348/// this case, we merge the first two "or's of icmp" into a switch, but then the
5349/// default value goes to an uncond block with a seteq in it, we get something
5350/// like:
5351///
5352/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
5353/// DEFAULT:
5354/// %tmp = icmp eq i8 %A, 92
5355/// br label %end
5356/// end:
5357/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
5358///
5359/// We prefer to split the edge to 'end' so that there is a true/false entry to
5360/// the PHI, merging the third icmp into the switch.
5361bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
5362 ICmpInst *ICI, IRBuilder<> &Builder) {
5363 // Select == nullptr means we assume that there is a hidden no-op select
5364 // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...`
5365 return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, nullptr, Builder);
5366}
5367
5368/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic
5369/// case. This is called when we find an icmp instruction (a seteq/setne with a
5370/// constant) and its following select instruction as the only TWO instructions
5371/// in a block that ends with an uncond branch. We are looking for a very
5372/// specific pattern that occurs when "
5373/// if (A == 1) return C1;
5374/// if (A == 2) return C2;
5375/// if (A < 3) return C3;
5376/// return C4;
5377/// " gets simplified. In this case, we merge the first two "branches of icmp"
5378/// into a switch, but then the default value goes to an uncond block with a lt
5379/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2".
5380/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might
5381/// get something like:
5382///
5383/// case1:
5384/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ]
5385/// case2:
5386/// br label %end
5387/// DEFAULT:
5388/// %tmp = icmp eq i8 %A, 2
5389/// %val = select i1 %tmp, i8 C3, i8 C4
5390/// br label %end
5391/// end:
5392/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ]
5393///
5394/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4
5395/// to the PHI, merging the icmp & select into the switch, as follows:
5396///
5397/// case1:
5398/// switch i8 %A, label %DEFAULT [
5399/// i8 0, label %end
5400/// i8 1, label %case2
5401/// i8 2, label %case3
5402/// ]
5403/// case2:
5404/// br label %end
5405/// case3:
5406/// br label %end
5407/// DEFAULT:
5408/// br label %end
5409/// end:
5410/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT]
5411bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
5412 ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) {
5413 BasicBlock *BB = ICI->getParent();
5414
5415 // If the block has any PHIs in it or the icmp/select has multiple uses, it is
5416 // too complex.
5417 /// TODO: support multi-phis in succ BB of select's BB.
5418 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse() ||
5419 (Select && !Select->hasOneUse()))
5420 return false;
5421
5422 // The pattern we're looking for is where our only predecessor is a switch on
5423 // 'V' and this block is the default case for the switch. In this case we can
5424 // fold the compared value into the switch to simplify things.
5426 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
5427 return false;
5428
5429 Value *IcmpCond;
5430 ConstantInt *NewCaseVal;
5431 CmpPredicate Predicate;
5432
5433 // Match icmp X, C
5434 if (!match(ICI,
5435 m_ICmp(Predicate, m_Value(IcmpCond), m_ConstantInt(NewCaseVal))))
5436 return false;
5437
5438 Value *SelectCond, *SelectTrueVal, *SelectFalseVal;
5440 if (!Select) {
5441 // If Select == nullptr, we can assume that there is a hidden no-op select
5442 // just after icmp
5443 SelectCond = ICI;
5444 SelectTrueVal = Builder.getTrue();
5445 SelectFalseVal = Builder.getFalse();
5446 User = ICI->user_back();
5447 } else {
5448 SelectCond = Select->getCondition();
5449 // Check if the select condition is the same as the icmp condition.
5450 if (SelectCond != ICI)
5451 return false;
5452 SelectTrueVal = Select->getTrueValue();
5453 SelectFalseVal = Select->getFalseValue();
5454 User = Select->user_back();
5455 }
5456
5457 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
5458 if (SI->getCondition() != IcmpCond)
5459 return false;
5460
5461 // If BB is reachable on a non-default case, then we simply know the value of
5462 // V in this block. Substitute it and constant fold the icmp instruction
5463 // away.
5464 if (SI->getDefaultDest() != BB) {
5465 ConstantInt *VVal = SI->findCaseDest(BB);
5466 assert(VVal && "Should have a unique destination value");
5467 ICI->setOperand(0, VVal);
5468
5469 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
5470 ICI->replaceAllUsesWith(V);
5471 ICI->eraseFromParent();
5472 }
5473 // BB is now empty, so it is likely to simplify away.
5474 return requestResimplify();
5475 }
5476
5477 // Ok, the block is reachable from the default dest. If the constant we're
5478 // comparing exists in one of the other edges, then we can constant fold ICI
5479 // and zap it.
5480 if (SI->findCaseValue(NewCaseVal) != SI->case_default()) {
5481 Value *V;
5482 if (Predicate == ICmpInst::ICMP_EQ)
5484 else
5486
5487 ICI->replaceAllUsesWith(V);
5488 ICI->eraseFromParent();
5489 // BB is now empty, so it is likely to simplify away.
5490 return requestResimplify();
5491 }
5492
5493 // The use of the select has to be in the 'end' block, by the only PHI node in
5494 // the block.
5495 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
5496 PHINode *PHIUse = dyn_cast<PHINode>(User);
5497 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
5499 return false;
5500
5501 // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new
5502 // edge gets SelectTrueVal in the PHI.
5503 Value *DefaultCst = SelectFalseVal;
5504 Value *NewCst = SelectTrueVal;
5505
5506 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
5507 std::swap(DefaultCst, NewCst);
5508
5509 // Replace Select (which is used by the PHI for the default value) with
5510 // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE.
5511 if (Select) {
5512 Select->replaceAllUsesWith(DefaultCst);
5513 Select->eraseFromParent();
5514 } else {
5515 ICI->replaceAllUsesWith(DefaultCst);
5516 }
5517 ICI->eraseFromParent();
5518
5519 SmallVector<DominatorTree::UpdateType, 2> Updates;
5520
5521 // Okay, the switch goes to this block on a default value. Add an edge from
5522 // the switch to the merge point on the compared value.
5523 BasicBlock *NewBB =
5524 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
5525 {
5526 SwitchInstProfUpdateWrapper SIW(*SI);
5527 auto W0 = SIW.getSuccessorWeight(0);
5529 if (W0) {
5530 NewW = ((uint64_t(*W0) + 1) >> 1);
5531 SIW.setSuccessorWeight(0, *NewW);
5532 }
5533 SIW.addCase(NewCaseVal, NewBB, NewW);
5534 if (DTU)
5535 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
5536 }
5537
5538 // NewBB branches to the phi block, add the uncond branch and the phi entry.
5539 Builder.SetInsertPoint(NewBB);
5540 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
5541 Builder.CreateBr(SuccBlock);
5542 PHIUse->addIncoming(NewCst, NewBB);
5543 if (DTU) {
5544 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
5545 DTU->applyUpdates(Updates);
5546 }
5547 return true;
5548}
5549
5550/// Check to see if it is branching on an or/and chain of icmp instructions, and
5551/// fold it into a switch instruction if so.
5552bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
5553 IRBuilder<> &Builder,
5554 const DataLayout &DL) {
5556 if (!Cond)
5557 return false;
5558
5559 // Change br (X == 0 | X == 1), T, F into a switch instruction.
5560 // If this is a bunch of seteq's or'd together, or if it's a bunch of
5561 // 'setne's and'ed together, collect them.
5562
5563 // Try to gather values from a chain of and/or to be turned into a switch
5564 ConstantComparesGatherer ConstantCompare(Cond, DL);
5565 // Unpack the result
5566 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
5567 Value *CompVal = ConstantCompare.CompValue;
5568 unsigned UsedICmps = ConstantCompare.UsedICmps;
5569 Value *ExtraCase = ConstantCompare.Extra;
5570 bool TrueWhenEqual = ConstantCompare.IsEq;
5571
5572 // If we didn't have a multiply compared value, fail.
5573 if (!CompVal)
5574 return false;
5575
5576 // Avoid turning single icmps into a switch.
5577 if (UsedICmps <= 1)
5578 return false;
5579
5580 // There might be duplicate constants in the list, which the switch
5581 // instruction can't handle, remove them now.
5583 Values.erase(llvm::unique(Values), Values.end());
5584
5585 // If Extra was used, we require at least two switch values to do the
5586 // transformation. A switch with one value is just a conditional branch.
5587 if (ExtraCase && Values.size() < 2)
5588 return false;
5589
5590 SmallVector<uint32_t> BranchWeights;
5591 const bool HasProfile = extractBranchWeights(*BI, BranchWeights);
5592
5593 // Figure out which block is which destination.
5594 BasicBlock *DefaultBB = BI->getSuccessor(1);
5595 BasicBlock *EdgeBB = BI->getSuccessor(0);
5596 if (!TrueWhenEqual) {
5597 std::swap(DefaultBB, EdgeBB);
5598 if (HasProfile)
5599 std::swap(BranchWeights[0], BranchWeights[1]);
5600 }
5601
5602 BasicBlock *BB = BI->getParent();
5603
5604 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
5605 << " cases into SWITCH. BB is:\n"
5606 << *BB);
5607
5608 SmallVector<DominatorTree::UpdateType, 2> Updates;
5609
5610 // If there are any extra values that couldn't be folded into the switch
5611 // then we evaluate them with an explicit branch first. Split the block
5612 // right before the condbr to handle it.
5613 if (ExtraCase) {
5614 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
5615 /*MSSAU=*/nullptr, "switch.early.test");
5616
5617 // Remove the uncond branch added to the old block.
5618 Instruction *OldTI = BB->getTerminator();
5619 Builder.SetInsertPoint(OldTI);
5620
5621 // There can be an unintended UB if extra values are Poison. Before the
5622 // transformation, extra values may not be evaluated according to the
5623 // condition, and it will not raise UB. But after transformation, we are
5624 // evaluating extra values before checking the condition, and it will raise
5625 // UB. It can be solved by adding freeze instruction to extra values.
5626 AssumptionCache *AC = Options.AC;
5627
5628 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
5629 ExtraCase = Builder.CreateFreeze(ExtraCase);
5630
5631 // We don't have any info about this condition.
5632 auto *Br = TrueWhenEqual ? Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB)
5633 : Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
5635
5636 OldTI->eraseFromParent();
5637
5638 if (DTU)
5639 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
5640
5641 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
5642 // for the edge we just added.
5643 addPredecessorToBlock(EdgeBB, BB, NewBB);
5644
5645 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
5646 << "\nEXTRABB = " << *BB);
5647 BB = NewBB;
5648 }
5649
5650 Builder.SetInsertPoint(BI);
5651 // Convert pointer to int before we switch.
5652 if (CompVal->getType()->isPointerTy()) {
5653 assert(!DL.hasUnstableRepresentation(CompVal->getType()) &&
5654 "Should not end up here with unstable pointers");
5655 CompVal = Builder.CreatePtrToInt(
5656 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
5657 }
5658
5659 // Check if we can represent the values as a contiguous range. If so, we use a
5660 // range check + conditional branch instead of a switch.
5661 if (Values.front()->getValue() - Values.back()->getValue() ==
5662 Values.size() - 1) {
5663 ConstantRange RangeToCheck = ConstantRange::getNonEmpty(
5664 Values.back()->getValue(), Values.front()->getValue() + 1);
5665 APInt Offset, RHS;
5666 ICmpInst::Predicate Pred;
5667 RangeToCheck.getEquivalentICmp(Pred, RHS, Offset);
5668 Value *X = CompVal;
5669 if (!Offset.isZero())
5670 X = Builder.CreateAdd(X, ConstantInt::get(CompVal->getType(), Offset));
5671 Value *Cond =
5672 Builder.CreateICmp(Pred, X, ConstantInt::get(CompVal->getType(), RHS));
5673 CondBrInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
5674 if (HasProfile)
5675 setBranchWeights(*NewBI, BranchWeights, /*IsExpected=*/false);
5676 else
5678 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5679 NewBI->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5680 // We don't need to update PHI nodes since we don't add any new edges.
5681 } else {
5682 // Create the new switch instruction now.
5683 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
5684 if (MDNode *Unpredictable = BI->getMetadata(LLVMContext::MD_unpredictable))
5685 New->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
5686 if (HasProfile) {
5687 // We know the weight of the default case. We don't know the weight of the
5688 // other cases, but rather than completely lose profiling info, we split
5689 // the remaining probability equally over them.
5690 SmallVector<uint32_t> NewWeights(Values.size() + 1);
5691 NewWeights[0] = BranchWeights[1]; // this is the default, and we swapped
5692 // if TrueWhenEqual.
5693 for (auto &V : drop_begin(NewWeights))
5694 V = BranchWeights[0] / Values.size();
5695 setBranchWeights(*New, NewWeights, /*IsExpected=*/false);
5696 } else {
5698 }
5699
5700 // Add all of the 'cases' to the switch instruction.
5701 for (ConstantInt *Val : Values)
5702 New->addCase(Val, EdgeBB);
5703
5704 // We added edges from PI to the EdgeBB. As such, if there were any
5705 // PHI nodes in EdgeBB, they need entries to be added corresponding to
5706 // the number of edges added.
5707 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
5708 PHINode *PN = cast<PHINode>(BBI);
5709 Value *InVal = PN->getIncomingValueForBlock(BB);
5710 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5711 PN->addIncoming(InVal, BB);
5712 }
5713 }
5714
5715 // Erase the old branch instruction.
5717 if (DTU)
5718 DTU->applyUpdates(Updates);
5719
5720 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5721 return true;
5722}
5723
5724bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5725 if (isa<PHINode>(RI->getValue()))
5726 return simplifyCommonResume(RI);
5727 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHIIt()) &&
5728 RI->getValue() == &*RI->getParent()->getFirstNonPHIIt())
5729 // The resume must unwind the exception that caused control to branch here.
5730 return simplifySingleResume(RI);
5731
5732 return false;
5733}
5734
5735// Check if cleanup block is empty
5737 for (Instruction &I : R) {
5738 auto *II = dyn_cast<IntrinsicInst>(&I);
5739 if (!II || II->getIntrinsicID() != Intrinsic::lifetime_end)
5740 return false;
5741 }
5742 return true;
5743}
5744
5745// Simplify resume that is shared by several landing pads (phi of landing pad).
5746bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5747 BasicBlock *BB = RI->getParent();
5748
5749 // Check that there are no other instructions except for debug and lifetime
5750 // intrinsics between the phi's and resume instruction.
5751 if (!isCleanupBlockEmpty(make_range(RI->getParent()->getFirstNonPHIIt(),
5752 BB->getTerminator()->getIterator())))
5753 return false;
5754
5755 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5756 auto *PhiLPInst = cast<PHINode>(RI->getValue());
5757
5758 // Check incoming blocks to see if any of them are trivial.
5759 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5760 Idx++) {
5761 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
5762 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
5763
5764 // If the block has other successors, we can not delete it because
5765 // it has other dependents.
5766 if (IncomingBB->getUniqueSuccessor() != BB)
5767 continue;
5768
5769 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHIIt());
5770 // Not the landing pad that caused the control to branch here.
5771 if (IncomingValue != LandingPad)
5772 continue;
5773
5775 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
5776 TrivialUnwindBlocks.insert(IncomingBB);
5777 }
5778
5779 // If no trivial unwind blocks, don't do any simplifications.
5780 if (TrivialUnwindBlocks.empty())
5781 return false;
5782
5783 // Turn all invokes that unwind here into calls.
5784 for (auto *TrivialBB : TrivialUnwindBlocks) {
5785 // Blocks that will be simplified should be removed from the phi node.
5786 // Note there could be multiple edges to the resume block, and we need
5787 // to remove them all.
5788 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
5789 BB->removePredecessor(TrivialBB, true);
5790
5791 for (BasicBlock *Pred :
5793 removeUnwindEdge(Pred, DTU);
5794 ++NumInvokes;
5795 }
5796
5797 // In each SimplifyCFG run, only the current processed block can be erased.
5798 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5799 // of erasing TrivialBB, we only remove the branch to the common resume
5800 // block so that we can later erase the resume block since it has no
5801 // predecessors.
5802 TrivialBB->getTerminator()->eraseFromParent();
5803 new UnreachableInst(RI->getContext(), TrivialBB);
5804 if (DTU)
5805 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
5806 }
5807
5808 // Delete the resume block if all its predecessors have been removed.
5809 if (pred_empty(BB))
5810 DeleteDeadBlock(BB, DTU);
5811
5812 return !TrivialUnwindBlocks.empty();
5813}
5814
5815// Simplify resume that is only used by a single (non-phi) landing pad.
5816bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5817 BasicBlock *BB = RI->getParent();
5818 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHIIt());
5819 assert(RI->getValue() == LPInst &&
5820 "Resume must unwind the exception that caused control to here");
5821
5822 // Check that there are no other instructions except for debug intrinsics.
5824 make_range<Instruction *>(LPInst->getNextNode(), RI)))
5825 return false;
5826
5827 // Turn all invokes that unwind here into calls and delete the basic block.
5828 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
5829 removeUnwindEdge(Pred, DTU);
5830 ++NumInvokes;
5831 }
5832
5833 // The landingpad is now unreachable. Zap it.
5834 DeleteDeadBlock(BB, DTU);
5835 return true;
5836}
5837
5839 // If this is a trivial cleanup pad that executes no instructions, it can be
5840 // eliminated. If the cleanup pad continues to the caller, any predecessor
5841 // that is an EH pad will be updated to continue to the caller and any
5842 // predecessor that terminates with an invoke instruction will have its invoke
5843 // instruction converted to a call instruction. If the cleanup pad being
5844 // simplified does not continue to the caller, each predecessor will be
5845 // updated to continue to the unwind destination of the cleanup pad being
5846 // simplified.
5847 BasicBlock *BB = RI->getParent();
5848 CleanupPadInst *CPInst = RI->getCleanupPad();
5849 if (CPInst->getParent() != BB)
5850 // This isn't an empty cleanup.
5851 return false;
5852
5853 // We cannot kill the pad if it has multiple uses. This typically arises
5854 // from unreachable basic blocks.
5855 if (!CPInst->hasOneUse())
5856 return false;
5857
5858 // Check that there are no other instructions except for benign intrinsics.
5860 make_range<Instruction *>(CPInst->getNextNode(), RI)))
5861 return false;
5862
5863 // If the cleanup return we are simplifying unwinds to the caller, this will
5864 // set UnwindDest to nullptr.
5865 BasicBlock *UnwindDest = RI->getUnwindDest();
5866
5867 // We're about to remove BB from the control flow. Before we do, sink any
5868 // PHINodes into the unwind destination. Doing this before changing the
5869 // control flow avoids some potentially slow checks, since we can currently
5870 // be certain that UnwindDest and BB have no common predecessors (since they
5871 // are both EH pads).
5872 if (UnwindDest) {
5873 // First, go through the PHI nodes in UnwindDest and update any nodes that
5874 // reference the block we are removing
5875 for (PHINode &DestPN : UnwindDest->phis()) {
5876 int Idx = DestPN.getBasicBlockIndex(BB);
5877 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5878 assert(Idx != -1);
5879 // This PHI node has an incoming value that corresponds to a control
5880 // path through the cleanup pad we are removing. If the incoming
5881 // value is in the cleanup pad, it must be a PHINode (because we
5882 // verified above that the block is otherwise empty). Otherwise, the
5883 // value is either a constant or a value that dominates the cleanup
5884 // pad being removed.
5885 //
5886 // Because BB and UnwindDest are both EH pads, all of their
5887 // predecessors must unwind to these blocks, and since no instruction
5888 // can have multiple unwind destinations, there will be no overlap in
5889 // incoming blocks between SrcPN and DestPN.
5890 Value *SrcVal = DestPN.getIncomingValue(Idx);
5891 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
5892
5893 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5894 for (auto *Pred : predecessors(BB)) {
5895 Value *Incoming =
5896 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
5897 DestPN.addIncoming(Incoming, Pred);
5898 }
5899 }
5900
5901 // Sink any remaining PHI nodes directly into UnwindDest.
5902 BasicBlock::iterator InsertPt = UnwindDest->getFirstNonPHIIt();
5903 for (PHINode &PN : make_early_inc_range(BB->phis())) {
5904 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5905 // If the PHI node has no uses or all of its uses are in this basic
5906 // block (meaning they are debug or lifetime intrinsics), just leave
5907 // it. It will be erased when we erase BB below.
5908 continue;
5909
5910 // Otherwise, sink this PHI node into UnwindDest.
5911 // Any predecessors to UnwindDest which are not already represented
5912 // must be back edges which inherit the value from the path through
5913 // BB. In this case, the PHI value must reference itself.
5914 for (auto *pred : predecessors(UnwindDest))
5915 if (pred != BB)
5916 PN.addIncoming(&PN, pred);
5917 PN.moveBefore(InsertPt);
5918 // Also, add a dummy incoming value for the original BB itself,
5919 // so that the PHI is well-formed until we drop said predecessor.
5920 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5921 }
5922 }
5923
5924 std::vector<DominatorTree::UpdateType> Updates;
5925
5926 // We use make_early_inc_range here because we will remove all predecessors.
5928 if (UnwindDest == nullptr) {
5929 if (DTU) {
5930 DTU->applyUpdates(Updates);
5931 Updates.clear();
5932 }
5933 removeUnwindEdge(PredBB, DTU);
5934 ++NumInvokes;
5935 } else {
5936 BB->removePredecessor(PredBB);
5937 Instruction *TI = PredBB->getTerminator();
5938 TI->replaceUsesOfWith(BB, UnwindDest);
5939 if (DTU) {
5940 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5941 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5942 }
5943 }
5944 }
5945
5946 if (DTU)
5947 DTU->applyUpdates(Updates);
5948
5949 DeleteDeadBlock(BB, DTU);
5950
5951 return true;
5952}
5953
5954// Try to merge two cleanuppads together.
5956 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5957 // with.
5958 BasicBlock *UnwindDest = RI->getUnwindDest();
5959 if (!UnwindDest)
5960 return false;
5961
5962 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5963 // be safe to merge without code duplication.
5964 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5965 return false;
5966
5967 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5968 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5969 if (!SuccessorCleanupPad)
5970 return false;
5971
5972 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5973 // Replace any uses of the successor cleanupad with the predecessor pad
5974 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5975 // funclet bundle operands.
5976 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5977 // Remove the old cleanuppad.
5978 SuccessorCleanupPad->eraseFromParent();
5979 // Now, we simply replace the cleanupret with a branch to the unwind
5980 // destination.
5981 UncondBrInst::Create(UnwindDest, RI->getParent());
5982 RI->eraseFromParent();
5983
5984 return true;
5985}
5986
5987bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5988 // It is possible to transiantly have an undef cleanuppad operand because we
5989 // have deleted some, but not all, dead blocks.
5990 // Eventually, this block will be deleted.
5991 if (isa<UndefValue>(RI->getOperand(0)))
5992 return false;
5993
5994 if (mergeCleanupPad(RI))
5995 return true;
5996
5997 if (removeEmptyCleanup(RI, DTU))
5998 return true;
5999
6000 return false;
6001}
6002
6003// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
6004bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
6005 BasicBlock *BB = UI->getParent();
6006
6007 bool Changed = false;
6008
6009 // Ensure that any debug-info records that used to occur after the Unreachable
6010 // are moved to in front of it -- otherwise they'll "dangle" at the end of
6011 // the block.
6013
6014 // Debug-info records on the unreachable inst itself should be deleted, as
6015 // below we delete everything past the final executable instruction.
6016 UI->dropDbgRecords();
6017
6018 // If there are any instructions immediately before the unreachable that can
6019 // be removed, do so.
6020 while (UI->getIterator() != BB->begin()) {
6022 --BBI;
6023
6025 break; // Can not drop any more instructions. We're done here.
6026 // Otherwise, this instruction can be freely erased,
6027 // even if it is not side-effect free.
6028
6029 // Note that deleting EH's here is in fact okay, although it involves a bit
6030 // of subtle reasoning. If this inst is an EH, all the predecessors of this
6031 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
6032 // and we can therefore guarantee this block will be erased.
6033
6034 // If we're deleting this, we're deleting any subsequent debug info, so
6035 // delete DbgRecords.
6036 BBI->dropDbgRecords();
6037
6038 // Delete this instruction (any uses are guaranteed to be dead)
6039 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
6040 BBI->eraseFromParent();
6041 Changed = true;
6042 }
6043
6044 // If the unreachable instruction is the first in the block, take a gander
6045 // at all of the predecessors of this instruction, and simplify them.
6046 if (&BB->front() != UI)
6047 return Changed;
6048
6049 std::vector<DominatorTree::UpdateType> Updates;
6050
6051 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
6052 for (BasicBlock *Predecessor : Preds) {
6053 Instruction *TI = Predecessor->getTerminator();
6054 IRBuilder<> Builder(TI);
6055 if (isa<UncondBrInst>(TI)) {
6056 new UnreachableInst(TI->getContext(), TI->getIterator());
6057 TI->eraseFromParent();
6058 Changed = true;
6059 if (DTU)
6060 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6061 } else if (auto *BI = dyn_cast<CondBrInst>(TI)) {
6062 // We could either have a proper unconditional branch,
6063 // or a degenerate conditional branch with matching destinations.
6064 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
6065 new UnreachableInst(TI->getContext(), TI->getIterator());
6066 TI->eraseFromParent();
6067 Changed = true;
6068 } else {
6069 Value* Cond = BI->getCondition();
6070 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
6071 "The destinations are guaranteed to be different here.");
6072 CallInst *Assumption;
6073 if (BI->getSuccessor(0) == BB) {
6074 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
6075 Builder.CreateBr(BI->getSuccessor(1));
6076 } else {
6077 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
6078 Assumption = Builder.CreateAssumption(Cond);
6079 Builder.CreateBr(BI->getSuccessor(0));
6080 }
6081 if (Options.AC)
6082 Options.AC->registerAssumption(cast<AssumeInst>(Assumption));
6083
6085 Changed = true;
6086 }
6087 if (DTU)
6088 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6089 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
6090 SwitchInstProfUpdateWrapper SU(*SI);
6091 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
6092 if (i->getCaseSuccessor() != BB) {
6093 ++i;
6094 continue;
6095 }
6096 BB->removePredecessor(SU->getParent());
6097 i = SU.removeCase(i);
6098 e = SU->case_end();
6099 Changed = true;
6100 }
6101 // Note that the default destination can't be removed!
6102 if (DTU && SI->getDefaultDest() != BB)
6103 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6104 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
6105 if (II->getUnwindDest() == BB) {
6106 if (DTU) {
6107 DTU->applyUpdates(Updates);
6108 Updates.clear();
6109 }
6110 auto *CI = cast<CallInst>(removeUnwindEdge(TI->getParent(), DTU));
6111 if (!CI->doesNotThrow())
6112 CI->setDoesNotThrow();
6113 Changed = true;
6114 }
6115 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
6116 if (CSI->getUnwindDest() == BB) {
6117 if (DTU) {
6118 DTU->applyUpdates(Updates);
6119 Updates.clear();
6120 }
6121 removeUnwindEdge(TI->getParent(), DTU);
6122 Changed = true;
6123 continue;
6124 }
6125
6126 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
6127 E = CSI->handler_end();
6128 I != E; ++I) {
6129 if (*I == BB) {
6130 CSI->removeHandler(I);
6131 --I;
6132 --E;
6133 Changed = true;
6134 }
6135 }
6136 if (DTU)
6137 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6138 if (CSI->getNumHandlers() == 0) {
6139 if (CSI->hasUnwindDest()) {
6140 // Redirect all predecessors of the block containing CatchSwitchInst
6141 // to instead branch to the CatchSwitchInst's unwind destination.
6142 if (DTU) {
6143 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
6144 Updates.push_back({DominatorTree::Insert,
6145 PredecessorOfPredecessor,
6146 CSI->getUnwindDest()});
6147 Updates.push_back({DominatorTree::Delete,
6148 PredecessorOfPredecessor, Predecessor});
6149 }
6150 }
6151 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
6152 } else {
6153 // Rewrite all preds to unwind to caller (or from invoke to call).
6154 if (DTU) {
6155 DTU->applyUpdates(Updates);
6156 Updates.clear();
6157 }
6158 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
6159 for (BasicBlock *EHPred : EHPreds)
6160 removeUnwindEdge(EHPred, DTU);
6161 }
6162 // The catchswitch is no longer reachable.
6163 new UnreachableInst(CSI->getContext(), CSI->getIterator());
6164 CSI->eraseFromParent();
6165 Changed = true;
6166 }
6167 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
6168 (void)CRI;
6169 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
6170 "Expected to always have an unwind to BB.");
6171 if (DTU)
6172 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
6173 new UnreachableInst(TI->getContext(), TI->getIterator());
6174 TI->eraseFromParent();
6175 Changed = true;
6176 }
6177 }
6178
6179 if (DTU)
6180 DTU->applyUpdates(Updates);
6181
6182 // If this block is now dead, remove it.
6183 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
6184 DeleteDeadBlock(BB, DTU);
6185 return true;
6186 }
6187
6188 return Changed;
6189}
6190
6199
6200static std::optional<ContiguousCasesResult>
6203 BasicBlock *Dest, BasicBlock *OtherDest) {
6204 assert(Cases.size() >= 1);
6205
6207 const APInt &Min = Cases.back()->getValue();
6208 const APInt &Max = Cases.front()->getValue();
6209 APInt Offset = Max - Min;
6210 size_t ContiguousOffset = Cases.size() - 1;
6211 if (Offset == ContiguousOffset) {
6212 return ContiguousCasesResult{
6213 /*Min=*/Cases.back(),
6214 /*Max=*/Cases.front(),
6215 /*Dest=*/Dest,
6216 /*OtherDest=*/OtherDest,
6217 /*Cases=*/&Cases,
6218 /*OtherCases=*/&OtherCases,
6219 };
6220 }
6221 ConstantRange CR = computeConstantRange(Condition, /*ForSigned=*/false,
6222 SimplifyQuery(Dest->getDataLayout()));
6223 // If this is a wrapping contiguous range, that is, [Min, OtherMin] +
6224 // [OtherMax, Max] (also [OtherMax, OtherMin]), [OtherMin+1, OtherMax-1] is a
6225 // contiguous range for the other destination. N.B. If CR is not a full range,
6226 // Max+1 is not equal to Min. It's not continuous in arithmetic.
6227 if (Max == CR.getUnsignedMax() && Min == CR.getUnsignedMin()) {
6228 assert(Cases.size() >= 2);
6229 auto *It =
6230 std::adjacent_find(Cases.begin(), Cases.end(), [](auto L, auto R) {
6231 return L->getValue() != R->getValue() + 1;
6232 });
6233 if (It == Cases.end())
6234 return std::nullopt;
6235 auto [OtherMax, OtherMin] = std::make_pair(*It, *std::next(It));
6236 if ((Max - OtherMax->getValue()) + (OtherMin->getValue() - Min) ==
6237 Cases.size() - 2) {
6238 return ContiguousCasesResult{
6239 /*Min=*/cast<ConstantInt>(
6240 ConstantInt::get(OtherMin->getType(), OtherMin->getValue() + 1)),
6241 /*Max=*/
6243 ConstantInt::get(OtherMax->getType(), OtherMax->getValue() - 1)),
6244 /*Dest=*/OtherDest,
6245 /*OtherDest=*/Dest,
6246 /*Cases=*/&OtherCases,
6247 /*OtherCases=*/&Cases,
6248 };
6249 }
6250 }
6251 return std::nullopt;
6252}
6253
6255 DomTreeUpdater *DTU,
6256 bool RemoveOrigDefaultBlock = true) {
6257 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
6258 auto *BB = Switch->getParent();
6259 auto *OrigDefaultBlock = Switch->getDefaultDest();
6260 if (RemoveOrigDefaultBlock)
6261 OrigDefaultBlock->removePredecessor(BB);
6262 BasicBlock *NewDefaultBlock = BasicBlock::Create(
6263 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
6264 OrigDefaultBlock);
6265 auto *UI = new UnreachableInst(Switch->getContext(), NewDefaultBlock);
6267 Switch->setDefaultDest(&*NewDefaultBlock);
6268 if (DTU) {
6270 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
6271 if (RemoveOrigDefaultBlock &&
6272 !is_contained(successors(BB), OrigDefaultBlock))
6273 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
6274 DTU->applyUpdates(Updates);
6275 }
6276}
6277
6278/// Turn a switch into an integer range comparison and branch.
6279/// Switches with more than 2 destinations are ignored.
6280/// Switches with 1 destination are also ignored.
6281bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
6282 IRBuilder<> &Builder) {
6283 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6284
6285 bool HasDefault = !SI->defaultDestUnreachable();
6286
6287 auto *BB = SI->getParent();
6288 // Partition the cases into two sets with different destinations.
6289 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
6290 BasicBlock *DestB = nullptr;
6293
6294 for (auto Case : SI->cases()) {
6295 BasicBlock *Dest = Case.getCaseSuccessor();
6296 if (!DestA)
6297 DestA = Dest;
6298 if (Dest == DestA) {
6299 CasesA.push_back(Case.getCaseValue());
6300 continue;
6301 }
6302 if (!DestB)
6303 DestB = Dest;
6304 if (Dest == DestB) {
6305 CasesB.push_back(Case.getCaseValue());
6306 continue;
6307 }
6308 return false; // More than two destinations.
6309 }
6310 if (!DestB)
6311 return false; // All destinations are the same and the default is unreachable
6312
6313 assert(DestA && DestB &&
6314 "Single-destination switch should have been folded.");
6315 assert(DestA != DestB);
6316 assert(DestB != SI->getDefaultDest());
6317 assert(!CasesB.empty() && "There must be non-default cases.");
6318 assert(!CasesA.empty() || HasDefault);
6319
6320 // Figure out if one of the sets of cases form a contiguous range.
6321 std::optional<ContiguousCasesResult> ContiguousCases;
6322
6323 // Only one icmp is needed when there is only one case.
6324 if (!HasDefault && CasesA.size() == 1)
6325 ContiguousCases = ContiguousCasesResult{
6326 /*Min=*/CasesA[0],
6327 /*Max=*/CasesA[0],
6328 /*Dest=*/DestA,
6329 /*OtherDest=*/DestB,
6330 /*Cases=*/&CasesA,
6331 /*OtherCases=*/&CasesB,
6332 };
6333 else if (CasesB.size() == 1)
6334 ContiguousCases = ContiguousCasesResult{
6335 /*Min=*/CasesB[0],
6336 /*Max=*/CasesB[0],
6337 /*Dest=*/DestB,
6338 /*OtherDest=*/DestA,
6339 /*Cases=*/&CasesB,
6340 /*OtherCases=*/&CasesA,
6341 };
6342 // Correctness: Cases to the default destination cannot be contiguous cases.
6343 else if (!HasDefault)
6344 ContiguousCases =
6345 findContiguousCases(SI->getCondition(), CasesA, CasesB, DestA, DestB);
6346
6347 if (!ContiguousCases)
6348 ContiguousCases =
6349 findContiguousCases(SI->getCondition(), CasesB, CasesA, DestB, DestA);
6350
6351 if (!ContiguousCases)
6352 return false;
6353
6354 auto [Min, Max, Dest, OtherDest, Cases, OtherCases] = *ContiguousCases;
6355
6356 // Start building the compare and branch.
6357
6359 Constant *NumCases = ConstantInt::get(Offset->getType(),
6360 Max->getValue() - Min->getValue() + 1);
6361 Instruction *NewBI;
6362 if (NumCases->isOneValue()) {
6363 assert(Max->getValue() == Min->getValue());
6364 Value *Cmp = Builder.CreateICmpEQ(SI->getCondition(), Min);
6365 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6366 }
6367 // If NumCases overflowed, then all possible values jump to the successor.
6368 else if (NumCases->isNullValue() && !Cases->empty()) {
6369 NewBI = Builder.CreateBr(Dest);
6370 } else {
6371 Value *Sub = SI->getCondition();
6372 if (!Offset->isNullValue())
6373 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
6374 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
6375 NewBI = Builder.CreateCondBr(Cmp, Dest, OtherDest);
6376 }
6377
6378 // Update weight for the newly-created conditional branch.
6379 if (hasBranchWeightMD(*SI) && isa<CondBrInst>(NewBI)) {
6380 SmallVector<uint64_t, 8> Weights;
6381 getBranchWeights(SI, Weights);
6382 if (Weights.size() == 1 + SI->getNumCases()) {
6383 uint64_t TrueWeight = 0;
6384 uint64_t FalseWeight = 0;
6385 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
6386 if (SI->getSuccessor(I) == Dest)
6387 TrueWeight += Weights[I];
6388 else
6389 FalseWeight += Weights[I];
6390 }
6391 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
6392 TrueWeight /= 2;
6393 FalseWeight /= 2;
6394 }
6395 setFittedBranchWeights(*NewBI, {TrueWeight, FalseWeight},
6396 /*IsExpected=*/false, /*ElideAllZero=*/true);
6397 }
6398 }
6399
6400 // Prune obsolete incoming values off the successors' PHI nodes.
6401 for (auto &PHI : make_early_inc_range(Dest->phis())) {
6402 unsigned PreviousEdges = Cases->size();
6403 if (Dest == SI->getDefaultDest())
6404 ++PreviousEdges;
6405 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
6406 PHI.removeIncomingValue(SI->getParent());
6407 }
6408 for (auto &PHI : make_early_inc_range(OtherDest->phis())) {
6409 unsigned PreviousEdges = OtherCases->size();
6410 if (OtherDest == SI->getDefaultDest())
6411 ++PreviousEdges;
6412 unsigned E = PreviousEdges - 1;
6413 // Remove all incoming values from OtherDest if OtherDest is unreachable.
6414 if (isa<UncondBrInst>(NewBI))
6415 ++E;
6416 for (unsigned I = 0; I != E; ++I)
6417 PHI.removeIncomingValue(SI->getParent());
6418 }
6419
6420 // Clean up the default block.
6421 SmallVector<DominatorTree::UpdateType, 2> Updates;
6422 if (!HasDefault) {
6423 BasicBlock *OrigDefaultBlock = SI->getDefaultDest();
6424 OrigDefaultBlock->removePredecessor(BB);
6425 Updates.push_back({DominatorTree::Delete, BB, OrigDefaultBlock});
6426 }
6427
6428 // Drop the switch.
6429 SI->eraseFromParent();
6430
6431 if (isa<UncondBrInst>(NewBI))
6432 Updates.push_back({DominatorTree::Delete, BB, OtherDest});
6433
6434 if (DTU)
6435 DTU->applyUpdates(Updates);
6436 return true;
6437}
6438
6439/// Compute masked bits for the condition of a switch
6440/// and use it to remove dead cases.
6442 AssumptionCache *AC,
6443 const DataLayout &DL) {
6444 Value *Cond = SI->getCondition();
6447 bool IsKnownValuesValid = collectPossibleValues(Cond, KnownValues, 4);
6448
6449 // We can also eliminate cases by determining that their values are outside of
6450 // the limited range of the condition based on how many significant (non-sign)
6451 // bits are in the condition value.
6452 unsigned MaxSignificantBitsInCond =
6454
6455 // Gather dead cases.
6457 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
6458 SmallVector<BasicBlock *, 8> UniqueSuccessors;
6459 for (const auto &Case : SI->cases()) {
6460 auto *Successor = Case.getCaseSuccessor();
6461 if (DTU) {
6462 auto [It, Inserted] = NumPerSuccessorCases.try_emplace(Successor);
6463 if (Inserted)
6464 UniqueSuccessors.push_back(Successor);
6465 ++It->second;
6466 }
6467 ConstantInt *CaseC = Case.getCaseValue();
6468 const APInt &CaseVal = CaseC->getValue();
6469 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
6470 (CaseVal.getSignificantBits() > MaxSignificantBitsInCond) ||
6471 (IsKnownValuesValid && !KnownValues.contains(CaseC))) {
6472 DeadCases.push_back(CaseC);
6473 if (DTU)
6474 --NumPerSuccessorCases[Successor];
6475 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
6476 << " is dead.\n");
6477 } else if (IsKnownValuesValid)
6478 KnownValues.erase(CaseC);
6479 }
6480
6481 // If we can prove that the cases must cover all possible values, the
6482 // default destination becomes dead and we can remove it. If we know some
6483 // of the bits in the value, we can use that to more precisely compute the
6484 // number of possible unique case values.
6485 bool HasDefault = !SI->defaultDestUnreachable();
6486 const unsigned NumUnknownBits =
6487 Known.getBitWidth() - (Known.Zero | Known.One).popcount();
6488 assert(NumUnknownBits <= Known.getBitWidth());
6489 if (HasDefault && DeadCases.empty()) {
6490 if (IsKnownValuesValid && all_of(KnownValues, IsaPred<UndefValue>)) {
6492 return true;
6493 }
6494
6495 if (NumUnknownBits < 64 /* avoid overflow */) {
6496 uint64_t AllNumCases = 1ULL << NumUnknownBits;
6497 if (SI->getNumCases() == AllNumCases) {
6499 return true;
6500 }
6501 // When only one case value is missing, replace default with that case.
6502 // Eliminating the default branch will provide more opportunities for
6503 // optimization, such as lookup tables.
6504 if (SI->getNumCases() == AllNumCases - 1) {
6505 assert(NumUnknownBits > 1 && "Should be canonicalized to a branch");
6506 IntegerType *CondTy = cast<IntegerType>(Cond->getType());
6507 if (CondTy->getIntegerBitWidth() > 64 ||
6508 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6509 return false;
6510
6511 uint64_t MissingCaseVal = 0;
6512 for (const auto &Case : SI->cases())
6513 MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
6514 auto *MissingCase = cast<ConstantInt>(
6515 ConstantInt::get(Cond->getType(), MissingCaseVal));
6517 SIW.addCase(MissingCase, SI->getDefaultDest(),
6518 SIW.getSuccessorWeight(0));
6520 /*RemoveOrigDefaultBlock*/ false);
6521 SIW.setSuccessorWeight(0, 0);
6522 return true;
6523 }
6524 }
6525 }
6526
6527 if (DeadCases.empty())
6528 return false;
6529
6531 for (ConstantInt *DeadCase : DeadCases) {
6532 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
6533 assert(CaseI != SI->case_default() &&
6534 "Case was not found. Probably mistake in DeadCases forming.");
6535 // Prune unused values from PHI nodes.
6536 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
6537 SIW.removeCase(CaseI);
6538 }
6539
6540 if (DTU) {
6541 std::vector<DominatorTree::UpdateType> Updates;
6542 for (auto *Successor : UniqueSuccessors)
6543 if (NumPerSuccessorCases[Successor] == 0)
6544 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
6545 DTU->applyUpdates(Updates);
6546 }
6547
6548 return true;
6549}
6550
6551/// If BB would be eligible for simplification by
6552/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
6553/// by an unconditional branch), look at the phi node for BB in the successor
6554/// block and see if the incoming value is equal to CaseValue. If so, return
6555/// the phi node, and set PhiIndex to BB's index in the phi node.
6557 BasicBlock *BB, int *PhiIndex) {
6558 if (&*BB->getFirstNonPHIIt() != BB->getTerminator())
6559 return nullptr; // BB must be empty to be a candidate for simplification.
6560 if (!BB->getSinglePredecessor())
6561 return nullptr; // BB must be dominated by the switch.
6562
6564 if (!Branch)
6565 return nullptr; // Terminator must be unconditional branch.
6566
6567 BasicBlock *Succ = Branch->getSuccessor();
6568
6569 for (PHINode &PHI : Succ->phis()) {
6570 int Idx = PHI.getBasicBlockIndex(BB);
6571 assert(Idx >= 0 && "PHI has no entry for predecessor?");
6572
6573 Value *InValue = PHI.getIncomingValue(Idx);
6574 if (InValue != CaseValue)
6575 continue;
6576
6577 *PhiIndex = Idx;
6578 return &PHI;
6579 }
6580
6581 return nullptr;
6582}
6583
6584/// Try to forward the condition of a switch instruction to a phi node
6585/// dominated by the switch, if that would mean that some of the destination
6586/// blocks of the switch can be folded away. Return true if a change is made.
6588 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
6589
6590 ForwardingNodesMap ForwardingNodes;
6591 BasicBlock *SwitchBlock = SI->getParent();
6592 bool Changed = false;
6593 for (const auto &Case : SI->cases()) {
6594 ConstantInt *CaseValue = Case.getCaseValue();
6595 BasicBlock *CaseDest = Case.getCaseSuccessor();
6596
6597 // Replace phi operands in successor blocks that are using the constant case
6598 // value rather than the switch condition variable:
6599 // switchbb:
6600 // switch i32 %x, label %default [
6601 // i32 17, label %succ
6602 // ...
6603 // succ:
6604 // %r = phi i32 ... [ 17, %switchbb ] ...
6605 // -->
6606 // %r = phi i32 ... [ %x, %switchbb ] ...
6607
6608 for (PHINode &Phi : CaseDest->phis()) {
6609 // This only works if there is exactly 1 incoming edge from the switch to
6610 // a phi. If there is >1, that means multiple cases of the switch map to 1
6611 // value in the phi, and that phi value is not the switch condition. Thus,
6612 // this transform would not make sense (the phi would be invalid because
6613 // a phi can't have different incoming values from the same block).
6614 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
6615 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
6616 count(Phi.blocks(), SwitchBlock) == 1) {
6617 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
6618 Changed = true;
6619 }
6620 }
6621
6622 // Collect phi nodes that are indirectly using this switch's case constants.
6623 int PhiIdx;
6624 if (auto *Phi = findPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
6625 ForwardingNodes[Phi].push_back(PhiIdx);
6626 }
6627
6628 for (auto &ForwardingNode : ForwardingNodes) {
6629 PHINode *Phi = ForwardingNode.first;
6630 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
6631 // Check if it helps to fold PHI.
6632 if (Indexes.size() < 2 && !llvm::is_contained(Phi->incoming_values(), SI->getCondition()))
6633 continue;
6634
6635 for (int Index : Indexes)
6636 Phi->setIncomingValue(Index, SI->getCondition());
6637 Changed = true;
6638 }
6639
6640 return Changed;
6641}
6642
6643/// Return true if the backend will be able to handle
6644/// initializing an array of constants like C.
6646 if (C->isThreadDependent())
6647 return false;
6648 if (C->isDLLImportDependent())
6649 return false;
6650
6653 return false;
6654
6655 // Globals cannot contain scalable types.
6656 if (C->getType()->isScalableTy())
6657 return false;
6658
6660 // Pointer casts and in-bounds GEPs will not prohibit the backend from
6661 // materializing the array of constants.
6662 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
6663 if (StrippedC == C || !validLookupTableConstant(StrippedC, TTI))
6664 return false;
6665 }
6666
6667 if (!TTI.shouldBuildLookupTablesForConstant(C))
6668 return false;
6669
6670 return true;
6671}
6672
6673/// If V is a Constant, return it. Otherwise, try to look up
6674/// its constant value in ConstantPool, returning 0 if it's not there.
6675static Constant *
6679 return C;
6680 return ConstantPool.lookup(V);
6681}
6682
6683/// Try to fold instruction I into a constant. This works for
6684/// simple instructions such as binary operations where both operands are
6685/// constant or can be replaced by constants from the ConstantPool. Returns the
6686/// resulting constant on success, 0 otherwise.
6687static Constant *
6691 Constant *A = lookupConstant(Select->getCondition(), ConstantPool);
6692 if (!A)
6693 return nullptr;
6694 if (A->isAllOnesValue())
6695 return lookupConstant(Select->getTrueValue(), ConstantPool);
6696 if (A->isNullValue())
6697 return lookupConstant(Select->getFalseValue(), ConstantPool);
6698 return nullptr;
6699 }
6700
6702 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
6703 if (Constant *A = lookupConstant(I->getOperand(N), ConstantPool))
6704 COps.push_back(A);
6705 else
6706 return nullptr;
6707 }
6708
6709 return ConstantFoldInstOperands(I, COps, DL);
6710}
6711
6712/// Try to determine the resulting constant values in phi nodes
6713/// at the common destination basic block, *CommonDest, for one of the case
6714/// destinations CaseDest corresponding to value CaseVal (nullptr for the
6715/// default case), of a switch instruction SI.
6716static bool
6718 BasicBlock **CommonDest,
6719 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
6720 const DataLayout &DL) {
6721 // The block from which we enter the common destination.
6722 BasicBlock *Pred = SI->getParent();
6723
6724 // If CaseDest is empty except for some side-effect free instructions through
6725 // which we can constant-propagate the CaseVal, continue to its successor.
6727 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
6728 for (Instruction &I : *CaseDest) {
6729 if (I.isTerminator()) {
6730 // If the terminator is a simple branch, continue to the next block.
6731 if (I.getNumSuccessors() != 1 || I.isSpecialTerminator())
6732 return false;
6733 Pred = CaseDest;
6734 CaseDest = I.getSuccessor(0);
6735 } else if (Constant *C = constantFold(&I, DL, ConstantPool)) {
6736 // Instruction is side-effect free and constant.
6737
6738 // If the instruction has uses outside this block or a phi node slot for
6739 // the block, it is not safe to bypass the instruction since it would then
6740 // no longer dominate all its uses.
6741 for (auto &Use : I.uses()) {
6742 User *User = Use.getUser();
6744 if (I->getParent() == CaseDest)
6745 continue;
6746 if (PHINode *Phi = dyn_cast<PHINode>(User))
6747 if (Phi->getIncomingBlock(Use) == CaseDest)
6748 continue;
6749 return false;
6750 }
6751
6752 ConstantPool.insert(std::make_pair(&I, C));
6753 } else {
6754 break;
6755 }
6756 }
6757
6758 // If we did not have a CommonDest before, use the current one.
6759 if (!*CommonDest)
6760 *CommonDest = CaseDest;
6761 // If the destination isn't the common one, abort.
6762 if (CaseDest != *CommonDest)
6763 return false;
6764
6765 // Get the values for this case from phi nodes in the destination block.
6766 for (PHINode &PHI : (*CommonDest)->phis()) {
6767 int Idx = PHI.getBasicBlockIndex(Pred);
6768 if (Idx == -1)
6769 continue;
6770
6771 Constant *ConstVal =
6772 lookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
6773 if (!ConstVal)
6774 return false;
6775
6776 Res.push_back(std::make_pair(&PHI, ConstVal));
6777 }
6778
6779 return Res.size() > 0;
6780}
6781
6782// Helper function used to add CaseVal to the list of cases that generate
6783// Result. Returns the updated number of cases that generate this result.
6784static size_t mapCaseToResult(ConstantInt *CaseVal,
6785 SwitchCaseResultVectorTy &UniqueResults,
6786 Constant *Result) {
6787 for (auto &I : UniqueResults) {
6788 if (I.first == Result) {
6789 I.second.push_back(CaseVal);
6790 return I.second.size();
6791 }
6792 }
6793 UniqueResults.push_back(
6794 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
6795 return 1;
6796}
6797
6798// Helper function that initializes a map containing
6799// results for the PHI node of the common destination block for a switch
6800// instruction. Returns false if multiple PHI nodes have been found or if
6801// there is not a common destination block for the switch.
6803 BasicBlock *&CommonDest,
6804 SwitchCaseResultVectorTy &UniqueResults,
6805 Constant *&DefaultResult,
6806 const DataLayout &DL,
6807 uintptr_t MaxUniqueResults) {
6808 for (const auto &I : SI->cases()) {
6809 ConstantInt *CaseVal = I.getCaseValue();
6810
6811 // Resulting value at phi nodes for this case value.
6812 SwitchCaseResultsTy Results;
6813 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
6814 DL))
6815 return false;
6816
6817 // Only one value per case is permitted.
6818 if (Results.size() > 1)
6819 return false;
6820
6821 // Add the case->result mapping to UniqueResults.
6822 const size_t NumCasesForResult =
6823 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
6824
6825 // Early out if there are too many cases for this result.
6826 if (NumCasesForResult > MaxSwitchCasesPerResult)
6827 return false;
6828
6829 // Early out if there are too many unique results.
6830 if (UniqueResults.size() > MaxUniqueResults)
6831 return false;
6832
6833 // Check the PHI consistency.
6834 if (!PHI)
6835 PHI = Results[0].first;
6836 else if (PHI != Results[0].first)
6837 return false;
6838 }
6839 // Find the default result value.
6841 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
6842 DL);
6843 // If the default value is not found abort unless the default destination
6844 // is unreachable.
6845 DefaultResult =
6846 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
6847
6848 return DefaultResult || SI->defaultDestUnreachable();
6849}
6850
6851// Helper function that checks if it is possible to transform a switch with only
6852// two cases (or two cases + default) that produces a result into a select.
6853// TODO: Handle switches with more than 2 cases that map to the same result.
6854// The branch weights correspond to the provided Condition (i.e. if Condition is
6855// modified from the original SwitchInst, the caller must adjust the weights)
6856static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
6857 Constant *DefaultResult, Value *Condition,
6858 IRBuilder<> &Builder, const DataLayout &DL,
6859 ArrayRef<uint32_t> BranchWeights) {
6860 // If we are selecting between only two cases transform into a simple
6861 // select or a two-way select if default is possible.
6862 // Example:
6863 // switch (a) { %0 = icmp eq i32 %a, 10
6864 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
6865 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
6866 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
6867 // }
6868
6869 const bool HasBranchWeights = !BranchWeights.empty();
6870
6871 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
6872 ResultVector[1].second.size() == 1) {
6873 ConstantInt *FirstCase = ResultVector[0].second[0];
6874 ConstantInt *SecondCase = ResultVector[1].second[0];
6875 Value *SelectValue = ResultVector[1].first;
6876 if (DefaultResult) {
6877 Value *ValueCompare =
6878 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
6879 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
6880 DefaultResult, "switch.select");
6881 if (auto *SI = dyn_cast<SelectInst>(SelectValue);
6882 SI && HasBranchWeights) {
6883 // We start with 3 probabilities, where the numerator is the
6884 // corresponding BranchWeights[i], and the denominator is the sum over
6885 // BranchWeights. We want the probability and negative probability of
6886 // Condition == SecondCase.
6887 assert(BranchWeights.size() == 3);
6889 *SI, {BranchWeights[2], BranchWeights[0] + BranchWeights[1]},
6890 /*IsExpected=*/false, /*ElideAllZero=*/true);
6891 }
6892 }
6893 Value *ValueCompare =
6894 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
6895 Value *Ret = Builder.CreateSelect(ValueCompare, ResultVector[0].first,
6896 SelectValue, "switch.select");
6897 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6898 // We may have had a DefaultResult. Base the position of the first and
6899 // second's branch weights accordingly. Also the proability that Condition
6900 // != FirstCase needs to take that into account.
6901 assert(BranchWeights.size() >= 2);
6902 size_t FirstCasePos = (Condition != nullptr);
6903 size_t SecondCasePos = FirstCasePos + 1;
6904 uint32_t DefaultCase = (Condition != nullptr) ? BranchWeights[0] : 0;
6906 {BranchWeights[FirstCasePos],
6907 DefaultCase + BranchWeights[SecondCasePos]},
6908 /*IsExpected=*/false, /*ElideAllZero=*/true);
6909 }
6910 return Ret;
6911 }
6912
6913 // Handle the degenerate case where two cases have the same result value.
6914 if (ResultVector.size() == 1 && DefaultResult) {
6915 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
6916 unsigned CaseCount = CaseValues.size();
6917 // n bits group cases map to the same result:
6918 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
6919 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
6920 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
6921 if (isPowerOf2_32(CaseCount)) {
6922 ConstantInt *MinCaseVal = CaseValues[0];
6923 // If there are bits that are set exclusively by CaseValues, we
6924 // can transform the switch into a select if the conjunction of
6925 // all the values uniquely identify CaseValues.
6926 APInt AndMask = APInt::getAllOnes(MinCaseVal->getBitWidth());
6927
6928 // Find the minimum value and compute the and of all the case values.
6929 for (auto *Case : CaseValues) {
6930 if (Case->getValue().slt(MinCaseVal->getValue()))
6931 MinCaseVal = Case;
6932 AndMask &= Case->getValue();
6933 }
6934 KnownBits Known = computeKnownBits(Condition, DL);
6935
6936 if (!AndMask.isZero() && Known.getMaxValue().uge(AndMask)) {
6937 // Compute the number of bits that are free to vary.
6938 unsigned FreeBits = Known.countMaxActiveBits() - AndMask.popcount();
6939
6940 // Check if the number of values covered by the mask is equal
6941 // to the number of cases.
6942 if (FreeBits == Log2_32(CaseCount)) {
6943 Value *And = Builder.CreateAnd(Condition, AndMask);
6944 Value *Cmp = Builder.CreateICmpEQ(
6945 And, Constant::getIntegerValue(And->getType(), AndMask));
6946 Value *Ret =
6947 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6948 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6949 // We know there's a Default case. We base the resulting branch
6950 // weights off its probability.
6951 assert(BranchWeights.size() >= 2);
6953 *SI,
6954 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6955 /*IsExpected=*/false, /*ElideAllZero=*/true);
6956 }
6957 return Ret;
6958 }
6959 }
6960
6961 // Mark the bits case number touched.
6962 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
6963 for (auto *Case : CaseValues)
6964 BitMask |= (Case->getValue() - MinCaseVal->getValue());
6965
6966 // Check if cases with the same result can cover all number
6967 // in touched bits.
6968 if (BitMask.popcount() == Log2_32(CaseCount)) {
6969 if (!MinCaseVal->isNullValue())
6970 Condition = Builder.CreateSub(Condition, MinCaseVal);
6971 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
6972 Value *Cmp = Builder.CreateICmpEQ(
6973 And, Constant::getNullValue(And->getType()), "switch.selectcmp");
6974 Value *Ret =
6975 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6976 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6977 assert(BranchWeights.size() >= 2);
6979 *SI,
6980 {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
6981 /*IsExpected=*/false, /*ElideAllZero=*/true);
6982 }
6983 return Ret;
6984 }
6985 }
6986
6987 // Handle the degenerate case where two cases have the same value.
6988 if (CaseValues.size() == 2) {
6989 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
6990 "switch.selectcmp.case1");
6991 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
6992 "switch.selectcmp.case2");
6993 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
6994 Value *Ret =
6995 Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
6996 if (auto *SI = dyn_cast<SelectInst>(Ret); SI && HasBranchWeights) {
6997 assert(BranchWeights.size() >= 2);
6999 *SI, {accumulate(drop_begin(BranchWeights), 0U), BranchWeights[0]},
7000 /*IsExpected=*/false, /*ElideAllZero=*/true);
7001 }
7002 return Ret;
7003 }
7004 }
7005
7006 return nullptr;
7007}
7008
7009// Helper function to cleanup a switch instruction that has been converted into
7010// a select, fixing up PHI nodes and basic blocks.
7012 Value *SelectValue,
7013 IRBuilder<> &Builder,
7014 DomTreeUpdater *DTU) {
7015 std::vector<DominatorTree::UpdateType> Updates;
7016
7017 BasicBlock *SelectBB = SI->getParent();
7018 BasicBlock *DestBB = PHI->getParent();
7019
7020 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
7021 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
7022 Builder.CreateBr(DestBB);
7023
7024 // Remove the switch.
7025
7026 PHI->removeIncomingValueIf(
7027 [&](unsigned Idx) { return PHI->getIncomingBlock(Idx) == SelectBB; });
7028 PHI->addIncoming(SelectValue, SelectBB);
7029
7030 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
7031 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
7032 BasicBlock *Succ = SI->getSuccessor(i);
7033
7034 if (Succ == DestBB)
7035 continue;
7036 Succ->removePredecessor(SelectBB);
7037 if (DTU && RemovedSuccessors.insert(Succ).second)
7038 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
7039 }
7040 SI->eraseFromParent();
7041 if (DTU)
7042 DTU->applyUpdates(Updates);
7043}
7044
7045/// If a switch is only used to initialize one or more phi nodes in a common
7046/// successor block with only two different constant values, try to replace the
7047/// switch with a select. Returns true if the fold was made.
7049 DomTreeUpdater *DTU, const DataLayout &DL) {
7050 Value *const Cond = SI->getCondition();
7051 PHINode *PHI = nullptr;
7052 BasicBlock *CommonDest = nullptr;
7053 Constant *DefaultResult;
7054 SwitchCaseResultVectorTy UniqueResults;
7055 // Collect all the cases that will deliver the same value from the switch.
7056 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
7057 DL, /*MaxUniqueResults*/ 2))
7058 return false;
7059
7060 assert(PHI != nullptr && "PHI for value select not found");
7061 Builder.SetInsertPoint(SI);
7062 SmallVector<uint32_t, 4> BranchWeights;
7063 [[maybe_unused]] auto HasWeights =
7065 assert(!HasWeights == (BranchWeights.empty()));
7066 assert(BranchWeights.empty() ||
7067 (BranchWeights.size() >=
7068 UniqueResults.size() + (DefaultResult != nullptr)));
7069
7070 Value *SelectValue = foldSwitchToSelect(UniqueResults, DefaultResult, Cond,
7071 Builder, DL, BranchWeights);
7072 if (!SelectValue)
7073 return false;
7074
7075 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
7076 return true;
7077}
7078
7079namespace {
7080
7081/// This class finds alternatives for switches to ultimately
7082/// replace the switch.
7083class SwitchReplacement {
7084public:
7085 /// Create a helper for optimizations to use as a switch replacement.
7086 /// Find a better representation for the content of Values,
7087 /// using DefaultValue to fill any holes in the table.
7088 /// If no representation is possible, isValid() returns false.
7089 SwitchReplacement(
7090 Module &M, uint64_t TableSize, ConstantInt *Offset,
7091 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7092 Constant *DefaultValue, const DataLayout &DL,
7093 const TargetTransformInfo &TTI, const StringRef &FuncName);
7094
7095 /// Build instructions with Builder to retrieve values using Index
7096 /// and replace the switch.
7097 Value *replaceSwitch(Value *Index, IRBuilder<> &Builder, const DataLayout &DL,
7098 Function *Func);
7099
7100 /// Return true if a table with TableSize elements of
7101 /// type ElementType would fit in a target-legal register.
7102 static bool wouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
7103 Type *ElementType);
7104
7105 /// Return the default value of the switch.
7106 Constant *getDefaultValue();
7107
7108 /// Return true if the replacement is a lookup table.
7109 bool isLookupTable();
7110
7111 /// Return true if the replacement is a bit map.
7112 bool isBitMap();
7113
7114 /// Return true if a suitable switch replacement was found.
7115 bool isValid() const { return Kind != InvalidKind; }
7116
7117private:
7118 // Depending on the switch, there are different alternatives.
7119 enum {
7120 // No suitable replacement was found.
7121 InvalidKind,
7122
7123 // For switches where each case contains the same value, we just have to
7124 // store that single value and return it for each lookup.
7125 SingleValueKind,
7126
7127 // For switches where there is a linear relationship between table index
7128 // and values. We calculate the result with a simple multiplication
7129 // and addition instead of a table lookup.
7130 LinearMapKind,
7131
7132 // For small tables with integer elements, we can pack them into a bitmap
7133 // that fits into a target-legal register. Values are retrieved by
7134 // shift and mask operations.
7135 BitMapKind,
7136
7137 // The table is stored as an array of values. Values are retrieved by load
7138 // instructions from the table.
7139 LookupTableKind
7140 } Kind;
7141
7142 // The default value of the switch.
7143 Constant *DefaultValue;
7144
7145 // The type of the output values.
7146 Type *ValueType;
7147
7148 // For SingleValueKind, this is the single value.
7149 Constant *SingleValue = nullptr;
7150
7151 // For BitMapKind, this is the bitmap.
7152 ConstantInt *BitMap = nullptr;
7153 IntegerType *BitMapElementTy = nullptr;
7154
7155 // For LinearMapKind, these are the constants used to derive the value.
7156 ConstantInt *LinearOffset = nullptr;
7157 ConstantInt *LinearMultiplier = nullptr;
7158 bool LinearMapValWrapped = false;
7159
7160 // For LookupTableKind, this is the table.
7161 Constant *Initializer = nullptr;
7162};
7163
7164} // end anonymous namespace
7165
7166SwitchReplacement::SwitchReplacement(
7167 Module &M, uint64_t TableSize, ConstantInt *Offset,
7168 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
7169 Constant *DefaultValue, const DataLayout &DL,
7170 const TargetTransformInfo &TTI, const StringRef &FuncName)
7171 : DefaultValue(DefaultValue) {
7172 assert(Values.size() && "Can't build lookup table without values!");
7173 assert(TableSize >= Values.size() && "Can't fit values in table!");
7174
7175 // If all values in the table are equal, this is that value.
7176 SingleValue = Values.begin()->second;
7177
7178 ValueType = Values.begin()->second->getType();
7179
7180 // Build up the table contents.
7181 SmallVector<Constant *, 64> TableContents(TableSize);
7182 for (const auto &[CaseVal, CaseRes] : Values) {
7183 assert(CaseRes->getType() == ValueType);
7184
7185 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
7186 TableContents[Idx] = CaseRes;
7187
7188 if (SingleValue && !isa<PoisonValue>(CaseRes) && CaseRes != SingleValue)
7189 SingleValue = isa<PoisonValue>(SingleValue) ? CaseRes : nullptr;
7190 }
7191
7192 // Fill in any holes in the table with the default result.
7193 if (Values.size() < TableSize) {
7194 assert(DefaultValue &&
7195 "Need a default value to fill the lookup table holes.");
7196 assert(DefaultValue->getType() == ValueType);
7197 for (uint64_t I = 0; I < TableSize; ++I) {
7198 if (!TableContents[I])
7199 TableContents[I] = DefaultValue;
7200 }
7201
7202 // If the default value is poison, all the holes are poison.
7203 bool DefaultValueIsPoison = isa<PoisonValue>(DefaultValue);
7204
7205 if (DefaultValue != SingleValue && !DefaultValueIsPoison)
7206 SingleValue = nullptr;
7207 }
7208
7209 // If each element in the table contains the same value, we only need to store
7210 // that single value.
7211 if (SingleValue) {
7212 Kind = SingleValueKind;
7213 return;
7214 }
7215
7216 // Check if we can derive the value with a linear transformation from the
7217 // table index.
7219 bool LinearMappingPossible = true;
7220 APInt PrevVal;
7221 APInt DistToPrev;
7222 // When linear map is monotonic and signed overflow doesn't happen on
7223 // maximum index, we can attach nsw on Add and Mul.
7224 bool NonMonotonic = false;
7225 assert(TableSize >= 2 && "Should be a SingleValue table.");
7226 // Check if there is the same distance between two consecutive values.
7227 for (uint64_t I = 0; I < TableSize; ++I) {
7228 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
7229
7230 if (!ConstVal && isa<PoisonValue>(TableContents[I])) {
7231 // This is an poison, so it's (probably) a lookup table hole.
7232 // To prevent any regressions from before we switched to using poison as
7233 // the default value, holes will fall back to using the first value.
7234 // This can be removed once we add proper handling for poisons in lookup
7235 // tables.
7236 ConstVal = dyn_cast<ConstantInt>(Values[0].second);
7237 }
7238
7239 if (!ConstVal) {
7240 // We only handle literal integers when checking for a linear mapping.
7241 LinearMappingPossible = false;
7242 break;
7243 }
7244 const APInt &Val = ConstVal->getValue();
7245 if (I != 0) {
7246 APInt Dist = Val - PrevVal;
7247 if (I == 1) {
7248 DistToPrev = Dist;
7249 } else if (Dist != DistToPrev) {
7250 LinearMappingPossible = false;
7251 break;
7252 }
7253 NonMonotonic |=
7254 Dist.isStrictlyPositive() ? Val.sle(PrevVal) : Val.sgt(PrevVal);
7255 }
7256 PrevVal = Val;
7257 }
7258 if (LinearMappingPossible) {
7259 LinearOffset = cast<ConstantInt>(TableContents[0]);
7260 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
7261 APInt M = LinearMultiplier->getValue();
7262 bool MayWrap = true;
7263 if (isIntN(M.getBitWidth(), TableSize - 1))
7264 (void)M.smul_ov(APInt(M.getBitWidth(), TableSize - 1), MayWrap);
7265 LinearMapValWrapped = NonMonotonic || MayWrap;
7266 Kind = LinearMapKind;
7267 return;
7268 }
7269 }
7270
7271 // If the values are integer constants and the table fits in a register,
7272 // build a bitmap.
7273 if (wouldFitInRegister(DL, TableSize, ValueType) &&
7274 all_of(TableContents, IsaPred<ConstantInt, UndefValue>)) {
7276 APInt TableInt(TableSize * IT->getBitWidth(), 0);
7277 for (uint64_t I = TableSize; I > 0; --I) {
7278 TableInt <<= IT->getBitWidth();
7279 // Insert values into the bitmap. Undef values are set to zero.
7280 if (!isa<UndefValue>(TableContents[I - 1])) {
7281 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
7282 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
7283 }
7284 }
7285 BitMap = ConstantInt::get(M.getContext(), TableInt);
7286 BitMapElementTy = IT;
7287 Kind = BitMapKind;
7288 return;
7289 }
7290
7291 // The remaining representation needs a global initializer.
7292 if (!all_of(TableContents,
7293 [&](Constant *C) { return validLookupTableConstant(C, TTI); })) {
7294 Kind = InvalidKind;
7295 return;
7296 }
7297
7298 if (auto *IT = dyn_cast<IntegerType>(ValueType)) {
7299 ConstantRange Range(IT->getBitWidth(), false);
7300 for (Constant *Value : TableContents)
7301 if (!isa<UndefValue>(Value))
7302 Range = Range.unionWith(cast<ConstantInt>(Value)->getValue());
7303 // TODO: handle sign extension as well?
7304 unsigned NeededBitWidth =
7305 std::max(TTI.getMinimumLookupTableEntryBitWidth(),
7306 unsigned(PowerOf2Ceil(Range.getActiveBits())));
7307 if (NeededBitWidth < IT->getBitWidth()) {
7308 IntegerType *DstTy = IntegerType::get(IT->getContext(), NeededBitWidth);
7309 for (Constant *&Value : TableContents)
7310 Value = ConstantFoldCastInstruction(Instruction::Trunc, Value, DstTy);
7311 }
7312 }
7313
7314 // Store the table in an array.
7315 auto *TableTy = ArrayType::get(TableContents[0]->getType(), TableSize);
7316 Initializer = ConstantArray::get(TableTy, TableContents);
7317
7318 Kind = LookupTableKind;
7319}
7320
7321Value *SwitchReplacement::replaceSwitch(Value *Index, IRBuilder<> &Builder,
7322 const DataLayout &DL, Function *Func) {
7323 switch (Kind) {
7324 case InvalidKind:
7325 llvm_unreachable("Cannot use an invalid switch replacement");
7326 case SingleValueKind:
7327 return SingleValue;
7328 case LinearMapKind: {
7329 ++NumLinearMaps;
7330 // Derive the result value from the input value.
7331 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
7332 false, "switch.idx.cast");
7333 if (!LinearMultiplier->isOne())
7334 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult",
7335 /*HasNUW = */ false,
7336 /*HasNSW = */ !LinearMapValWrapped);
7337
7338 if (!LinearOffset->isZero())
7339 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset",
7340 /*HasNUW = */ false,
7341 /*HasNSW = */ !LinearMapValWrapped);
7342 return Result;
7343 }
7344 case BitMapKind: {
7345 ++NumBitMaps;
7346 // Type of the bitmap (e.g. i59).
7347 IntegerType *MapTy = BitMap->getIntegerType();
7348
7349 // Cast Index to the same type as the bitmap.
7350 // Note: The Index is <= the number of elements in the table, so
7351 // truncating it to the width of the bitmask is safe.
7352 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
7353
7354 // Multiply the shift amount by the element width. NUW/NSW can always be
7355 // set, because wouldFitInRegister guarantees Index * ShiftAmt is in
7356 // BitMap's bit width.
7357 ShiftAmt = Builder.CreateMul(
7358 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
7359 "switch.shiftamt",/*HasNUW =*/true,/*HasNSW =*/true);
7360
7361 // Shift down.
7362 Value *DownShifted =
7363 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
7364 // Mask off.
7365 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
7366 }
7367 case LookupTableKind: {
7368 ++NumLookupTables;
7369 auto *Table =
7370 new GlobalVariable(*Func->getParent(), Initializer->getType(),
7371 /*isConstant=*/true, GlobalVariable::PrivateLinkage,
7372 Initializer, "switch.table." + Func->getName());
7373 Table->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7374 // Set the alignment to that of an array items. We will be only loading one
7375 // value out of it.
7376 Table->setAlignment(DL.getPrefTypeAlign(ValueType));
7377 Type *IndexTy = DL.getIndexType(Table->getType());
7378 auto *ArrayTy = cast<ArrayType>(Table->getValueType());
7379
7380 if (Index->getType() != IndexTy) {
7381 unsigned OldBitWidth = Index->getType()->getIntegerBitWidth();
7382 Index = Builder.CreateZExtOrTrunc(Index, IndexTy);
7383 if (auto *Zext = dyn_cast<ZExtInst>(Index))
7384 Zext->setNonNeg(
7385 isUIntN(OldBitWidth - 1, ArrayTy->getNumElements() - 1));
7386 }
7387
7388 Value *GEPIndices[] = {ConstantInt::get(IndexTy, 0), Index};
7389 Value *GEP =
7390 Builder.CreateInBoundsGEP(ArrayTy, Table, GEPIndices, "switch.gep");
7391 Value *Load =
7392 Builder.CreateLoad(ArrayTy->getElementType(), GEP, "switch.load");
7393 if (Load->getType() == ValueType)
7394 return Load;
7395 return Builder.CreateZExt(Load, ValueType, "switch.ext");
7396 }
7397 }
7398 llvm_unreachable("Unknown helper kind!");
7399}
7400
7401bool SwitchReplacement::wouldFitInRegister(const DataLayout &DL,
7402 uint64_t TableSize,
7403 Type *ElementType) {
7404 auto *IT = dyn_cast<IntegerType>(ElementType);
7405 if (!IT)
7406 return false;
7407 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
7408 // are <= 15, we could try to narrow the type.
7409
7410 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
7411 if (TableSize >= UINT_MAX / IT->getBitWidth())
7412 return false;
7413 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
7414}
7415
7417 const DataLayout &DL) {
7418 // Allow any legal type.
7419 if (TTI.isTypeLegal(Ty))
7420 return true;
7421
7422 auto *IT = dyn_cast<IntegerType>(Ty);
7423 if (!IT)
7424 return false;
7425
7426 // Also allow power of 2 integer types that have at least 8 bits and fit in
7427 // a register. These types are common in frontend languages and targets
7428 // usually support loads of these types.
7429 // TODO: We could relax this to any integer that fits in a register and rely
7430 // on ABI alignment and padding in the table to allow the load to be widened.
7431 // Or we could widen the constants and truncate the load.
7432 unsigned BitWidth = IT->getBitWidth();
7433 return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
7434 DL.fitsInLegalInteger(IT->getBitWidth());
7435}
7436
7437Constant *SwitchReplacement::getDefaultValue() { return DefaultValue; }
7438
7439bool SwitchReplacement::isLookupTable() { return Kind == LookupTableKind; }
7440
7441bool SwitchReplacement::isBitMap() { return Kind == BitMapKind; }
7442
7443static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize) {
7444 // 40% is the default density for building a jump table in optsize/minsize
7445 // mode, 10% is the default density for jump tables. See also
7446 // TargetLoweringBase::isSuitableForJumpTable(), which this function was based
7447 // on.
7448 const uint64_t MinDensity = OptSize ? 40 : 10;
7449
7450 if (CaseRange >= UINT64_MAX / 100)
7451 return false; // Avoid multiplication overflows below.
7452
7453 return NumCases * 100 >= CaseRange * MinDensity;
7454}
7455
7456static bool isSwitchDense(ArrayRef<int64_t> Values, bool OptSize) {
7457 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
7458 uint64_t Range = Diff + 1;
7459 if (Range < Diff)
7460 return false; // Overflow.
7461
7462 return isSwitchDense(Values.size(), Range, OptSize);
7463}
7464
7465static std::optional<unsigned>
7467 bool OptSize) {
7468 assert(Values.size() > 1 && "expected multiple switch cases");
7469 if (!llvm::all_of(Values, [Base](int64_t V) { return V >= Base; }))
7470 return std::nullopt;
7471
7472 // First, transform the values by subtracting Base.
7473 SmallVector<int64_t, 4> ReducedValues(Values);
7474 uint64_t ReducedValuesOr = 0;
7475 for (auto &V : ReducedValues) {
7476 uint64_t Reduced = (uint64_t)V - (uint64_t)Base;
7477 ReducedValuesOr |= Reduced;
7478 V = (int64_t)Reduced;
7479 }
7480
7481 // Conceptually, the reduced values are non-negative distances from Base.
7482 // Since the rest of the transform is bitwise only, treat them as unsigned
7483 // bit patterns from here.
7484
7485 // countr_zero(0) returns 64. As Values is guaranteed to have more than
7486 // one element and LLVM disallows duplicate cases, ReducedValuesOr will
7487 // have at least one bit set, so Shift will be less than 64.
7488 unsigned Shift = llvm::countr_zero(ReducedValuesOr);
7489 assert(Shift < 64);
7490 if (Shift > 0)
7491 for (auto &V : ReducedValues)
7492 V = (int64_t)((uint64_t)V >> Shift);
7493
7494 if (!isSwitchDense(ReducedValues, OptSize))
7495 return std::nullopt;
7496
7497 return Shift;
7498}
7499
7500/// Determine whether a lookup table should be built for this switch, based on
7501/// the number of cases, size of the table, and the types of the results.
7502// TODO: We could support larger than legal types by limiting based on the
7503// number of loads required and/or table size. If the constants are small we
7504// could use smaller table entries and extend after the load.
7506 const TargetTransformInfo &TTI,
7507 const DataLayout &DL,
7508 const SmallVector<Type *> &ResultTypes) {
7509 if (SI->getNumCases() > TableSize)
7510 return false; // TableSize overflowed.
7511
7512 bool AllTablesFitInRegister = true;
7513 bool HasIllegalType = false;
7514 for (const auto &Ty : ResultTypes) {
7515 // Saturate this flag to true.
7516 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
7517
7518 // Saturate this flag to false.
7519 AllTablesFitInRegister =
7520 AllTablesFitInRegister &&
7521 SwitchReplacement::wouldFitInRegister(DL, TableSize, Ty);
7522
7523 // If both flags saturate, we're done. NOTE: This *only* works with
7524 // saturating flags, and all flags have to saturate first due to the
7525 // non-deterministic behavior of iterating over a dense map.
7526 if (HasIllegalType && !AllTablesFitInRegister)
7527 break;
7528 }
7529
7530 // If each table would fit in a register, we should build it anyway.
7531 if (AllTablesFitInRegister)
7532 return true;
7533
7534 // Don't build a table that doesn't fit in-register if it has illegal types.
7535 if (HasIllegalType)
7536 return false;
7537
7538 return isSwitchDense(SI->getNumCases(), TableSize,
7539 SI->getFunction()->hasOptSize());
7540}
7541
7543 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
7544 bool HasDefaultResults, const SmallVector<Type *> &ResultTypes,
7545 const DataLayout &DL, const TargetTransformInfo &TTI) {
7546 if (MinCaseVal.isNullValue())
7547 return true;
7548 if (MinCaseVal.isNegative() ||
7549 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
7550 !HasDefaultResults)
7551 return false;
7552 return all_of(ResultTypes, [&](const auto &ResultType) {
7553 return SwitchReplacement::wouldFitInRegister(
7554 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */, ResultType);
7555 });
7556}
7557
7558/// Try to reuse the switch table index compare. Following pattern:
7559/// \code
7560/// if (idx < tablesize)
7561/// r = table[idx]; // table does not contain default_value
7562/// else
7563/// r = default_value;
7564/// if (r != default_value)
7565/// ...
7566/// \endcode
7567/// Is optimized to:
7568/// \code
7569/// cond = idx < tablesize;
7570/// if (cond)
7571/// r = table[idx];
7572/// else
7573/// r = default_value;
7574/// if (cond)
7575/// ...
7576/// \endcode
7577/// Jump threading will then eliminate the second if(cond).
7579 User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
7580 Constant *DefaultValue,
7581 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
7583 if (!CmpInst)
7584 return;
7585
7586 // We require that the compare is in the same block as the phi so that jump
7587 // threading can do its work afterwards.
7588 if (CmpInst->getParent() != PhiBlock)
7589 return;
7590
7592 if (!CmpOp1)
7593 return;
7594
7595 Value *RangeCmp = RangeCheckBranch->getCondition();
7596 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
7597 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
7598
7599 // Check if the compare with the default value is constant true or false.
7600 const DataLayout &DL = PhiBlock->getDataLayout();
7602 CmpInst->getPredicate(), DefaultValue, CmpOp1, DL);
7603 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
7604 return;
7605
7606 // Check if the compare with the case values is distinct from the default
7607 // compare result.
7608 for (auto ValuePair : Values) {
7610 CmpInst->getPredicate(), ValuePair.second, CmpOp1, DL);
7611 if (!CaseConst || CaseConst == DefaultConst ||
7612 (CaseConst != TrueConst && CaseConst != FalseConst))
7613 return;
7614 }
7615
7616 // Check if the branch instruction dominates the phi node. It's a simple
7617 // dominance check, but sufficient for our needs.
7618 // Although this check is invariant in the calling loops, it's better to do it
7619 // at this late stage. Practically we do it at most once for a switch.
7620 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
7621 for (BasicBlock *Pred : predecessors(PhiBlock)) {
7622 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
7623 return;
7624 }
7625
7626 if (DefaultConst == FalseConst) {
7627 // The compare yields the same result. We can replace it.
7628 CmpInst->replaceAllUsesWith(RangeCmp);
7629 ++NumTableCmpReuses;
7630 } else {
7631 // The compare yields the same result, just inverted. We can replace it.
7632 Value *InvertedTableCmp = BinaryOperator::CreateXor(
7633 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
7634 RangeCheckBranch->getIterator());
7635 CmpInst->replaceAllUsesWith(InvertedTableCmp);
7636 ++NumTableCmpReuses;
7637 }
7638}
7639
7640/// If the switch is only used to initialize one or more phi nodes in a common
7641/// successor block with different constant values, replace the switch with
7642/// lookup tables.
7644 DomTreeUpdater *DTU, const DataLayout &DL,
7645 const TargetTransformInfo &TTI,
7646 bool ConvertSwitchToLookupTable) {
7647 assert(SI->getNumCases() > 1 && "Degenerate switch?");
7648
7649 BasicBlock *BB = SI->getParent();
7650 Function *Fn = BB->getParent();
7651
7652 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
7653 // split off a dense part and build a lookup table for that.
7654
7655 // FIXME: This creates arrays of GEPs to constant strings, which means each
7656 // GEP needs a runtime relocation in PIC code. We should just build one big
7657 // string and lookup indices into that.
7658
7659 // Ignore switches with less than three cases. Lookup tables will not make
7660 // them faster, so we don't analyze them.
7661 if (SI->getNumCases() < 3)
7662 return false;
7663
7664 // Figure out the corresponding result for each case value and phi node in the
7665 // common destination, as well as the min and max case values.
7666 assert(!SI->cases().empty());
7667 SwitchInst::CaseIt CI = SI->case_begin();
7668 ConstantInt *MinCaseVal = CI->getCaseValue();
7669 ConstantInt *MaxCaseVal = CI->getCaseValue();
7670
7671 BasicBlock *CommonDest = nullptr;
7672
7673 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
7675
7677 SmallVector<Type *> ResultTypes;
7679
7680 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
7681 ConstantInt *CaseVal = CI->getCaseValue();
7682 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
7683 MinCaseVal = CaseVal;
7684 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
7685 MaxCaseVal = CaseVal;
7686
7687 // Resulting value at phi nodes for this case value.
7689 ResultsTy Results;
7690 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
7691 Results, DL))
7692 return false;
7693
7694 // Append the result and result types from this case to the list for each
7695 // phi.
7696 for (const auto &I : Results) {
7697 PHINode *PHI = I.first;
7698 Constant *Value = I.second;
7699 auto [It, Inserted] = ResultLists.try_emplace(PHI);
7700 if (Inserted)
7701 PHIs.push_back(PHI);
7702 It->second.push_back(std::make_pair(CaseVal, Value));
7703 ResultTypes.push_back(PHI->getType());
7704 }
7705 }
7706
7707 // If the table has holes, we need a constant result for the default case
7708 // or a bitmask that fits in a register.
7709 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
7710 bool HasDefaultResults = getCaseResults(SI, nullptr, SI->getDefaultDest(),
7711 &CommonDest, DefaultResultsList, DL);
7712 for (const auto &I : DefaultResultsList) {
7713 PHINode *PHI = I.first;
7714 Constant *Result = I.second;
7715 DefaultResults[PHI] = Result;
7716 }
7717
7718 bool UseSwitchConditionAsTableIndex = shouldUseSwitchConditionAsTableIndex(
7719 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
7720 uint64_t TableSize;
7721 ConstantInt *TableIndexOffset;
7722 if (UseSwitchConditionAsTableIndex) {
7723 TableSize = MaxCaseVal->getLimitedValue() + 1;
7724 TableIndexOffset = ConstantInt::get(MaxCaseVal->getIntegerType(), 0);
7725 } else {
7726 TableSize =
7727 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
7728
7729 TableIndexOffset = MinCaseVal;
7730 }
7731
7732 // If the default destination is unreachable, or if the lookup table covers
7733 // all values of the conditional variable, branch directly to the lookup table
7734 // BB. Otherwise, check that the condition is within the case range.
7735 uint64_t NumResults = ResultLists[PHIs[0]].size();
7736 bool DefaultIsReachable = !SI->defaultDestUnreachable();
7737
7738 bool TableHasHoles = (NumResults < TableSize);
7739
7740 // If the table has holes but the default destination doesn't produce any
7741 // constant results, the lookup table entries corresponding to the holes will
7742 // contain poison.
7743 bool AllHolesArePoison = TableHasHoles && !HasDefaultResults;
7744
7745 // If the default destination doesn't produce a constant result but is still
7746 // reachable, and the lookup table has holes, we need to use a mask to
7747 // determine if the current index should load from the lookup table or jump
7748 // to the default case.
7749 // The mask is unnecessary if the table has holes but the default destination
7750 // is unreachable, as in that case the holes must also be unreachable.
7751 bool NeedMask = AllHolesArePoison && DefaultIsReachable;
7752 if (NeedMask) {
7753 // As an extra penalty for the validity test we require more cases.
7754 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
7755 return false;
7756 if (!DL.fitsInLegalInteger(TableSize))
7757 return false;
7758 }
7759
7760 if (!shouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
7761 return false;
7762
7763 // Compute the table index value.
7764 Value *TableIndex;
7765 if (UseSwitchConditionAsTableIndex) {
7766 TableIndex = SI->getCondition();
7767 if (HasDefaultResults) {
7768 // Grow the table to cover all possible index values to avoid the range
7769 // check. It will use the default result to fill in the table hole later,
7770 // so make sure it exist.
7771 ConstantRange CR = computeConstantRange(TableIndex, /*ForSigned=*/false,
7772 SimplifyQuery(DL));
7773 // Grow the table shouldn't have any size impact by checking
7774 // wouldFitInRegister.
7775 // TODO: Consider growing the table also when it doesn't fit in a register
7776 // if no optsize is specified.
7777 const uint64_t UpperBound = CR.getUpper().getLimitedValue();
7778 if (!CR.isUpperWrapped() &&
7779 all_of(ResultTypes, [&](const auto &ResultType) {
7780 return SwitchReplacement::wouldFitInRegister(DL, UpperBound,
7781 ResultType);
7782 })) {
7783 // There may be some case index larger than the UpperBound (unreachable
7784 // case), so make sure the table size does not get smaller.
7785 TableSize = std::max(UpperBound, TableSize);
7786 // The default branch is unreachable after we enlarge the lookup table.
7787 // Adjust DefaultIsReachable to reuse code path.
7788 DefaultIsReachable = false;
7789 }
7790 }
7791 }
7792
7793 // Keep track of the switch replacement for each phi
7795 for (PHINode *PHI : PHIs) {
7796 const auto &ResultList = ResultLists[PHI];
7797
7798 Type *ResultType = ResultList.begin()->second->getType();
7799 // Use any value to fill the lookup table holes.
7800 Constant *DefaultVal =
7801 AllHolesArePoison ? PoisonValue::get(ResultType) : DefaultResults[PHI];
7802 StringRef FuncName = Fn->getName();
7803 SwitchReplacement Replacement(*Fn->getParent(), TableSize, TableIndexOffset,
7804 ResultList, DefaultVal, DL, TTI, FuncName);
7805 if (!Replacement.isValid())
7806 return false;
7807 PhiToReplacementMap.insert({PHI, Replacement});
7808 }
7809
7810 bool AnyLookupTables = any_of(
7811 PhiToReplacementMap, [](auto &KV) { return KV.second.isLookupTable(); });
7812 bool AnyBitMaps = any_of(PhiToReplacementMap,
7813 [](auto &KV) { return KV.second.isBitMap(); });
7814
7815 // A few conditions prevent the generation of lookup tables:
7816 // 1. The target does not support lookup tables.
7817 // 2. The "no-jump-tables" function attribute is set.
7818 // However, these objections do not apply to other switch replacements, like
7819 // the bitmap, so we only stop here if any of these conditions are met and we
7820 // want to create a LUT. Otherwise, continue with the switch replacement.
7821 if (AnyLookupTables &&
7822 (!TTI.shouldBuildLookupTables() ||
7823 Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
7824 return false;
7825
7826 // In the early optimization pipeline, disable formation of lookup tables,
7827 // bit maps and mask checks, as they may inhibit further optimization.
7828 if (!ConvertSwitchToLookupTable &&
7829 (AnyLookupTables || AnyBitMaps || NeedMask))
7830 return false;
7831
7832 Builder.SetInsertPoint(SI);
7833 // TableIndex is the switch condition - TableIndexOffset if we don't
7834 // use the condition directly
7835 if (!UseSwitchConditionAsTableIndex) {
7836 // If the default is unreachable, all case values are s>= MinCaseVal. Then
7837 // we can try to attach nsw.
7838 bool MayWrap = true;
7839 if (!DefaultIsReachable) {
7840 APInt Res =
7841 MaxCaseVal->getValue().ssub_ov(MinCaseVal->getValue(), MayWrap);
7842 (void)Res;
7843 }
7844 TableIndex = Builder.CreateSub(SI->getCondition(), TableIndexOffset,
7845 "switch.tableidx", /*HasNUW =*/false,
7846 /*HasNSW =*/!MayWrap);
7847 }
7848
7849 std::vector<DominatorTree::UpdateType> Updates;
7850
7851 // Compute the maximum table size representable by the integer type we are
7852 // switching upon.
7853 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
7854 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
7855 assert(MaxTableSize >= TableSize &&
7856 "It is impossible for a switch to have more entries than the max "
7857 "representable value of its input integer type's size.");
7858
7859 // Create the BB that does the lookups.
7860 Module &Mod = *CommonDest->getParent()->getParent();
7861 BasicBlock *LookupBB = BasicBlock::Create(
7862 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
7863
7864 CondBrInst *RangeCheckBranch = nullptr;
7865 CondBrInst *CondBranch = nullptr;
7866
7867 Builder.SetInsertPoint(SI);
7868 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
7869 const bool IsFullyCoveredLookupTable =
7870 !DefaultIsReachable || GeneratingCoveredLookupTable;
7871 if (IsFullyCoveredLookupTable) {
7872 Builder.CreateBr(LookupBB);
7873 if (DTU)
7874 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7875 // Note: We call removeProdecessor later since we need to be able to get the
7876 // PHI value for the default case in case we're using a bit mask.
7877 } else {
7878 Value *Cmp = Builder.CreateICmpULT(
7879 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
7880 RangeCheckBranch =
7881 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
7882 CondBranch = RangeCheckBranch;
7883 if (DTU)
7884 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
7885 }
7886
7887 // Populate the BB that does the lookups.
7888 Builder.SetInsertPoint(LookupBB);
7889
7890 if (NeedMask) {
7891 // Before doing the lookup, we do the hole check. The LookupBB is therefore
7892 // re-purposed to do the hole check, and we create a new LookupBB.
7893 BasicBlock *MaskBB = LookupBB;
7894 MaskBB->setName("switch.hole_check");
7895 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
7896 CommonDest->getParent(), CommonDest);
7897
7898 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
7899 // unnecessary illegal types.
7900 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
7901 APInt MaskInt(TableSizePowOf2, 0);
7902 APInt One(TableSizePowOf2, 1);
7903 // Build bitmask; fill in a 1 bit for every case.
7904 const ResultListTy &ResultList = ResultLists[PHIs[0]];
7905 for (const auto &Result : ResultList) {
7906 uint64_t Idx = (Result.first->getValue() - TableIndexOffset->getValue())
7907 .getLimitedValue();
7908 MaskInt |= One << Idx;
7909 }
7910 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
7911
7912 // Get the TableIndex'th bit of the bitmask.
7913 // If this bit is 0 (meaning hole) jump to the default destination,
7914 // else continue with table lookup.
7915 IntegerType *MapTy = TableMask->getIntegerType();
7916 Value *MaskIndex =
7917 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
7918 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
7919 Value *LoBit = Builder.CreateTrunc(
7920 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
7921 if (!IsFullyCoveredLookupTable)
7923 CondBranch = Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
7924 if (DTU) {
7925 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
7926 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
7927 }
7928 Builder.SetInsertPoint(LookupBB);
7929 addPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
7930 }
7931
7932 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7933 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
7934 // do not delete PHINodes here.
7935 SI->getDefaultDest()->removePredecessor(BB,
7936 /*KeepOneInputPHIs=*/true);
7937 if (DTU)
7938 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
7939 }
7940
7941 for (PHINode *PHI : PHIs) {
7942 const ResultListTy &ResultList = ResultLists[PHI];
7943 auto Replacement = PhiToReplacementMap.at(PHI);
7944 auto *Result = Replacement.replaceSwitch(TableIndex, Builder, DL, Fn);
7945 // Do a small peephole optimization: re-use the switch table compare if
7946 // possible.
7947 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
7948 BasicBlock *PhiBlock = PHI->getParent();
7949 // Search for compare instructions which use the phi.
7950 for (auto *User : PHI->users()) {
7951 reuseTableCompare(User, PhiBlock, RangeCheckBranch,
7952 Replacement.getDefaultValue(), ResultList);
7953 }
7954 }
7955
7956 PHI->addIncoming(Result, LookupBB);
7957 }
7958
7959 Builder.CreateBr(CommonDest);
7960 if (DTU)
7961 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
7962
7963 SmallVector<uint32_t> BranchWeights;
7964 const bool HasBranchWeights =
7965 CondBranch && extractBranchWeights(*SI, BranchWeights);
7966 uint64_t ToLookupWeight = 0;
7967 uint64_t ToDefaultWeight = 0;
7968
7969 // Remove the switch.
7970 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
7971 for (unsigned I = 0, E = SI->getNumSuccessors(); I < E; ++I) {
7972 BasicBlock *Succ = SI->getSuccessor(I);
7973
7974 if (Succ == SI->getDefaultDest()) {
7975 if (HasBranchWeights)
7976 ToDefaultWeight += BranchWeights[I];
7977 continue;
7978 }
7979 Succ->removePredecessor(BB);
7980 if (DTU && RemovedSuccessors.insert(Succ).second)
7981 Updates.push_back({DominatorTree::Delete, BB, Succ});
7982 if (HasBranchWeights)
7983 ToLookupWeight += BranchWeights[I];
7984 }
7985 SI->eraseFromParent();
7986 // In the case where we do not have a fully covered lookup table (i.e., we
7987 // need a range check), and we need a mask check, we split the default case
7988 // into two different cases for which we cannot infer branch weights.
7989 // Otherwise we have a single branch for which we can infer branch weights.
7990 if ((NeedMask && !IsFullyCoveredLookupTable) &&
7993 else if (HasBranchWeights)
7994 setFittedBranchWeights(*CondBranch, {ToLookupWeight, ToDefaultWeight},
7995 /*IsExpected=*/false);
7996 if (DTU)
7997 DTU->applyUpdates(Updates);
7998
7999 if (NeedMask)
8000 ++NumLookupTablesHoles;
8001 return true;
8002}
8003
8004/// Try to transform a switch that has "holes" in it to a contiguous sequence
8005/// of cases.
8006///
8007/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
8008/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
8009///
8010/// This converts a sparse switch into a dense switch which allows better
8011/// lowering and could also allow transforming into a lookup table.
8013 const DataLayout &DL,
8014 const TargetTransformInfo &TTI) {
8015 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
8016 if (CondTy->getIntegerBitWidth() > 64 ||
8017 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8018 return false;
8019 // Only bother with this optimization if there are more than 3 switch cases;
8020 // SDAG will only bother creating jump tables for 4 or more cases.
8021 if (SI->getNumCases() < 4)
8022 return false;
8023
8024 // This transform is agnostic to the signedness of the input or case values. We
8025 // can treat the case values as signed or unsigned. We can optimize more common
8026 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
8027 // as signed.
8029 for (const auto &C : SI->cases())
8030 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
8032
8033 // If the switch is already dense, there's nothing useful to do here.
8034 bool OptSize = SI->getFunction()->hasOptSize();
8035 if (isSwitchDense(Values, OptSize))
8036 return false;
8037
8038 // Find a Base and corresponding Shift that results in a dense switch range.
8039 // Values[0] is the local minimum.
8040 int64_t Base = Values[0];
8041 std::optional<unsigned> Shift;
8042 // Prefer Base=0 when shifting out common low zero bits still produces a dense
8043 // range, as this avoids an unnecessary `(condition - local_min)` expression.
8044 // However, avoiding the subtract can leave a wider reduced range than using
8045 // the local minimum, so require Base=0 to satisfy the stricter optsize
8046 // density threshold before falling back to the normal density policy for
8047 // local-min.
8048 if ((Shift = getDenseSwitchRangeReductionShift(Values, /*Base=*/0,
8049 /*OptSize=*/true)))
8050 Base = 0;
8051 else if (Base != 0)
8053
8054 if (!Shift)
8055 return false;
8056
8057 // The obvious transform is to shift the switch condition right and emit a
8058 // check that the condition actually cleanly divided by GCD, i.e.
8059 // C & (1 << Shift - 1) == 0
8060 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
8061 //
8062 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
8063 // shift and puts the shifted-off bits in the uppermost bits. If any of these
8064 // are nonzero then the switch condition will be very large and will hit the
8065 // default case.
8066 //
8067 // This transform can be done speculatively because it is so cheap - it
8068 // results in a single rotate operation being inserted.
8069
8070 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
8071 Builder.SetInsertPoint(SI);
8072 Value *Sub = SI->getCondition();
8073 if (Base != 0)
8074 Sub = Builder.CreateSub(Sub, ConstantInt::getSigned(Ty, Base));
8075 Value *Rot = Builder.CreateIntrinsic(
8076 Ty, Intrinsic::fshl,
8077 {Sub, Sub, ConstantInt::get(Ty, Ty->getBitWidth() - *Shift)});
8078 SI->replaceUsesOfWith(SI->getCondition(), Rot);
8079
8080 for (auto Case : SI->cases()) {
8081 auto *Orig = Case.getCaseValue();
8082 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base, true);
8083 Case.setValue(cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(*Shift))));
8084 }
8085 return true;
8086}
8087
8088/// Tries to transform the switch when the condition is umin with a constant.
8089/// In that case, the default branch can be replaced by the constant's branch.
8090/// This method also removes dead cases when the simplification cannot replace
8091/// the default branch.
8092///
8093/// For example:
8094/// switch(umin(a, 3)) {
8095/// case 0:
8096/// case 1:
8097/// case 2:
8098/// case 3:
8099/// case 4:
8100/// // ...
8101/// default:
8102/// unreachable
8103/// }
8104///
8105/// Transforms into:
8106///
8107/// switch(a) {
8108/// case 0:
8109/// case 1:
8110/// case 2:
8111/// default:
8112/// // This is case 3
8113/// }
8115 Value *A;
8117
8118 if (!match(SI->getCondition(), m_UMin(m_Value(A), m_ConstantInt(Constant))))
8119 return false;
8120
8123 BasicBlock *BB = SIW->getParent();
8124
8125 // Dead cases are removed even when the simplification fails.
8126 // A case is dead when its value is higher than the Constant.
8127 for (auto I = SI->case_begin(), E = SI->case_end(); I != E;) {
8128 if (!I->getCaseValue()->getValue().ugt(Constant->getValue())) {
8129 ++I;
8130 continue;
8131 }
8132 BasicBlock *DeadCaseBB = I->getCaseSuccessor();
8133 DeadCaseBB->removePredecessor(BB);
8134 I = SIW.removeCase(I);
8135 E = SIW->case_end();
8136 if (!is_contained(successors(BB), DeadCaseBB))
8137 Updates.push_back({DominatorTree::Delete, BB, DeadCaseBB});
8138 }
8139
8140 auto Case = SI->findCaseValue(Constant);
8141 // If the case value is not found, `findCaseValue` returns the default case.
8142 // In this scenario, since there is no explicit `case 3:`, the simplification
8143 // fails. The simplification also fails when the switch’s default destination
8144 // is reachable.
8145 if (!SI->defaultDestUnreachable() || Case == SI->case_default()) {
8146 if (DTU)
8147 DTU->applyUpdates(Updates);
8148 return !Updates.empty();
8149 }
8150
8151 BasicBlock *Unreachable = SI->getDefaultDest();
8152 SIW.replaceDefaultDest(Case);
8153 SIW.removeCase(Case);
8154 SIW->setCondition(A);
8155
8156 Updates.push_back({DominatorTree::Delete, BB, Unreachable});
8157
8158 if (DTU)
8159 DTU->applyUpdates(Updates);
8160
8161 return true;
8162}
8163
8165 const DataLayout &DL,
8166 AssumptionCache *AC) {
8167 assert(SI);
8168 if (SI->defaultDestUnreachable())
8169 return false;
8170
8171 // If it can be proved that the switch condition takes some concrete value
8172 // in the default block, we can make some nice simplifications to the
8173 // switch.
8174 BasicBlock *Default = SI->getDefaultDest();
8175 const Instruction *CtxI = &*Default->getFirstNonPHIIt();
8177 SI->getCondition(),
8178 SimplifyQuery(DL, /*DT=*/nullptr, AC, CtxI).allowEphemerals(true));
8179 if (!Known.isConstant())
8180 return false;
8181
8182 // At this point, we know that only one value can be mapped to the
8183 // default block. So, if a case doesn't exist for it already, we
8184 // can create one pointing to the default block.
8185 ConstantInt *CaseVal =
8186 ConstantInt::get(SI->getContext(), Known.getConstant());
8187 const llvm::SwitchInst::CaseIt CaseIt = SI->findCaseValue(CaseVal);
8188 if (CaseIt == SI->case_default()) {
8190 SIW.addCase(CaseVal, Default, SIW.getSuccessorWeight(0));
8191 SIW.setSuccessorWeight(0, 0);
8192 }
8193 // If there is a pre-existing case for the constant, the default branch
8194 // will be removed rather than being moved. Thus, we are removing an edge
8195 // in the CFG, and need to update any PHIs in the default block.
8196 createUnreachableSwitchDefault(SI, DTU, /*RemoveOrigDefaultBlock=*/CaseIt !=
8197 SI->case_default());
8198
8199 assert(SI->getNumCases() > 0 && "Switch should have at least one case");
8200 assert(SI->findCaseValue(CaseVal) != SI->case_default() &&
8201 "Proven value should have a dedicated case");
8202 assert(SI->defaultDestUnreachable());
8203 return true;
8204}
8205
8206/// Tries to transform switch of powers of two to reduce switch range.
8207/// For example, switch like:
8208/// switch (C) { case 1: case 2: case 64: case 128: }
8209/// will be transformed to:
8210/// switch (count_trailing_zeros(C)) { case 0: case 1: case 6: case 7: }
8211///
8212/// This transformation allows better lowering and may transform the switch
8213/// instruction into a sequence of bit manipulation and a smaller
8214/// log2(C)-indexed value table (instead of traditionally emitting a load of the
8215/// address of the jump target, and indirectly jump to it).
8217 DomTreeUpdater *DTU,
8218 const DataLayout &DL,
8219 const TargetTransformInfo &TTI) {
8220 Value *Condition = SI->getCondition();
8221 LLVMContext &Context = SI->getContext();
8222 auto *CondTy = cast<IntegerType>(Condition->getType());
8223
8224 if (CondTy->getIntegerBitWidth() > 64 ||
8225 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
8226 return false;
8227
8228 // Ensure trailing zeroes count intrinsic emission is not too expensive.
8229 IntrinsicCostAttributes Attrs(Intrinsic::cttz, CondTy,
8230 {Condition, ConstantInt::getTrue(Context)});
8231 if (TTI.getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) >
8232 TTI::TCC_Basic * 2)
8233 return false;
8234
8235 // Only bother with this optimization if there are more than 3 switch cases.
8236 // SDAG will start emitting jump tables for 4 or more cases.
8237 if (SI->getNumCases() < 4)
8238 return false;
8239
8240 // Check that switch cases are powers of two.
8242 for (const auto &Case : SI->cases()) {
8243 uint64_t CaseValue = Case.getCaseValue()->getValue().getZExtValue();
8244 if (llvm::has_single_bit(CaseValue))
8245 Values.push_back(CaseValue);
8246 else
8247 return false;
8248 }
8249
8250 // isSwichDense requires case values to be sorted.
8252 if (!isSwitchDense(Values.size(),
8253 llvm::countr_zero(Values.back()) -
8254 llvm::countr_zero(Values.front()) + 1,
8255 SI->getFunction()->hasOptSize()))
8256 // Transform is unable to generate dense switch.
8257 return false;
8258
8259 Builder.SetInsertPoint(SI);
8260
8261 if (!SI->defaultDestUnreachable()) {
8262 // Let non-power-of-two inputs jump to the default case, when the latter is
8263 // reachable.
8264 auto *PopC = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Condition);
8265 auto *IsPow2 = Builder.CreateICmpEQ(PopC, ConstantInt::get(CondTy, 1));
8266
8267 auto *OrigBB = SI->getParent();
8268 auto *DefaultCaseBB = SI->getDefaultDest();
8269 BasicBlock *SplitBB = SplitBlock(OrigBB, SI, DTU);
8270 auto It = OrigBB->getTerminator()->getIterator();
8271 SmallVector<uint32_t> Weights;
8272 auto HasWeights = extractBranchWeights(*SI, Weights);
8273 auto *BI = CondBrInst::Create(IsPow2, SplitBB, DefaultCaseBB, It);
8274 if (HasWeights && any_of(Weights, not_equal_to(0))) {
8275 // IsPow2 covers a subset of the cases in which we'd go to the default
8276 // label. The other is those powers of 2 that don't appear in the case
8277 // statement. We don't know the distribution of the values coming in, so
8278 // the safest is to split 50-50 the original probability to `default`.
8279 uint64_t OrigDenominator =
8281 SmallVector<uint64_t> NewWeights(2);
8282 NewWeights[1] = Weights[0] / 2;
8283 NewWeights[0] = OrigDenominator - NewWeights[1];
8284 setFittedBranchWeights(*BI, NewWeights, /*IsExpected=*/false);
8285 // The probability of executing the default block stays constant. It was
8286 // p_d = Weights[0] / OrigDenominator
8287 // we rewrite as W/D
8288 // We want to find the probability of the default branch of the switch
8289 // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
8290 // i.e. the original probability is the probability we go to the default
8291 // branch from the BI branch, or we take the default branch on the SI.
8292 // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
8293 // This matches using W/2 for the default branch probability numerator and
8294 // D-W/2 as the denominator.
8295 Weights[0] = NewWeights[1];
8296 uint64_t CasesDenominator = OrigDenominator - Weights[0];
8297 for (auto &W : drop_begin(Weights))
8298 W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
8299
8300 setBranchWeights(*SI, Weights, /*IsExpected=*/false);
8301 }
8302 // BI is handling the default case for SI, and so should share its DebugLoc.
8303 BI->setDebugLoc(SI->getDebugLoc());
8304 It->eraseFromParent();
8305
8306 addPredecessorToBlock(DefaultCaseBB, OrigBB, SplitBB);
8307 if (DTU)
8308 DTU->applyUpdates({{DominatorTree::Insert, OrigBB, DefaultCaseBB}});
8309 }
8310
8311 // Replace each case with its trailing zeros number.
8312 for (auto &Case : SI->cases()) {
8313 auto *OrigValue = Case.getCaseValue();
8314 Case.setValue(ConstantInt::get(OrigValue->getIntegerType(),
8315 OrigValue->getValue().countr_zero()));
8316 }
8317
8318 // Replace condition with its trailing zeros number.
8319 auto *ConditionTrailingZeros = Builder.CreateIntrinsic(
8320 Intrinsic::cttz, {CondTy}, {Condition, ConstantInt::getTrue(Context)});
8321
8322 SI->setCondition(ConditionTrailingZeros);
8323
8324 return true;
8325}
8326
8327/// Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have
8328/// the same destination.
8330 DomTreeUpdater *DTU) {
8331 auto *Cmp = dyn_cast<CmpIntrinsic>(SI->getCondition());
8332 if (!Cmp || !Cmp->hasOneUse())
8333 return false;
8334
8336 bool HasWeights = extractBranchWeights(getBranchWeightMDNode(*SI), Weights);
8337 if (!HasWeights)
8338 Weights.resize(4); // Avoid checking HasWeights everywhere.
8339
8340 // Normalize to [us]cmp == Res ? Succ : OtherSucc.
8341 int64_t Res;
8342 BasicBlock *Succ, *OtherSucc;
8343 uint32_t SuccWeight = 0, OtherSuccWeight = 0;
8344 BasicBlock *Unreachable = nullptr;
8345
8346 if (SI->getNumCases() == 2) {
8347 // Find which of 1, 0 or -1 is missing (handled by default dest).
8348 SmallSet<int64_t, 3> Missing;
8349 Missing.insert(1);
8350 Missing.insert(0);
8351 Missing.insert(-1);
8352
8353 Succ = SI->getDefaultDest();
8354 SuccWeight = Weights[0];
8355 OtherSucc = nullptr;
8356 for (auto &Case : SI->cases()) {
8357 std::optional<int64_t> Val =
8358 Case.getCaseValue()->getValue().trySExtValue();
8359 if (!Val)
8360 return false;
8361 if (!Missing.erase(*Val))
8362 return false;
8363 if (OtherSucc && OtherSucc != Case.getCaseSuccessor())
8364 return false;
8365 OtherSucc = Case.getCaseSuccessor();
8366 OtherSuccWeight += Weights[Case.getSuccessorIndex()];
8367 }
8368
8369 assert(Missing.size() == 1 && "Should have one case left");
8370 Res = *Missing.begin();
8371 } else if (SI->getNumCases() == 3 && SI->defaultDestUnreachable()) {
8372 // Normalize so that Succ is taken once and OtherSucc twice.
8373 Unreachable = SI->getDefaultDest();
8374 Succ = OtherSucc = nullptr;
8375 for (auto &Case : SI->cases()) {
8376 BasicBlock *NewSucc = Case.getCaseSuccessor();
8377 uint32_t Weight = Weights[Case.getSuccessorIndex()];
8378 if (!OtherSucc || OtherSucc == NewSucc) {
8379 OtherSucc = NewSucc;
8380 OtherSuccWeight += Weight;
8381 } else if (!Succ) {
8382 Succ = NewSucc;
8383 SuccWeight = Weight;
8384 } else if (Succ == NewSucc) {
8385 std::swap(Succ, OtherSucc);
8386 std::swap(SuccWeight, OtherSuccWeight);
8387 } else
8388 return false;
8389 }
8390 for (auto &Case : SI->cases()) {
8391 std::optional<int64_t> Val =
8392 Case.getCaseValue()->getValue().trySExtValue();
8393 if (!Val || (Val != 1 && Val != 0 && Val != -1))
8394 return false;
8395 if (Case.getCaseSuccessor() == Succ) {
8396 Res = *Val;
8397 break;
8398 }
8399 }
8400 } else {
8401 return false;
8402 }
8403
8404 // Determine predicate for the missing case.
8406 switch (Res) {
8407 case 1:
8409 break;
8410 case 0:
8412 break;
8413 case -1:
8415 break;
8416 }
8417 if (Cmp->isSigned())
8419
8420 MDNode *NewWeights = nullptr;
8421 if (HasWeights)
8422 NewWeights = MDBuilder(SI->getContext())
8423 .createBranchWeights(SuccWeight, OtherSuccWeight);
8424
8425 BasicBlock *BB = SI->getParent();
8426 Builder.SetInsertPoint(SI->getIterator());
8427 Value *ICmp = Builder.CreateICmp(Pred, Cmp->getLHS(), Cmp->getRHS());
8428 Builder.CreateCondBr(ICmp, Succ, OtherSucc, NewWeights,
8429 SI->getMetadata(LLVMContext::MD_unpredictable));
8430 OtherSucc->removePredecessor(BB);
8431 if (Unreachable)
8432 Unreachable->removePredecessor(BB);
8433 SI->eraseFromParent();
8434 Cmp->eraseFromParent();
8435 if (DTU && Unreachable)
8436 DTU->applyUpdates({{DominatorTree::Delete, BB, Unreachable}});
8437 return true;
8438}
8439
8440/// Checking whether two BBs are equal depends on the contents of the
8441/// BasicBlock and the incoming values of their successor PHINodes.
8442/// PHINode::getIncomingValueForBlock is O(|Preds|), so we'd like to avoid
8443/// calling this function on each BasicBlock every time isEqual is called,
8444/// especially since the same BasicBlock may be passed as an argument multiple
8445/// times. To do this, we can precompute a map of PHINode -> Pred BasicBlock ->
8446/// IncomingValue and add it in the Wrapper so isEqual can do O(1) checking
8447/// of the incoming values.
8450
8451 // One Phi usually has < 8 incoming values.
8455
8456 // We only merge the identical non-entry BBs with
8457 // - terminator unconditional br to Succ (pending relaxation),
8458 // - does not have address taken / weird control.
8459 static bool canBeMerged(const BasicBlock *BB) {
8460 assert(BB && "Expected non-null BB");
8461 // Entry block cannot be eliminated or have predecessors.
8462 if (BB->isEntryBlock())
8463 return false;
8464
8465 // Single successor and must be Succ.
8466 // FIXME: Relax that the terminator is a BranchInst by checking for equality
8467 // on other kinds of terminators. We decide to only support unconditional
8468 // branches for now for compile time reasons.
8469 auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
8470 if (!BI)
8471 return false;
8472
8473 // Avoid blocks that are "address-taken" (blockaddress) or have unusual
8474 // uses.
8475 if (BB->hasAddressTaken() || BB->isEHPad())
8476 return false;
8477
8478 // TODO: relax this condition to merge equal blocks with >1 instructions?
8479 // Here, we use a O(1) form of the O(n) comparison of `size() != 1`.
8480 if (&BB->front() != &BB->back())
8481 return false;
8482
8483 // The BB must have at least one predecessor.
8484 if (pred_empty(BB))
8485 return false;
8486
8487 return true;
8488 }
8489};
8490
8492 static unsigned getHashValue(const EqualBBWrapper *EBW) {
8493 BasicBlock *BB = EBW->BB;
8495 assert(BB->size() == 1 && "Expected just a single branch in the BB");
8496
8497 // Since we assume the BB is just a single UncondBrInst with a single
8498 // successor, we hash as the BB and the incoming Values of its successor
8499 // PHIs. Initially, we tried to just use the successor BB as the hash, but
8500 // including the incoming PHI values leads to better performance.
8501 // We also tried to build a map from BB -> Succs.IncomingValues ahead of
8502 // time and passing it in EqualBBWrapper, but this slowed down the average
8503 // compile time without having any impact on the worst case compile time.
8504 BasicBlock *Succ = BI->getSuccessor();
8505 auto PhiValsForBB = map_range(Succ->phis(), [&](PHINode &Phi) {
8506 return (*EBW->PhiPredIVs)[&Phi][BB];
8507 });
8508 return hash_combine(Succ, hash_combine_range(PhiValsForBB));
8509 }
8510 static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS) {
8511 BasicBlock *A = LHS->BB;
8512 BasicBlock *B = RHS->BB;
8513
8514 // FIXME: we checked that the size of A and B are both 1 in
8515 // mergeIdenticalUncondBBs to make the Case list smaller to
8516 // improve performance. If we decide to support BasicBlocks with more
8517 // than just a single instruction, we need to check that A.size() ==
8518 // B.size() here, and we need to check more than just the BranchInsts
8519 // for equality.
8520
8521 UncondBrInst *ABI = cast<UncondBrInst>(A->getTerminator());
8522 UncondBrInst *BBI = cast<UncondBrInst>(B->getTerminator());
8523 if (ABI->getSuccessor() != BBI->getSuccessor())
8524 return false;
8525
8526 // Need to check that PHIs in successor have matching values.
8527 BasicBlock *Succ = ABI->getSuccessor();
8528 auto IfPhiIVMatch = [&](PHINode &Phi) {
8529 // Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
8530 // query.
8531 auto &PredIVs = (*LHS->PhiPredIVs)[&Phi];
8532 return PredIVs[A] == PredIVs[B];
8533 };
8534 return all_of(Succ->phis(), IfPhiIVMatch);
8535 }
8536};
8537
8538// Merge identical BBs into one of them.
8540 DomTreeUpdater *DTU) {
8541 if (Candidates.size() < 2)
8542 return false;
8543
8544 // Build Cases. Skip BBs that are not candidates for simplification. Mark
8545 // PHINodes which need to be processed into PhiPredIVs. We decide to process
8546 // an entire PHI at once after the loop, opposed to calling
8547 // getIncomingValueForBlock inside this loop, since each call to
8548 // getIncomingValueForBlock is O(|Preds|).
8549 EqualBBWrapper::Phi2IVsMap PhiPredIVs;
8551 BBs2Merge.reserve(Candidates.size());
8553
8554 for (BasicBlock *BB : Candidates) {
8555 BasicBlock *Succ = BB->getSingleSuccessor();
8556 assert(Succ && "Expected unconditional BB");
8557 BBs2Merge.emplace_back(EqualBBWrapper{BB, &PhiPredIVs});
8558 Phis.insert_range(make_pointer_range(Succ->phis()));
8559 }
8560
8561 // Precompute a data structure to improve performance of isEqual for
8562 // EqualBBWrapper.
8563 PhiPredIVs.reserve(Phis.size());
8564 for (PHINode *Phi : Phis) {
8565 auto &IVs =
8566 PhiPredIVs.try_emplace(Phi, Phi->getNumIncomingValues()).first->second;
8567 // Pre-fill all incoming for O(1) lookup as Phi.getIncomingValueForBlock is
8568 // O(|Pred|).
8569 for (auto &IV : Phi->incoming_values())
8570 IVs.insert({Phi->getIncomingBlock(IV), IV.get()});
8571 }
8572
8573 // Group duplicates using DenseSet with custom equality/hashing.
8574 // Build a set such that if the EqualBBWrapper exists in the set and another
8575 // EqualBBWrapper isEqual, then the equivalent EqualBBWrapper which is not in
8576 // the set should be replaced with the one in the set. If the EqualBBWrapper
8577 // is not in the set, then it should be added to the set so other
8578 // EqualBBWrapper can check against it in the same manner. We use
8579 // EqualBBWrapper instead of just BasicBlock because we'd like to pass around
8580 // information to isEquality, getHashValue, and when doing the replacement
8581 // with better performance.
8583 Keep.reserve(BBs2Merge.size());
8584
8586 Updates.reserve(BBs2Merge.size() * 2);
8587
8588 bool MadeChange = false;
8589
8590 // Helper: redirect all edges X -> DeadPred to X -> LivePred.
8591 auto RedirectIncomingEdges = [&](BasicBlock *Dead, BasicBlock *Live) {
8594 if (DTU) {
8595 // All predecessors of DeadPred (except the common predecessor) will be
8596 // moved to LivePred.
8597 Updates.reserve(Updates.size() + DeadPreds.size() * 2);
8599 predecessors(Live));
8600 for (BasicBlock *PredOfDead : DeadPreds) {
8601 // Do not modify those common predecessors of DeadPred and LivePred.
8602 if (!LivePreds.contains(PredOfDead))
8603 Updates.push_back({DominatorTree::Insert, PredOfDead, Live});
8604 Updates.push_back({DominatorTree::Delete, PredOfDead, Dead});
8605 }
8606 }
8607 LLVM_DEBUG(dbgs() << "Replacing duplicate pred BB ";
8608 Dead->printAsOperand(dbgs()); dbgs() << " with pred ";
8609 Live->printAsOperand(dbgs()); dbgs() << " for ";
8610 Live->getSingleSuccessor()->printAsOperand(dbgs());
8611 dbgs() << "\n");
8612 // Replace successors in all predecessors of DeadPred.
8613 for (BasicBlock *PredOfDead : DeadPreds) {
8614 Instruction *T = PredOfDead->getTerminator();
8615 T->replaceSuccessorWith(Dead, Live);
8616 }
8617 };
8618
8619 // Try to eliminate duplicate predecessors.
8620 for (const auto &EBW : BBs2Merge) {
8621 // EBW is a candidate for simplification. If we find a duplicate BB,
8622 // replace it.
8623 const auto &[It, Inserted] = Keep.insert(&EBW);
8624 if (Inserted)
8625 continue;
8626
8627 // Found duplicate: merge P into canonical predecessor It->Pred.
8628 BasicBlock *KeepBB = (*It)->BB;
8629 BasicBlock *DeadBB = EBW.BB;
8630
8631 // Avoid merging a BB with itself.
8632 if (KeepBB == DeadBB)
8633 continue;
8634
8635 // Redirect all edges into DeadPred to KeepPred.
8636 RedirectIncomingEdges(DeadBB, KeepBB);
8637
8638 // Now DeadBB should become unreachable; leave DCE to later,
8639 // but we can try to simplify it if it only branches to Succ.
8640 // (We won't erase here to keep the routine simple and DT-safe.)
8641 assert(pred_empty(DeadBB) && "DeadBB should be unreachable.");
8642 MadeChange = true;
8643 }
8644
8645 if (DTU && !Updates.empty())
8646 DTU->applyUpdates(Updates);
8647
8648 return MadeChange;
8649}
8650
8651bool SimplifyCFGOpt::simplifyDuplicateSwitchArms(SwitchInst *SI,
8652 DomTreeUpdater *DTU) {
8653 // Collect candidate switch-arms top-down.
8654 SmallSetVector<BasicBlock *, 16> FilteredArms(
8657 return mergeIdenticalBBs(FilteredArms.getArrayRef(), DTU);
8658}
8659
8660bool SimplifyCFGOpt::simplifyDuplicatePredecessors(BasicBlock *BB,
8661 DomTreeUpdater *DTU) {
8662 // Need at least 2 predecessors to do anything.
8663 if (!BB || !BB->hasNPredecessorsOrMore(2))
8664 return false;
8665
8666 // Compilation time consideration: retain the canonical loop, otherwise, we
8667 // require more time in the later loop canonicalization.
8668 if (Options.NeedCanonicalLoop && is_contained(LoopHeaders, BB))
8669 return false;
8670
8671 // Collect candidate predecessors bottom-up.
8672 SmallSetVector<BasicBlock *, 8> FilteredPreds(
8675 return mergeIdenticalBBs(FilteredPreds.getArrayRef(), DTU);
8676}
8677
8678bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
8679 BasicBlock *BB = SI->getParent();
8680
8681 if (isValueEqualityComparison(SI)) {
8682 // If we only have one predecessor, and the predecessor branches on the
8683 // same value as this switch, try to simplify the switch based on the
8684 // conditions under which the predecessor jumps to this block.
8685 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8686 if (simplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
8687 return requestResimplify();
8688
8689 Value *Cond = SI->getCondition();
8690 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
8691 if (simplifySwitchOnSelect(SI, Select))
8692 return requestResimplify();
8693
8694 // If the block only contains the switch, see if we can fold the block
8695 // away into any preds.
8696 if (SI == &*BB->begin())
8697 if (foldValueComparisonIntoPredecessors(SI, Builder))
8698 return requestResimplify();
8699 }
8700
8701 // Try to transform the switch into an icmp and a branch.
8702 // The conversion from switch to comparison may lose information on
8703 // impossible switch values, so disable it early in the pipeline.
8704 if (Options.ConvertSwitchRangeToICmp && turnSwitchRangeIntoICmp(SI, Builder))
8705 return requestResimplify();
8706
8707 // Remove unreachable cases.
8708 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
8709 return requestResimplify();
8710
8711 if (simplifySwitchOfCmpIntrinsic(SI, Builder, DTU))
8712 return requestResimplify();
8713
8714 if (trySwitchToSelect(SI, Builder, DTU, DL))
8715 return requestResimplify();
8716
8717 if (Options.ForwardSwitchCondToPhi && forwardSwitchConditionToPHI(SI))
8718 return requestResimplify();
8719
8720 // The conversion of switches to arithmetic or lookup table is disabled in
8721 // the early optimization pipeline, as it may lose information or make the
8722 // resulting code harder to analyze.
8723 if (Options.ConvertSwitchToArithmetic || Options.ConvertSwitchToLookupTable)
8724 if (simplifySwitchLookup(SI, Builder, DTU, DL, TTI,
8725 Options.ConvertSwitchToLookupTable))
8726 return requestResimplify();
8727
8728 if (simplifySwitchOfPowersOfTwo(SI, Builder, DTU, DL, TTI))
8729 return requestResimplify();
8730
8731 if (reduceSwitchRange(SI, Builder, DL, TTI))
8732 return requestResimplify();
8733
8734 if (HoistCommon &&
8735 hoistCommonCodeFromSuccessors(SI, !Options.HoistCommonInsts))
8736 return requestResimplify();
8737
8738 // We can merge identical switch arms early to enhance more aggressive
8739 // optimization on switch.
8740 if (simplifyDuplicateSwitchArms(SI, DTU))
8741 return requestResimplify();
8742
8743 if (simplifySwitchWhenUMin(SI, DTU))
8744 return requestResimplify();
8745
8746 if (simplifySwitchDefaultBranch(SI, DTU, DL, Options.AC))
8747 return requestResimplify();
8748
8749 return false;
8750}
8751
8752bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
8753 BasicBlock *BB = IBI->getParent();
8754 bool Changed = false;
8755 SmallVector<uint32_t> BranchWeights;
8756 const bool HasBranchWeights = extractBranchWeights(*IBI, BranchWeights);
8757
8758 DenseMap<const BasicBlock *, uint64_t> TargetWeight;
8759 if (HasBranchWeights)
8760 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8761 TargetWeight[IBI->getDestination(I)] += BranchWeights[I];
8762
8763 // Eliminate redundant destinations.
8764 SmallPtrSet<Value *, 8> Succs;
8765 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
8766 for (unsigned I = 0, E = IBI->getNumDestinations(); I != E; ++I) {
8767 BasicBlock *Dest = IBI->getDestination(I);
8768 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
8769 if (!Dest->hasAddressTaken())
8770 RemovedSuccs.insert(Dest);
8771 Dest->removePredecessor(BB);
8772 IBI->removeDestination(I);
8773 --I;
8774 --E;
8775 Changed = true;
8776 }
8777 }
8778
8779 if (DTU) {
8780 std::vector<DominatorTree::UpdateType> Updates;
8781 Updates.reserve(RemovedSuccs.size());
8782 for (auto *RemovedSucc : RemovedSuccs)
8783 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
8784 DTU->applyUpdates(Updates);
8785 }
8786
8787 if (IBI->getNumDestinations() == 0) {
8788 // If the indirectbr has no successors, change it to unreachable.
8789 new UnreachableInst(IBI->getContext(), IBI->getIterator());
8791 return true;
8792 }
8793
8794 if (IBI->getNumDestinations() == 1) {
8795 // If the indirectbr has one successor, change it to a direct branch.
8798 return true;
8799 }
8800 if (HasBranchWeights) {
8801 SmallVector<uint64_t> NewBranchWeights(IBI->getNumDestinations());
8802 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8803 NewBranchWeights[I] += TargetWeight.find(IBI->getDestination(I))->second;
8804 setFittedBranchWeights(*IBI, NewBranchWeights, /*IsExpected=*/false);
8805 }
8806 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
8807 if (simplifyIndirectBrOnSelect(IBI, SI))
8808 return requestResimplify();
8809 }
8810 return Changed;
8811}
8812
8813/// Given an block with only a single landing pad and a unconditional branch
8814/// try to find another basic block which this one can be merged with. This
8815/// handles cases where we have multiple invokes with unique landing pads, but
8816/// a shared handler.
8817///
8818/// We specifically choose to not worry about merging non-empty blocks
8819/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
8820/// practice, the optimizer produces empty landing pad blocks quite frequently
8821/// when dealing with exception dense code. (see: instcombine, gvn, if-else
8822/// sinking in this file)
8823///
8824/// This is primarily a code size optimization. We need to avoid performing
8825/// any transform which might inhibit optimization (such as our ability to
8826/// specialize a particular handler via tail commoning). We do this by not
8827/// merging any blocks which require us to introduce a phi. Since the same
8828/// values are flowing through both blocks, we don't lose any ability to
8829/// specialize. If anything, we make such specialization more likely.
8830///
8831/// Phis in the successor are allowed if both blocks pass the same value, or
8832/// each passes its own landing pad value and that is its only use: the merged
8833/// block's landing pad then carries the value for both edges.
8835 BasicBlock *BB, DomTreeUpdater *DTU) {
8836 auto Succ = BB->getUniqueSuccessor();
8837 assert(Succ);
8838
8839 for (BasicBlock *OtherPred : predecessors(Succ)) {
8840 if (BB == OtherPred)
8841 continue;
8842 BasicBlock::iterator I = OtherPred->begin();
8844 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
8845 continue;
8846 ++I;
8848 if (!BI2 || !BI2->isIdenticalTo(BI))
8849 continue;
8850
8851 // Merging must not require a new phi in the merged landing pad block.
8852 if (!all_of(Succ->phis(), [&](PHINode &PN) {
8853 Value *V = PN.getIncomingValueForBlock(BB);
8854 Value *V2 = PN.getIncomingValueForBlock(OtherPred);
8855 return V == V2 || (V == LPad && V2 == LPad2);
8856 }))
8857 continue;
8858
8859 // Those phis must be the only uses of the landing pads. Otherwise, with a
8860 // loop through Succ, a use would be clobbered when the merged pad is
8861 // re-entered.
8862 unsigned NumLPadPhis = count_if(Succ->phis(), [&](PHINode &PN) {
8863 return PN.getIncomingValueForBlock(BB) == LPad;
8864 });
8865 if (!LPad->hasNUses(NumLPadPhis) || !LPad2->hasNUses(NumLPadPhis))
8866 continue;
8867
8868 std::vector<DominatorTree::UpdateType> Updates;
8869
8870 // We've found an identical block. Update our predecessors to take that
8871 // path instead and make ourselves dead.
8873 for (BasicBlock *Pred : UniquePreds) {
8874 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
8875 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
8876 "unexpected successor");
8877 II->setUnwindDest(OtherPred);
8878 if (DTU) {
8879 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
8880 Updates.push_back({DominatorTree::Delete, Pred, BB});
8881 }
8882 }
8883
8885 for (BasicBlock *Succ : UniqueSuccs) {
8886 Succ->removePredecessor(BB);
8887 if (DTU)
8888 Updates.push_back({DominatorTree::Delete, BB, Succ});
8889 }
8890
8891 IRBuilder<> Builder(BI);
8892 Builder.CreateUnreachable();
8893 BI->eraseFromParent();
8894 if (DTU)
8895 DTU->applyUpdates(Updates);
8896 return true;
8897 }
8898 return false;
8899}
8900
8901bool SimplifyCFGOpt::simplifyUncondBranch(UncondBrInst *BI,
8902 IRBuilder<> &Builder) {
8903 BasicBlock *BB = BI->getParent();
8904 BasicBlock *Succ = BI->getSuccessor(0);
8905
8906 // If the Terminator is the only non-phi instruction, simplify the block.
8907 // If LoopHeader is provided, check if the block or its successor is a loop
8908 // header. (This is for early invocations before loop simplify and
8909 // vectorization to keep canonical loop forms for nested loops. These blocks
8910 // can be eliminated when the pass is invoked later in the back-end.)
8911 // Note that if BB has only one predecessor then we do not introduce new
8912 // backedge, so we can eliminate BB.
8913 bool NeedCanonicalLoop =
8914 Options.NeedCanonicalLoop &&
8915 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
8916 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
8918 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
8919 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
8920 return true;
8921
8922 // If the only instruction in the block is a seteq/setne comparison against a
8923 // constant, try to simplify the block.
8924 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
8925 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
8926 ++I;
8927 if (I->isTerminator() &&
8928 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
8929 return true;
8930 if (isa<SelectInst>(I) && I->getNextNode()->isTerminator() &&
8931 tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, cast<SelectInst>(I),
8932 Builder))
8933 return true;
8934 }
8935 }
8936
8937 // See if we can merge an empty landing pad block with another which is
8938 // equivalent.
8939 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
8940 ++I;
8941 if (I->isTerminator() && tryToMergeLandingPad(LPad, BI, BB, DTU))
8942 return true;
8943 }
8944
8945 return false;
8946}
8947
8949 BasicBlock *PredPred = nullptr;
8950 for (auto *P : predecessors(BB)) {
8951 BasicBlock *PPred = P->getSinglePredecessor();
8952 if (!PPred || (PredPred && PredPred != PPred))
8953 return nullptr;
8954 PredPred = PPred;
8955 }
8956 return PredPred;
8957}
8958
8959/// Fold the following pattern:
8960/// bb0:
8961/// br i1 %cond1, label %bb1, label %bb2
8962/// bb1:
8963/// br i1 %cond2, label %bb3, label %bb4
8964/// bb2:
8965/// br i1 %cond2, label %bb4, label %bb3
8966/// bb3:
8967/// ...
8968/// bb4:
8969/// ...
8970/// into
8971/// bb0:
8972/// %cond = xor i1 %cond1, %cond2
8973/// br i1 %cond, label %bb4, label %bb3
8974/// bb3:
8975/// ...
8976/// bb4:
8977/// ...
8978/// NOTE: %cond2 always dominates the terminator of bb0.
8980 BasicBlock *BB = BI->getParent();
8981 BasicBlock *BB1 = BI->getSuccessor(0);
8982 BasicBlock *BB2 = BI->getSuccessor(1);
8983 auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
8984 if (Succ == BB)
8985 return false;
8986 if (&Succ->front() != Succ->getTerminator())
8987 return false;
8988 SuccBI = dyn_cast<CondBrInst>(Succ->getTerminator());
8989 if (!SuccBI)
8990 return false;
8991 BasicBlock *Succ1 = SuccBI->getSuccessor(0);
8992 BasicBlock *Succ2 = SuccBI->getSuccessor(1);
8993 return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
8994 !isa<PHINode>(Succ1->front()) && !isa<PHINode>(Succ2->front());
8995 };
8996 CondBrInst *BB1BI, *BB2BI;
8997 if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
8998 return false;
8999
9000 if (BB1BI->getCondition() != BB2BI->getCondition() ||
9001 BB1BI->getSuccessor(0) != BB2BI->getSuccessor(1) ||
9002 BB1BI->getSuccessor(1) != BB2BI->getSuccessor(0))
9003 return false;
9004
9005 BasicBlock *BB3 = BB1BI->getSuccessor(0);
9006 BasicBlock *BB4 = BB1BI->getSuccessor(1);
9007 // Bail out on trivial cases to avoid bothering to handle the special case in
9008 // the code below.
9009 if (BB3 == BB4)
9010 return false;
9011 IRBuilder<> Builder(BI);
9012 BI->setCondition(
9013 Builder.CreateXor(BI->getCondition(), BB1BI->getCondition()));
9014 BB1->removePredecessor(BB);
9015 BI->setSuccessor(0, BB4);
9016 BB2->removePredecessor(BB);
9017 BI->setSuccessor(1, BB3);
9018 if (DTU) {
9020 Updates.push_back({DominatorTree::Delete, BB, BB1});
9021 Updates.push_back({DominatorTree::Insert, BB, BB4});
9022 Updates.push_back({DominatorTree::Delete, BB, BB2});
9023 Updates.push_back({DominatorTree::Insert, BB, BB3});
9024
9025 DTU->applyUpdates(Updates);
9026 }
9027 bool HasWeight = false;
9028 uint64_t BBTWeight, BBFWeight;
9029 if (extractBranchWeights(*BI, BBTWeight, BBFWeight))
9030 HasWeight = true;
9031 else
9032 BBTWeight = BBFWeight = 1;
9033 uint64_t BB1TWeight, BB1FWeight;
9034 if (extractBranchWeights(*BB1BI, BB1TWeight, BB1FWeight))
9035 HasWeight = true;
9036 else
9037 BB1TWeight = BB1FWeight = 1;
9038 uint64_t BB2TWeight, BB2FWeight;
9039 if (extractBranchWeights(*BB2BI, BB2TWeight, BB2FWeight))
9040 HasWeight = true;
9041 else
9042 BB2TWeight = BB2FWeight = 1;
9043 if (HasWeight) {
9044 uint64_t Weights[2] = {BBTWeight * BB1FWeight + BBFWeight * BB2TWeight,
9045 BBTWeight * BB1TWeight + BBFWeight * BB2FWeight};
9046 setFittedBranchWeights(*BI, Weights, /*IsExpected=*/false,
9047 /*ElideAllZero=*/true);
9048 }
9049 return true;
9050}
9051
9052bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
9053 assert(
9055 BI->getSuccessor(0) != BI->getSuccessor(1) &&
9056 "Tautological conditional branch should have been eliminated already.");
9057
9058 BasicBlock *BB = BI->getParent();
9059 if (!Options.SimplifyCondBranch ||
9060 BI->getFunction()->hasFnAttribute(Attribute::OptForFuzzing))
9061 return false;
9062
9063 // Conditional branch
9064 if (isValueEqualityComparison(BI)) {
9065 // If we only have one predecessor, and the predecessor branches on the
9066 // same value as this branch, try to simplify the branch based on the
9067 // conditions under which the predecessor jumps to this block.
9068 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
9069 if (simplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
9070 return requestResimplify();
9071
9072 // This block must be empty, except for the setcond inst, if it exists.
9073 // Ignore pseudo intrinsics.
9074 for (auto &I : *BB) {
9075 if (isa<PseudoProbeInst>(I) ||
9076 &I == cast<Instruction>(BI->getCondition()))
9077 continue;
9078 if (&I == BI)
9079 if (foldValueComparisonIntoPredecessors(BI, Builder))
9080 return requestResimplify();
9081 break;
9082 }
9083 }
9084
9085 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
9086 if (simplifyBranchOnICmpChain(BI, Builder, DL))
9087 return true;
9088
9089 // If this basic block has dominating predecessor blocks and the dominating
9090 // blocks' conditions imply BI's condition, we know the direction of BI.
9091 std::optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
9092 if (Imp) {
9093 // Turn this into a branch on constant.
9094 auto *OldCond = BI->getCondition();
9095 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
9096 : ConstantInt::getFalse(BB->getContext());
9097 BI->setCondition(TorF);
9099 return requestResimplify();
9100 }
9101
9102 // If this basic block is ONLY a compare and a branch, and if a predecessor
9103 // branches to us and one of our successors, fold the comparison into the
9104 // predecessor and use logical operations to pick the right destination.
9105 if (Options.SpeculateBlocks &&
9106 foldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, Options.AC,
9107 Options.BonusInstThreshold))
9108 return requestResimplify();
9109
9110 // We have a conditional branch to two blocks that are only reachable
9111 // from BI. We know that the condbr dominates the two blocks, so see if
9112 // there is any identical code in the "then" and "else" blocks. If so, we
9113 // can hoist it up to the branching block.
9114 if (BI->getSuccessor(0)->getSinglePredecessor()) {
9115 if (BI->getSuccessor(1)->getSinglePredecessor()) {
9116 if (HoistCommon &&
9117 hoistCommonCodeFromSuccessors(BI, !Options.HoistCommonInsts))
9118 return requestResimplify();
9119
9120 if (BI && Options.HoistLoadsStoresWithCondFaulting &&
9121 isProfitableToSpeculate(BI, std::nullopt, TTI)) {
9122 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
9123 auto CanSpeculateConditionalLoadsStores = [&]() {
9124 for (auto *Succ : successors(BB)) {
9125 for (Instruction &I : *Succ) {
9126 if (I.isTerminator()) {
9127 if (I.getNumSuccessors() > 1)
9128 return false;
9129 continue;
9130 } else if (!isSafeCheapLoadStore(&I, TTI) ||
9131 SpeculatedConditionalLoadsStores.size() ==
9133 return false;
9134 }
9135 SpeculatedConditionalLoadsStores.push_back(&I);
9136 }
9137 }
9138 return !SpeculatedConditionalLoadsStores.empty();
9139 };
9140
9141 if (CanSpeculateConditionalLoadsStores()) {
9142 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores,
9143 std::nullopt, nullptr);
9144 return requestResimplify();
9145 }
9146 }
9147 } else {
9148 // If Successor #1 has multiple preds, we may be able to conditionally
9149 // execute Successor #0 if it branches to Successor #1.
9150 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
9151 if (Succ0TI->getNumSuccessors() == 1 &&
9152 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
9153 if (speculativelyExecuteBB(BI, BI->getSuccessor(0)))
9154 return requestResimplify();
9155 }
9156 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
9157 // If Successor #0 has multiple preds, we may be able to conditionally
9158 // execute Successor #1 if it branches to Successor #0.
9159 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
9160 if (Succ1TI->getNumSuccessors() == 1 &&
9161 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
9162 if (speculativelyExecuteBB(BI, BI->getSuccessor(1)))
9163 return requestResimplify();
9164 }
9165
9166 // If this is a branch on something for which we know the constant value in
9167 // predecessors (e.g. a phi node in the current block), thread control
9168 // through this block.
9169 if (foldCondBranchOnValueKnownInPredecessor(BI))
9170 return requestResimplify();
9171
9172 // Scan predecessor blocks for conditional branches.
9173 for (BasicBlock *Pred : predecessors(BB))
9174 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator()))
9175 if (PBI != BI)
9176 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
9177 return requestResimplify();
9178
9179 // Look for diamond patterns.
9180 if (MergeCondStores)
9181 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
9182 if (CondBrInst *PBI = dyn_cast<CondBrInst>(PrevBB->getTerminator()))
9183 if (PBI != BI)
9184 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
9185 return requestResimplify();
9186
9187 // Look for nested conditional branches.
9188 if (mergeNestedCondBranch(BI, DTU))
9189 return requestResimplify();
9190
9191 return false;
9192}
9193
9194/// Check if passing a value to an instruction will cause undefined behavior.
9195static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
9196 assert(V->getType() == I->getType() && "Mismatched types");
9198 if (!C)
9199 return false;
9200
9201 if (I->use_empty())
9202 return false;
9203
9204 if (C->isNullValue() || isa<UndefValue>(C)) {
9205 // Find the first same-block use with a UB-triggering opcode, skipping
9206 // cross-block or before-I uses.
9207 auto FindUse = llvm::find_if(I->uses(), [I](auto &U) {
9208 auto *Use = cast<Instruction>(U.getUser());
9209 // Only same-block uses after I can witness UB at I's program point.
9210 // Self-uses and before-I uses can occur when I is a PHI node.
9211 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
9212 return false;
9213 // Change this list when we want to add new instructions.
9214 switch (Use->getOpcode()) {
9215 default:
9216 return false;
9217 case Instruction::GetElementPtr:
9218 case Instruction::Ret:
9219 case Instruction::BitCast:
9220 case Instruction::Load:
9221 case Instruction::Store:
9222 case Instruction::Call:
9223 case Instruction::CallBr:
9224 case Instruction::Invoke:
9225 case Instruction::UDiv:
9226 case Instruction::URem:
9227 // Note: signed div/rem of INT_MIN / -1 is also immediate UB, not
9228 // implemented to avoid code complexity as it is unclear how useful such
9229 // logic is.
9230 case Instruction::SDiv:
9231 case Instruction::SRem:
9232 return true;
9233 }
9234 });
9235 if (FindUse == I->use_end())
9236 return false;
9237 auto &Use = *FindUse;
9238 auto *User = cast<Instruction>(Use.getUser());
9239
9240 // Now make sure that there are no instructions in between that can alter
9241 // control flow (eg. calls)
9242 auto InstrRange =
9243 make_range(std::next(I->getIterator()), User->getIterator());
9244 if (any_of(InstrRange, [](Instruction &I) {
9246 }))
9247 return false;
9248
9249 // Look through GEPs. A load from a GEP derived from NULL is still undefined
9251 if (GEP->getPointerOperand() == I) {
9252 // The type of GEP may differ from the type of base pointer.
9253 // Bail out on vector GEPs, as they are not handled by other checks.
9254 if (GEP->getType()->isVectorTy())
9255 return false;
9256 // The current base address is null, there are four cases to consider:
9257 // getelementptr (TY, null, 0) -> null
9258 // getelementptr (TY, null, not zero) -> may be modified
9259 // getelementptr inbounds (TY, null, 0) -> null
9260 // getelementptr inbounds (TY, null, not zero) -> poison iff null is
9261 // undefined?
9262 if (!GEP->hasAllZeroIndices() &&
9263 (!GEP->isInBounds() ||
9264 NullPointerIsDefined(GEP->getFunction(),
9265 GEP->getPointerAddressSpace())))
9266 PtrValueMayBeModified = true;
9267 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
9268 }
9269
9270 // Look through return.
9271 if (ReturnInst *Ret = dyn_cast<ReturnInst>(User)) {
9272 bool HasNoUndefAttr =
9273 Ret->getFunction()->hasRetAttribute(Attribute::NoUndef);
9274 // Return undefined to a noundef return value is undefined.
9275 if (isa<UndefValue>(C) && HasNoUndefAttr)
9276 return true;
9277 // Return null to a nonnull+noundef return value is undefined.
9278 if (C->isNullValue() && HasNoUndefAttr &&
9279 Ret->getFunction()->hasRetAttribute(Attribute::NonNull)) {
9280 return !PtrValueMayBeModified;
9281 }
9282 }
9283
9284 // Load from null is undefined.
9285 if (LoadInst *LI = dyn_cast<LoadInst>(User))
9286 if (!LI->isVolatile())
9287 return !NullPointerIsDefined(LI->getFunction(),
9288 LI->getPointerAddressSpace());
9289
9290 // Store to null is undefined.
9292 if (!SI->isVolatile())
9293 return (!NullPointerIsDefined(SI->getFunction(),
9294 SI->getPointerAddressSpace())) &&
9295 SI->getPointerOperand() == I;
9296
9297 // llvm.assume(false/undef) always triggers immediate UB.
9298 if (auto *Assume = dyn_cast<AssumeInst>(User)) {
9299 // Ignore assume operand bundles.
9300 if (I == Assume->getArgOperand(0))
9301 return true;
9302 }
9303
9304 if (auto *CB = dyn_cast<CallBase>(User)) {
9305 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
9306 return false;
9307 // A call to null is undefined.
9308 if (CB->getCalledOperand() == I)
9309 return true;
9310
9311 if (CB->isArgOperand(&Use)) {
9312 unsigned ArgIdx = CB->getArgOperandNo(&Use);
9313 // Passing null to a nonnnull+noundef argument is undefined.
9314 if (isa<ConstantPointerNull>(C) && C->getType()->isPointerTy() &&
9315 CB->paramHasNonNullAttr(ArgIdx, /*AllowUndefOrPoison=*/false))
9316 return !PtrValueMayBeModified;
9317 // Passing undef to a noundef argument is undefined.
9318 if (isa<UndefValue>(C) && CB->isPassingUndefUB(ArgIdx))
9319 return true;
9320 }
9321 }
9322 // Div/Rem by zero is immediate UB
9323 if (match(User, m_BinOp(m_Value(), m_Specific(I))) && User->isIntDivRem())
9324 return true;
9325 }
9326 return false;
9327}
9328
9329/// If BB has an incoming value that will always trigger undefined behavior
9330/// (eg. null pointer dereference), remove the branch leading here.
9332 DomTreeUpdater *DTU,
9333 AssumptionCache *AC) {
9334 for (PHINode &PHI : BB->phis())
9335 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
9336 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
9337 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
9338 Instruction *T = Predecessor->getTerminator();
9339 IRBuilder<> Builder(T);
9340 if (isa<UncondBrInst>(T)) {
9341 BB->removePredecessor(Predecessor);
9342 // Turn unconditional branches into unreachables.
9343 Builder.CreateUnreachable();
9344 T->eraseFromParent();
9345 if (DTU)
9346 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9347 return true;
9348 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(T)) {
9349 BB->removePredecessor(Predecessor);
9350 // Handle degenerate conditional branches.
9351 if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
9352 // The only difference from the UncondBrInst path above is that it
9353 // has two edges in CFG.
9354 BB->removePredecessor(Predecessor);
9355 // Turn unconditional branches into unreachables.
9356 Builder.CreateUnreachable();
9357 } else {
9358 // Preserve guarding condition in assume, because it might not be
9359 // inferrable from any dominating condition.
9360 Value *Cond = BI->getCondition();
9361 CallInst *Assumption;
9362 if (BI->getSuccessor(0) == BB)
9363 Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
9364 else
9365 Assumption = Builder.CreateAssumption(Cond);
9366 if (AC)
9367 AC->registerAssumption(cast<AssumeInst>(Assumption));
9368 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
9369 : BI->getSuccessor(0));
9370 }
9371 BI->eraseFromParent();
9372 if (DTU)
9373 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
9374 return true;
9375 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
9376 // Redirect all branches leading to UB into
9377 // a newly created unreachable block.
9378 BasicBlock *Unreachable = BasicBlock::Create(
9379 Predecessor->getContext(), "unreachable", BB->getParent(), BB);
9380 Builder.SetInsertPoint(Unreachable);
9381 // The new block contains only one instruction: Unreachable
9382 Builder.CreateUnreachable();
9383 for (const auto &Case : SI->cases())
9384 if (Case.getCaseSuccessor() == BB) {
9385 BB->removePredecessor(Predecessor);
9386 Case.setSuccessor(Unreachable);
9387 }
9388 if (SI->getDefaultDest() == BB) {
9389 BB->removePredecessor(Predecessor);
9390 SI->setDefaultDest(Unreachable);
9391 }
9392
9393 if (DTU)
9394 DTU->applyUpdates(
9395 { { DominatorTree::Insert, Predecessor, Unreachable },
9396 { DominatorTree::Delete, Predecessor, BB } });
9397 return true;
9398 }
9399 }
9400
9401 return false;
9402}
9403
9404bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
9405 bool Changed = false;
9406
9407 assert(BB && BB->getParent() && "Block not embedded in function!");
9408 assert(BB->hasTerminator() && "Degenerate basic block encountered!");
9409
9410 // Remove basic blocks that have no predecessors (except the entry block)...
9411 // or that just have themself as a predecessor. These are unreachable.
9412 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
9413 BB->getSinglePredecessor() == BB) {
9414 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
9415 DeleteDeadBlock(BB, DTU);
9416 return true;
9417 }
9418
9419 // Check to see if we can constant propagate this terminator instruction
9420 // away...
9421 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
9422 /*TLI=*/nullptr, DTU);
9423
9424 // Check for and eliminate duplicate PHI nodes in this block.
9426
9427 // Check for and remove branches that will always cause undefined behavior.
9429 return requestResimplify();
9430
9431 // Merge basic blocks into their predecessor if there is only one distinct
9432 // pred, and if there is only one distinct successor of the predecessor, and
9433 // if there are no PHI nodes.
9434 if (MergeBlockIntoPredecessor(BB, DTU))
9435 return true;
9436
9437 if (SinkCommon && Options.SinkCommonInsts) {
9438 if (sinkCommonCodeFromPredecessors(BB, DTU) ||
9439 mergeCompatibleInvokes(BB, DTU)) {
9440 // sinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
9441 // so we may now have duplicate PHI's.
9442 // Let's rerun EliminateDuplicatePHINodes() first,
9443 // before foldTwoEntryPHINode() potentially converts them into select's,
9444 // after which we'd need a whole EarlyCSE pass run to cleanup them.
9445 return true;
9446 }
9447 // Merge identical predecessors of this block.
9448 if (simplifyDuplicatePredecessors(BB, DTU))
9449 return true;
9450 }
9451
9452 if (Options.SpeculateBlocks &&
9453 !BB->getParent()->hasFnAttribute(Attribute::OptForFuzzing)) {
9454 // If there is a trivial two-entry PHI node in this basic block, and we can
9455 // eliminate it, do so now.
9456 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
9457 if (PN->getNumIncomingValues() == 2)
9458 if (foldTwoEntryPHINode(PN, TTI, DTU, Options.AC, DL,
9459 Options.SpeculateUnpredictables))
9460 return true;
9461 }
9462
9463 IRBuilder<> Builder(BB);
9465 Builder.SetInsertPoint(Terminator);
9466 switch (Terminator->getOpcode()) {
9467 case Instruction::UncondBr:
9468 Changed |= simplifyUncondBranch(cast<UncondBrInst>(Terminator), Builder);
9469 break;
9470 case Instruction::CondBr:
9471 Changed |= simplifyCondBranch(cast<CondBrInst>(Terminator), Builder);
9472 break;
9473 case Instruction::Resume:
9474 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
9475 break;
9476 case Instruction::CleanupRet:
9477 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
9478 break;
9479 case Instruction::Switch:
9480 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
9481 break;
9482 case Instruction::Unreachable:
9483 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
9484 break;
9485 case Instruction::IndirectBr:
9486 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
9487 break;
9488 }
9489
9490 return Changed;
9491}
9492
9493bool SimplifyCFGOpt::run(BasicBlock *BB) {
9494 bool Changed = false;
9495
9496 // Repeated simplify BB as long as resimplification is requested.
9497 do {
9498 Resimplify = false;
9499
9500 // Perform one round of simplifcation. Resimplify flag will be set if
9501 // another iteration is requested.
9502 Changed |= simplifyOnce(BB);
9503 } while (Resimplify);
9504
9505 return Changed;
9506}
9507
9510 ArrayRef<WeakVH> LoopHeaders) {
9511 return SimplifyCFGOpt(TTI, DTU, BB->getDataLayout(), LoopHeaders,
9512 Options)
9513 .run(BB);
9514}
#define Fail
#define Success
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
static MachineBasicBlock * OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
@ Default
#define DEBUG_TYPE
Hexagon Common GEP
static bool IsIndirectCall(const MachineInstr *MI)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
This file contains the declarations for profiling metadata utility functions.
static cl::opt< uint32_t > SelectFalseWeight("profcheck-default-select-false-weight", cl::init(3U), cl::desc("When annotating `select` instructions, this value will be used " "for the second ('false') case."))
static cl::opt< uint32_t > SelectTrueWeight("profcheck-default-select-true-weight", cl::init(2U), cl::desc("When annotating `select` instructions, this value will be used " "for the first ('true') case."))
SmallVector< MachineOperand, 4 > Cond
int64_t C1
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
Provides some synthesis utilities to produce sequences of values.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
static std::optional< ContiguousCasesResult > findContiguousCases(Value *Condition, SmallVectorImpl< ConstantInt * > &Cases, SmallVectorImpl< ConstantInt * > &OtherCases, BasicBlock *Dest, BasicBlock *OtherDest)
static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, BasicBlock *ExistPred, MemorySSAUpdater *MSSAU=nullptr)
Update PHI nodes in Succ to indicate that there will now be entries in it from the 'NewPred' block.
static bool validLookupTableConstant(Constant *C, const TargetTransformInfo &TTI)
Return true if the backend will be able to handle initializing an array of constants like C.
static StoreInst * findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2)
static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize)
static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB, BasicBlock *EndBB, unsigned &SpeculatedInstructions, InstructionCost &Cost, const TargetTransformInfo &TTI)
Estimate the cost of the insertion(s) and check that the PHI nodes can be converted to selects.
static bool simplifySwitchLookup(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI, bool ConvertSwitchToLookupTable)
If the switch is only used to initialize one or more phi nodes in a common successor block with diffe...
static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI, Value *SelectValue, IRBuilder<> &Builder, DomTreeUpdater *DTU)
static bool valuesOverlap(std::vector< ValueEqualityComparisonCase > &C1, std::vector< ValueEqualityComparisonCase > &C2)
Return true if there are any keys in C1 that exist in C2 as well.
static bool isProfitableToSpeculate(const CondBrInst *BI, std::optional< bool > Invert, const TargetTransformInfo &TTI)
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeCleanupPad(CleanupReturnInst *RI)
static bool isVectorOp(Instruction &I)
Return if an instruction's type or any of its operands' types are a vector type.
static BasicBlock * allPredecessorsComeFromSameSource(BasicBlock *BB)
static void cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap)
static int constantIntSortPredicate(ConstantInt *const *P1, ConstantInt *const *P2)
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified=false)
Check if passing a value to an instruction will cause undefined behavior.
static std::optional< std::tuple< BasicBlock *, Instruction::BinaryOps, bool > > shouldFoldCondBranchesToCommonDestination(CondBrInst *BI, CondBrInst *PBI, const TargetTransformInfo *TTI)
Determine if the two branches share a common destination and deduce a glue that joins the branches' c...
static bool isSafeToHoistInstr(Instruction *I, unsigned Flags)
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
static ConstantInt * getConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
static bool simplifySwitchOfCmpIntrinsic(SwitchInst *SI, IRBuilderBase &Builder, DomTreeUpdater *DTU)
Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have the same destination.
static bool shouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, const TargetTransformInfo &TTI, const DataLayout &DL, const SmallVector< Type * > &ResultTypes)
Determine whether a lookup table should be built for this switch, based on the number of cases,...
static Constant * constantFold(Instruction *I, const DataLayout &DL, const SmallDenseMap< Value *, Constant * > &ConstantPool)
Try to fold instruction I into a constant.
static bool getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant * > > &Res, const DataLayout &DL)
Try to determine the resulting constant values in phi nodes at the common destination basic block,...
static bool areIdenticalUpToCommutativity(const Instruction *I1, const Instruction *I2)
static bool forwardSwitchConditionToPHI(SwitchInst *SI)
Try to forward the condition of a switch instruction to a phi node dominated by the switch,...
static PHINode * findPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
If BB would be eligible for simplification by TryToSimplifyUncondBranchFromEmptyBlock (i....
static bool reachesUncontrolledConvergentCallBeforeBlock(BasicBlock *From, BasicBlock *StopBB)
static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
Tries to transform switch of powers of two to reduce switch range.
static bool isCleanupBlockEmpty(iterator_range< BasicBlock::iterator > R)
static bool isSafeToThreadThroughLoopHeader(BasicBlock *Header, ArrayRef< BasicBlock * > PredBBs, BasicBlock *RealDest)
Return true if threading PredBBs through Header to RealDest eliminates the loop's single backedge.
static Value * ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, Value *AlternativeV=nullptr)
static Value * createLogicalOp(IRBuilderBase &Builder, Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="")
static void hoistConditionalLoadsStores(CondBrInst *BI, SmallVectorImpl< Instruction * > &SpeculatedConditionalLoadsStores, std::optional< bool > Invert, Instruction *Sel)
If the target supports conditional faulting, we look for the following pattern:
static bool shouldHoistCommonInstructions(Instruction *I1, Instruction *I2, const TargetTransformInfo &TTI)
Helper function for hoistCommonCodeFromSuccessors.
static bool reduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to transform a switch that has "holes" in it to a contiguous sequence of cases.
static bool safeToMergeTerminators(Instruction *SI1, Instruction *SI2, SmallSetVector< BasicBlock *, 4 > *FailBlocks=nullptr)
Return true if it is safe to merge these two terminator instructions together.
SkipFlags
@ SkipReadMem
@ SkipSideEffect
@ SkipImplicitControlFlow
static bool simplifySwitchDefaultBranch(SwitchInst *SI, DomTreeUpdater *DTU, const DataLayout &DL, AssumptionCache *AC)
static bool incomingValuesAreCompatible(BasicBlock *BB, ArrayRef< BasicBlock * > IncomingBlocks, SmallPtrSetImpl< Value * > *EquivalenceSet=nullptr)
Return true if all the PHI nodes in the basic block BB receive compatible (identical) incoming values...
static void createUnreachableSwitchDefault(SwitchInst *Switch, DomTreeUpdater *DTU, bool RemoveOrigDefaultBlock=true)
static Value * foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector, Constant *DefaultResult, Value *Condition, IRBuilder<> &Builder, const DataLayout &DL, ArrayRef< uint32_t > BranchWeights)
static bool sinkCommonCodeFromPredecessors(BasicBlock *BB, DomTreeUpdater *DTU)
Check whether BB's predecessors end with unconditional branches.
static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI, const DataLayout &DL)
static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL)
Compute masked bits for the condition of a switch and use it to remove dead cases.
static bool blockIsSimpleEnoughToThreadThrough(BasicBlock *BB, BlocksSet &NonLocalUseBlocks)
Return true if we can thread a branch across this block.
static bool foldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL, bool SpeculateUnpredictables)
Given a BB that starts with the specified two-entry PHI node, see if we can eliminate it.
static bool findReaching(BasicBlock *BB, BasicBlock *DefBB, BlocksSet &ReachesNonLocalUses)
static bool extractPredSuccWeights(CondBrInst *PBI, CondBrInst *BI, uint64_t &PredTrueWeight, uint64_t &PredFalseWeight, uint64_t &SuccTrueWeight, uint64_t &SuccFalseWeight)
Return true if either PBI or BI has branch weight available, and store the weights in {Pred|Succ}...
static bool shouldUseSwitchConditionAsTableIndex(ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal, bool HasDefaultResults, const SmallVector< Type * > &ResultTypes, const DataLayout &DL, const TargetTransformInfo &TTI)
static InstructionCost computeSpeculationCost(const User *I, const TargetTransformInfo &TTI)
Compute an abstract "cost" of speculating the given instruction, which is assumed to be safe to specu...
static bool performBranchToCommonDestFolding(CondBrInst *BI, CondBrInst *PBI, DomTreeUpdater *DTU, MemorySSAUpdater *MSSAU, const TargetTransformInfo *TTI)
static std::optional< unsigned > getDenseSwitchRangeReductionShift(ArrayRef< int64_t > Values, int64_t Base, bool OptSize)
SmallPtrSet< BasicBlock *, 8 > BlocksSet
static unsigned skippedInstrFlags(Instruction *I)
static bool mergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU)
If this block is a landingpad exception handling block, categorize all the predecessor invokes into s...
static bool replacingOperandWithVariableIsCheap(const Instruction *I, int OpIdx)
static void eraseTerminatorAndDCECond(Instruction *TI, MemorySSAUpdater *MSSAU=nullptr)
static void eliminateBlockCases(BasicBlock *BB, std::vector< ValueEqualityComparisonCase > &Cases)
Given a vector of bb/value pairs, remove any entries in the list that match the specified block.
static bool mergeConditionalStores(CondBrInst *PBI, CondBrInst *QBI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
static bool mergeNestedCondBranch(CondBrInst *BI, DomTreeUpdater *DTU)
Fold the following pattern: bb0: br i1 cond1, label bb1, label bb2 bb1: br i1 cond2,...
static void sinkLastInstruction(ArrayRef< BasicBlock * > Blocks)
static size_t mapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
static bool tryWidenCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU)
If the previous block ended with a widenable branch, determine if reusing the target block is profita...
static void mergeCompatibleInvokesImpl(ArrayRef< InvokeInst * > Invokes, DomTreeUpdater *DTU)
static bool mergeIdenticalBBs(ArrayRef< BasicBlock * > Candidates, DomTreeUpdater *DTU)
static void getBranchWeights(Instruction *TI, SmallVectorImpl< uint64_t > &Weights)
Get Weights of a given terminator, the default weight is at the front of the vector.
static bool tryToMergeLandingPad(LandingPadInst *LPad, UncondBrInst *BI, BasicBlock *BB, DomTreeUpdater *DTU)
Given an block with only a single landing pad and a unconditional branch try to find another basic bl...
static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, uintptr_t MaxUniqueResults)
static Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB, Instruction *&PreviousAccess)
Determine if we can hoist sink a sole store instruction out of a conditional block.
static Constant * lookupConstant(Value *V, const SmallDenseMap< Value *, Constant * > &ConstantPool)
If V is a Constant, return it.
static bool SimplifyCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI, DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI)
If we have a conditional branch as a predecessor of another block, this function tries to simplify it...
static bool canSinkInstructions(ArrayRef< Instruction * > Insts, DenseMap< const Use *, SmallVector< Value *, 4 > > &PHIOperands)
static void hoistLockstepIdenticalDbgVariableRecords(Instruction *TI, Instruction *I1, SmallVectorImpl< Instruction * > &OtherInsts)
Hoists DbgVariableRecords from I1 and OtherInstrs that are identical in lock-step to TI.
static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU)
static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, DomTreeUpdater *DTU, const DataLayout &DL)
If a switch is only used to initialize one or more phi nodes in a common successor block with only tw...
static bool removeUndefIntroducingPredecessor(BasicBlock *BB, DomTreeUpdater *DTU, AssumptionCache *AC)
If BB has an incoming value that will always trigger undefined behavior (eg.
static bool isUncontrolledConvergentCall(CallBase *CB)
static bool simplifySwitchWhenUMin(SwitchInst *SI, DomTreeUpdater *DTU)
Tries to transform the switch when the condition is umin with a constant.
static bool isSafeCheapLoadStore(const Instruction *I, const TargetTransformInfo &TTI)
static ConstantInt * getKnownValueOnEdge(Value *V, BasicBlock *From, BasicBlock *To)
static std::optional< bool > foldCondBranchOnValueKnownInPredecessorImpl(CondBrInst *BI, const TargetTransformInfo &TTI, DomTreeUpdater *DTU, AssumptionCache *AC, const DataLayout &DL, bool KeepCanonicalLoop)
If we have a conditional branch on something for which we know the constant value in predecessors (e....
static bool dominatesMergePoint(Value *V, BasicBlock *BB, Instruction *InsertPt, SmallPtrSetImpl< Instruction * > &AggressiveInsts, InstructionCost &Cost, InstructionCost Budget, const TargetTransformInfo &TTI, AssumptionCache *AC, SmallPtrSetImpl< Instruction * > &ZeroCostInstructions, unsigned Depth=0)
If we have a merge point of an "if condition" as accepted above, return true if the specified value d...
static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch, Constant *DefaultValue, const SmallVectorImpl< std::pair< ConstantInt *, Constant * > > &Values)
Try to reuse the switch table index compare.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1594
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:463
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:461
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:638
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
BranchProbability getCompl() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void addRangeRetAttr(const ConstantRange &CR)
adds the range attribute to the list of attributes.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
bool isConvergent() const
Determine if the invoke is convergent.
Value * getConvergenceControlToken() const
Return the convergence control token for this call, if it exists.
bool isDataOperand(const Use *U) const
bool tryIntersectAttributes(const CallBase *Other)
Try to intersect the attributes from 'this' CallBase and the 'Other' CallBase.
This class represents a function call, abstracting a target machine's calling convention.
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
CleanupPadInst * getCleanupPad() const
Convenience accessor.
BasicBlock * getUnwindDest() const
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
ConstantFolder - Create constants with minimum, target independent, folding.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isNegative() const
Definition Constants.h:214
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
IntegerType * getIntegerType() const
Variant of the getType() method to always return an IntegerType, which reduces the amount of casting ...
Definition Constants.h:198
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A constant pointer value that points to null.
Definition Constants.h:716
This class represents a range of values.
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool isUpperWrapped() const
Return true if the exclusive upper bound wraps around the unsigned domain.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:83
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
simple_ilist< DbgRecord >::iterator self_iterator
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:126
bool isSameSourceLocation(const DebugLoc &Other) const
Return true if the source locations match, ignoring isImplicitCode and source atom info.
Definition DebugLoc.h:250
static DebugLoc getTemporary()
Definition DebugLoc.h:152
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:186
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:173
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2474
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2215
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:1218
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:451
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:177
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2811
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1534
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:2021
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1212
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1856
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:1241
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2458
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:1913
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:456
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2568
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1458
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2987
Indirect Branch Instruction.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
LLVM_ABI void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
LLVM_ABI void dropLocation()
Drop the instruction's debug location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY
Return true if there are any uses of this instruction in blocks other than the specified block.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
@ CompareUsingIntersectedAttrs
Check for equivalence with intersected callbase attrs.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
LLVM_ABI void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Invoke instruction.
void setNormalDest(BasicBlock *B)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
The landingpad instruction holds all of the information necessary to generate correct exception handl...
An instruction for reading from memory.
static unsigned getPointerOperandIndex()
Iterates through instructions in a set of blocks in reverse order from the first non-terminator.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1081
Helper class to manipulate !mmra metadata nodes.
bool empty() const
Definition MapVector.h:80
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
size_type size() const
Definition MapVector.h:59
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getValue() const
Convenience accessor.
Return a value (possibly void), from a function.
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
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.
bool isAtomic() const
Return true if this store has an atomic ordering.
Align getAlign() const
bool isSimple() const
Value * getValueOperand()
bool isUnordered() const
static unsigned getPointerOperandIndex()
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
Value * getPointerOperand()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
LLVM_ABI void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
LLVM_ABI CaseWeightOpt getSuccessorWeight(unsigned idx)
LLVM_ABI void replaceDefaultDest(SwitchInst::CaseIt I)
Replace the default destination by given case.
std::optional< uint32_t > CaseWeightOpt
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
Multiway switch.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
BasicBlock * getSuccessor(unsigned idx) const
void setCondition(Value *V)
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
CaseIteratorImpl< CaseHandle > CaseIt
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
unsigned getNumSuccessors() const
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
void setSuccessor(BasicBlock *NewSucc)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static constexpr uint64_t MaximumAlignment
Definition Value.h:801
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:49
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Represents an op.with.overflow intrinsic.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A range adaptor for a pair of iterators.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
LLVM_ABI bool foldBranchToCommonDest(CondBrInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=nullptr, AssumptionCache *AC=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
static cl::opt< unsigned > MaxLoopHeaderThreadingSearchBlocks("simplifycfg-max-loop-header-threading-search", cl::Hidden, cl::init(1024), cl::desc("Limit number of blocks searched to prove that threading through " "a loop header keeps the loop canonical"))
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
static cl::opt< unsigned > MaxSwitchCasesPerResult("max-switch-cases-per-result", cl::Hidden, cl::init(16), cl::desc("Limit cases to analyze when converting a switch to select"))
InstructionCost Cost
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
static cl::opt< bool > SpeculateOneExpensiveInst("speculate-one-expensive-inst", cl::Hidden, cl::init(true), cl::desc("Allow exactly one expensive instruction to be speculatively " "executed"))
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
auto pred_end(const MachineBasicBlock *BB)
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
auto accumulate(R &&Range, E &&Init)
Wrapper for std::accumulate.
Definition STLExtras.h:1718
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
static cl::opt< unsigned > MaxSpeculationDepth("max-speculation-depth", cl::Hidden, cl::init(10), cl::desc("Limit maximum recursion depth when calculating costs of " "speculatively executed instructions"))
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
static cl::opt< unsigned > PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), cl::desc("Control the amount of phi node folding to perform (default = 2)"))
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
static cl::opt< bool > MergeCondStoresAggressively("simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), cl::desc("When merging conditional stores, do so even if the resultant " "basic blocks are unlikely to be if-converted as a result"))
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
static cl::opt< unsigned > BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden, cl::init(2), cl::desc("Maximum cost of combining conditions when " "folding branches"))
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
static cl::opt< bool > SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), cl::desc("Sink common instructions down to the end block"))
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
static cl::opt< bool > HoistStoresWithCondFaulting("simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist stores if the target supports conditional faulting"))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr detail::StaticCastFunc< To > StaticCastTo
Function objects corresponding to the Cast types defined above.
Definition Casting.h:882
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI CondBrInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition Local.cpp:1185
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
LLVM_ABI void InvertBranch(CondBrInst *PBI, IRBuilderBase &Builder)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
static cl::opt< bool > EnableMergeCompatibleInvokes("simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true), cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"))
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition Local.cpp:2923
auto succ_size(const MachineBasicBlock *BB)
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static cl::opt< unsigned > MaxJumpThreadingLiveBlocks("max-jump-threading-live-blocks", cl::Hidden, cl::init(24), cl::desc("Limit number of blocks a define in a threaded block is allowed " "to be live in"))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3176
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
static cl::opt< int > MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden, cl::init(10), cl::desc("Max size of a block which is still considered " "small enough to thread through"))
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
LLVM_ABI bool isWidenableBranch(const User *U)
Returns true iff U is a widenable branch (that is, extractWidenableCondition returns widenable condit...
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
static cl::opt< unsigned > HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden, cl::init(20), cl::desc("Allow reordering across at most this many " "instructions when hoisting"))
LLVM_ABI cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
static cl::opt< bool > MergeCondStores("simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores even if an unconditional store does not " "precede - hoist multiple conditional stores into a single " "predicated store"))
static cl::opt< unsigned > BranchFoldToCommonDestVectorMultiplier("simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden, cl::init(2), cl::desc("Multiplier to apply to threshold when determining whether or not " "to fold branch to common destination when vector operations are " "present"))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
Definition Local.cpp:3457
@ Sub
Subtraction of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
IntPtrTy
Definition InstrProf.h:82
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3963
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
void RemapDbgRecord(Module *M, DbgRecord *DR, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecord DR using the value map VM.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
static cl::opt< bool > HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores if an unconditional store precedes"))
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
static cl::opt< unsigned > HoistLoadsStoresWithCondFaultingThreshold("hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(6), cl::desc("Control the maximal conditional load/store that we are willing " "to speculatively execute to eliminate conditional branch " "(default = 6)"))
static cl::opt< bool > HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true), cl::desc("Hoist common instructions up to the parent block"))
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static cl::opt< unsigned > TwoEntryPHINodeFoldingThreshold("two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4), cl::desc("Control the maximal total instruction cost that we are willing " "to speculatively execute to fold a 2-entry PHI node into a " "select (default = 4)"))
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
SmallVector< uint64_t, 2 > getDisjunctionWeights(const SmallVector< T1, 2 > &B1, const SmallVector< T2, 2 > &B2)
Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2 are 2 booleans that are t...
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:266
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
static cl::opt< bool > HoistLoadsWithCondFaulting("simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(true), cl::desc("Hoist loads if the target supports conditional faulting"))
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1550
@ Keep
No function return thunk.
Definition CodeGen.h:370
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
SmallVectorImpl< ConstantInt * > * Cases
SmallVectorImpl< ConstantInt * > * OtherCases
Checking whether two BBs are equal depends on the contents of the BasicBlock and the incoming values ...
SmallDenseMap< BasicBlock *, Value *, 8 > BB2ValueMap
Phi2IVsMap * PhiPredIVs
DenseMap< PHINode *, BB2ValueMap > Phi2IVsMap
static bool canBeMerged(const BasicBlock *BB)
BasicBlock * BB
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS)
static unsigned getHashValue(const EqualBBWrapper *EBW)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344