48 #define DEBUG_TYPE "lower-switch" 60 const std::vector<IntRange> &Ranges) {
67 Ranges, R, [](IntRange A, IntRange
B) {
return A.High < B.High; });
68 return I != Ranges.end() &&
I->Low <= R.Low;
95 : Low(low),
High(high), BB(bb) {}
98 using CaseVector = std::vector<CaseRange>;
99 using CaseItr = std::vector<CaseRange>::iterator;
106 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
110 const std::vector<IntRange> &UnreachableRanges);
114 unsigned Clusterify(CaseVector &Cases,
SwitchInst *SI);
120 bool operator()(
const LowerSwitch::CaseRange& C1,
121 const LowerSwitch::CaseRange& C2) {
122 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
123 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
136 "Lower SwitchInst's to branches",
false,
false)
144 return new LowerSwitch();
148 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
149 auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>();
159 bool Changed =
false;
167 if (DeleteList.
count(Cur))
172 processSwitchInst(
SI, DeleteList, AC, LVI);
187 const LowerSwitch::CaseVector &
C) {
190 for (LowerSwitch::CaseVector::const_iterator
B = C.begin(),
E = C.end();
192 O <<
"[" <<
B->Low->getValue() <<
", " <<
B->High->getValue() <<
"]";
220 unsigned LocalNumMergedCases = NumMergedCases;
221 for (; Idx !=
E; ++Idx) {
231 for (++Idx; LocalNumMergedCases > 0 && Idx <
E; ++Idx)
234 LocalNumMergedCases--;
249 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
ConstantInt *LowerBound,
253 const std::vector<IntRange> &UnreachableRanges) {
254 assert(LowerBound && UpperBound &&
"Bounds must be initialized");
255 unsigned Size = End - Begin;
262 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
263 unsigned NumMergedCases = 0;
265 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
268 return newLeafBlock(*Begin, Val, LowerBound, UpperBound, OrigBlock,
272 unsigned Mid = Size / 2;
273 std::vector<CaseRange> LHS(Begin, Begin + Mid);
275 std::vector<CaseRange> RHS(Begin + Mid, End);
278 CaseRange &Pivot = *(Begin + Mid);
279 LLVM_DEBUG(
dbgs() <<
"Pivot ==> [" << Pivot.Low->getValue() <<
", " 280 << Pivot.High->getValue() <<
"]\n");
291 NewLowerBound->getValue() - 1);
293 if (!UnreachableRanges.empty()) {
295 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
296 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
297 IntRange Gap = { GapLow, GapHigh };
298 if (GapHigh >= GapLow &&
IsInRanges(Gap, UnreachableRanges))
299 NewUpperBound = LHS.back().High;
304 <<
"RHS Bounds ==> [" << NewLowerBound->getSExtValue()
313 Val, Pivot.Low,
"Pivot");
315 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
316 NewUpperBound, Val, NewNode, OrigBlock,
318 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
319 UpperBound, Val, NewNode, OrigBlock,
322 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
344 if (Leaf.Low == Leaf.High) {
347 Leaf.Low,
"SwitchLeaf");
350 if (Leaf.Low == LowerBound) {
354 }
else if (Leaf.High == UpperBound) {
358 }
else if (Leaf.Low->isZero()) {
383 uint64_t Range = Leaf.High->getSExtValue() -
384 Leaf.Low->getSExtValue();
385 for (uint64_t j = 0; j < Range; ++j) {
390 assert(BlockIdx != -1 &&
"Switch didn't go to this successor??");
400 unsigned LowerSwitch::Clusterify(CaseVector& Cases,
SwitchInst *
SI) {
401 unsigned NumSimpleCases = 0;
404 for (
auto Case : SI->
cases()) {
407 Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
408 Case.getCaseSuccessor()));
415 if (Cases.size() >= 2) {
416 CaseItr
I = Cases.begin();
417 for (CaseItr J = std::next(I),
E = Cases.end(); J !=
E; ++J) {
418 int64_t nextValue = J->Low->getSExtValue();
419 int64_t currentValue = I->High->getSExtValue();
425 assert(nextValue > currentValue &&
"Cases should be strictly ascending");
426 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
429 }
else if (++I != J) {
433 Cases.erase(std::next(I), Cases.end());
436 return NumSimpleCases;
441 void LowerSwitch::processSwitchInst(
SwitchInst *SI,
453 DeleteList.
insert(OrigBlock);
459 const unsigned NumSimpleCases = Clusterify(Cases, SI);
460 LLVM_DEBUG(
dbgs() <<
"Clusterify finished. Total clusters: " << Cases.size()
461 <<
". Total non-default cases: " << NumSimpleCases
462 <<
"\nCase clusters: " << Cases <<
"\n");
468 fixPhis(Default, OrigBlock, OrigBlock);
475 bool DefaultIsUnreachableFromSwitch =
false;
481 LowerBound = Cases.front().Low;
482 UpperBound = Cases.back().High;
483 DefaultIsUnreachableFromSwitch =
true;
505 APInt Low = Cases.front().Low->getValue();
506 APInt High = Cases.back().High->getValue();
512 DefaultIsUnreachableFromSwitch = (Min + (NumSimpleCases - 1) == Max);
515 std::vector<IntRange> UnreachableRanges;
517 if (DefaultIsUnreachableFromSwitch) {
522 IntRange R = {std::numeric_limits<int64_t>::min(),
524 UnreachableRanges.push_back(R);
525 for (
const auto &
I : Cases) {
526 int64_t Low =
I.Low->getSExtValue();
527 int64_t
High =
I.High->getSExtValue();
529 IntRange &LastRange = UnreachableRanges.back();
530 if (LastRange.Low == Low) {
532 UnreachableRanges.pop_back();
535 assert(Low > LastRange.Low);
536 LastRange.High = Low - 1;
540 UnreachableRanges.push_back(R);
544 int64_t
N = High - Low + 1;
545 unsigned &Pop = Popularity[
I.BB];
546 if ((Pop += N) > MaxPop) {
553 for (
auto I = UnreachableRanges.begin(),
E = UnreachableRanges.end();
565 const unsigned NumDefaultEdges = SI->
getNumCases() + 1 - NumSimpleCases;
566 for (
unsigned I = 0;
I < NumDefaultEdges; ++
I)
571 assert(MaxPop > 0 && PopSucc);
575 Cases, [PopSucc](
const CaseRange &R) {
return R.BB == PopSucc; }),
584 for (
unsigned I = 0 ;
I < (MaxPop - 1) ; ++
I)
602 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
603 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
607 fixPhis(Default, OrigBlock, NewDefault);
618 DeleteList.
insert(OldDefault);
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
ConstantRange getConstantRange(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
Return the ConstantRange constraint that is known to hold for the specified value at the end of the s...
iterator erase(iterator where)
This class represents lattice values for constants.
Wrapper around LazyValueInfo.
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void push_back(const T &Elt)
bool slt(const APInt &RHS) const
Signed less than comparison.
FunctionPass * createLowerSwitchPass()
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
static bool IsInRanges(const IntRange &R, const std::vector< IntRange > &Ranges)
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
static ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
INITIALIZE_PASS_BEGIN(LowerSwitch, "lowerswitch", "Lower SwitchInst's to branches", false, false) INITIALIZE_PASS_END(LowerSwitch
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
const APInt & getValue() const
Return the constant as an APInt value reference.
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
const BasicBlock & getEntryBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
BasicBlock * getDefaultDest() const
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
bool pred_empty(const BasicBlock *BB)
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB, const unsigned NumMergedCases=std::numeric_limits< unsigned >::max())
Update the first occurrence of the "switch statement" BB in the PHI node with the "new" BB...
void sort(IteratorTy Start, IteratorTy End)
const InstListType & getInstList() const
Return the underlying instruction list container.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
Align max(MaybeAlign Lhs, Align Rhs)
This class represents a range of values.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Class for arbitrary precision integers.
void push_back(pointer val)
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
iterator insert(iterator where, pointer New)
Lower SwitchInst s to branches
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
void eraseBlock(BasicBlock *BB)
Inform the analysis cache that we have erased a block.
This pass computes, caches, and vends lazy value constraint information.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void initializeLowerSwitchPass(PassRegistry &)
This class implements an extremely fast bulk output stream that can only output to a stream...
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
void disableDT()
Disables use of the DominatorTree within LVI.
const BasicBlock * getParent() const
#define LLVM_ATTRIBUTE_USED