51 using namespace llvm::PatternMatch;
53 #define DEBUG_TYPE "local"
55 STATISTIC(NumRemoved,
"Number of unreachable basic blocks removed");
74 if (
BranchInst *BI = dyn_cast<BranchInst>(T)) {
75 if (BI->isUnconditional())
return false;
79 if (
ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
82 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
83 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
105 assert(BI->getParent() &&
"Terminator not inserted in block!");
110 Value *Cond = BI->getCondition();
111 BI->eraseFromParent();
112 if (DeleteDeadConditions)
127 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
128 SI->getNumCases() > 0) {
129 TheOnlyDest =
SI->case_begin().getCaseSuccessor();
136 if (
i.getCaseValue() == CI) {
137 TheOnlyDest =
i.getCaseSuccessor();
143 if (
i.getCaseSuccessor() == DefaultDest) {
145 unsigned NCases =
SI->getNumCases();
153 auto *CI = mdconst::extract<ConstantInt>(MD->
getOperand(MD_i));
157 unsigned idx =
i.getCaseIndex();
158 Weights[0] += Weights[idx+1];
164 createBranchWeights(Weights));
167 DefaultDest->removePredecessor(
SI->getParent());
176 if (
i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest =
nullptr;
179 if (CI && !TheOnlyDest) {
182 TheOnlyDest =
SI->getDefaultDest();
195 if (Succ == TheOnlyDest)
196 TheOnlyDest =
nullptr;
202 Value *Cond =
SI->getCondition();
203 SI->eraseFromParent();
204 if (DeleteDeadConditions)
209 if (
SI->getNumCases() == 1) {
219 SI->getDefaultDest());
223 mdconst::dyn_extract<ConstantInt>(MD->
getOperand(2));
225 mdconst::dyn_extract<ConstantInt>(MD->
getOperand(1));
231 SIDef->getValue().getZExtValue()));
240 SI->eraseFromParent();
249 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
250 BasicBlock *TheOnlyDest = BA->getBasicBlock();
254 for (
unsigned i = 0, e = IBI->getNumDestinations();
i != e; ++
i) {
255 if (IBI->getDestination(
i) == TheOnlyDest)
256 TheOnlyDest =
nullptr;
261 IBI->eraseFromParent();
262 if (DeleteDeadConditions)
290 if (!I->
use_empty() || isa<TerminatorInst>(
I))
return false;
300 if (DDI->getAddress())
316 if (II->getIntrinsicID() == Intrinsic::stacksave)
320 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
321 II->getIntrinsicID() == Intrinsic::lifetime_end)
322 return isa<UndefValue>(II->getArgOperand(1));
328 if (II->getIntrinsicID() == Intrinsic::assume ||
329 II->getIntrinsicID() == Intrinsic::experimental_guard) {
330 if (
ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
331 return !Cond->isZero();
340 if (
Constant *
C = dyn_cast<Constant>(CI->getArgOperand(0)))
341 return C->isNullValue() || isa<UndefValue>(
C);
384 }
while (!DeadInsts.
empty());
400 for (++UI; UI != UE; ++UI) {
416 I = cast<Instruction>(*
I->user_begin())) {
422 if (!Visited.
insert(
I).second) {
465 WorkList.
insert(cast<Instruction>(U));
470 bool Changed =
false;
491 bool MadeChange =
false;
508 assert(!BI->isTerminator());
514 if (!WorkList.count(I))
518 while (!WorkList.empty()) {
543 if (!isa<PHINode>(BB->
begin()))
552 while (
PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
554 Value *OldPhiIt = PhiIt;
562 if (PhiIt != OldPhiIt) PhiIt = &BB->
front();
574 while (
PHINode *PN = dyn_cast<PHINode>(DestBB->
begin())) {
575 Value *NewVal = PN->getIncomingValue(0);
579 PN->eraseFromParent();
583 assert(PredBB &&
"Block doesn't have a single predecessor!");
621 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
650 if (BBPN && BBPN->getParent() == BB) {
653 if (BBPreds.
count(IBB) &&
657 << Succ->
getName() <<
" is conflicting with "
658 << BBPN->getName() <<
" with regard to common predecessor "
670 if (BBPreds.
count(IBB) &&
673 << Succ->
getName() <<
" is conflicting with regard to common "
674 <<
"predecessor " << IBB->
getName() <<
"\n");
701 if (!isa<UndefValue>(OldVal)) {
703 IncomingValues.
find(BB)->second == OldVal) &&
704 "Expected OldVal to match incoming value from BB!");
706 IncomingValues.
insert(std::make_pair(BB, OldVal));
711 if (It != IncomingValues.
end())
return It->second;
730 if (!isa<UndefValue>(V))
731 IncomingValues.
insert(std::make_pair(BB, V));
745 if (!isa<UndefValue>(V))
continue;
749 if (It == IncomingValues.
end())
continue;
766 assert(OldVal &&
"No entry in PHI for Pred BB!");
783 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->
getParent() == BB) {
784 PHINode *OldValPN = cast<PHINode>(OldVal);
801 for (
unsigned i = 0, e = BBPreds.
size();
i != e; ++
i) {
824 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
828 if (BB == Succ)
return false;
846 if (!Succ->getSinglePredecessor()) {
848 while (isa<PHINode>(*BBI)) {
849 for (
Use &U : BBI->uses()) {
850 if (
PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
851 if (PN->getIncomingBlock(U) != BB)
861 DEBUG(
dbgs() <<
"Killing Trivial BB: \n" << *BB);
863 if (isa<PHINode>(Succ->begin())) {
877 if (Succ->getSinglePredecessor()) {
883 Succ->getInstList().
splice(Succ->getFirstNonPHI()->getIterator(),
888 assert(PN->use_empty() &&
"There shouldn't be any uses here!");
889 PN->eraseFromParent();
906 if (!Succ->hasName()) Succ->takeName(BB);
921 struct PHIDenseMapInfo {
922 static PHINode *getEmptyKey() {
925 static PHINode *getTombstoneKey() {
928 static unsigned getHashValue(
PHINode *PN) {
937 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
938 RHS == getEmptyKey() || RHS == getTombstoneKey())
948 bool Changed =
false;
950 auto Inserted = PHISet.
insert(PN);
951 if (!Inserted.second) {
976 assert(PrefAlign > Align);
980 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
987 Align = std::max(AI->getAlignment(), Align);
988 if (PrefAlign <= Align)
995 AI->setAlignment(PrefAlign);
999 if (
auto *GO = dyn_cast<GlobalObject>(V)) {
1001 Align = std::max(GO->getAlignment(), Align);
1002 if (PrefAlign <= Align)
1009 if (!GO->canIncreaseAlignment())
1012 GO->setAlignment(PrefAlign);
1025 "getOrEnforceKnownAlignment expects a pointer!");
1028 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1030 unsigned TrailZ = KnownZero.countTrailingOnes();
1034 TrailZ =
std::min(TrailZ,
unsigned(
sizeof(
unsigned) * CHAR_BIT - 1));
1036 unsigned Align = 1u <<
std::min(BitWidth - 1, TrailZ);
1041 if (PrefAlign > Align)
1063 DVI->getOffset() == 0 &&
1064 DVI->getVariable() == DIVar &&
1065 DVI->getExpression() == DIExpr)
1080 for (
auto DVI : DbgValues) {
1081 assert (DVI->getValue() == APN);
1082 assert (DVI->getOffset() == 0);
1083 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1095 assert(DIVar &&
"Missing variable");
1112 unsigned FragmentOffset = 0;
1115 auto Fragment = DIExpr->getFragmentInfo();
1117 Ops.
append(DIExpr->elements_begin(), DIExpr->elements_end()-3);
1118 FragmentOffset = Fragment->OffsetInBits;
1120 Ops.
append(DIExpr->elements_begin(), DIExpr->elements_end());
1141 assert(DIVar &&
"Missing variable");
1161 assert(DIVar &&
"Missing variable");
1172 if (InsertionPt != BB->
end())
1190 if (
auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1196 for (
auto &
I : Dbgs) {
1206 for (
auto &AIUse : AI->
uses()) {
1207 User *U = AIUse.getUser();
1209 if (AIUse.getOperandNo() == 1)
1211 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(U)) {
1213 }
else if (
CallInst *CI = dyn_cast<CallInst>(U)) {
1219 NewDIExpr.
push_back(dwarf::DW_OP_deref);
1220 NewDIExpr.
append(DIExpr->elements_begin(), DIExpr->elements_end());
1221 DIB.insertDbgValueIntrinsic(AI, 0, DDI->
getVariable(),
1222 DIB.createExpression(NewDIExpr),
1262 }
else if (Offset < 0) {
1271 if (!Deref && !Offset)
1288 bool Deref,
int Offset) {
1295 assert(DIVar &&
"Missing variable");
1301 Builder.
insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1317 assert(DIVar &&
"Missing variable");
1322 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1323 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1332 NewDIExpr.
append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
1345 for (
auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1347 if (
auto *DVI = dyn_cast<DbgValueInst>(U.
getUser()))
1353 unsigned NumDeadInst = 0;
1357 while (EndInst != &BB->
front()) {
1366 if (!isa<DbgInfoIntrinsic>(Inst))
1374 bool PreserveLCSSA) {
1379 Successor->removePredecessor(BB, PreserveLCSSA);
1392 unsigned NumInstrsRemoved = 0;
1394 while (BBI != BBE) {
1395 if (!BBI->use_empty())
1400 return NumInstrsRemoved;
1447 InvokeArgs, OpBundles, CI->
getName(), BB);
1468 bool Changed =
false;
1479 if (
auto *II = dyn_cast<IntrinsicInst>(&
I)) {
1480 if (II->getIntrinsicID() == Intrinsic::assume) {
1489 if (II->getIntrinsicID() == Intrinsic::experimental_guard) {
1499 if (!isa<UnreachableInst>(II->getNextNode())) {
1507 if (
auto *CI = dyn_cast<CallInst>(&
I)) {
1508 Value *Callee = CI->getCalledValue();
1509 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1514 if (CI->doesNotReturn()) {
1518 if (!isa<UnreachableInst>(CI->getNextNode())) {
1530 if (
auto *
SI = dyn_cast<StoreInst>(&
I)) {
1532 if (
SI->isVolatile())
continue;
1536 if (isa<UndefValue>(Ptr) ||
1537 (isa<ConstantPointerNull>(Ptr) &&
1538 SI->getPointerAddressSpace() == 0)) {
1547 if (
auto *II = dyn_cast<InvokeInst>(Terminator)) {
1549 Value *Callee = II->getCalledValue();
1550 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1554 if (II->use_empty() && II->onlyReadsMemory()) {
1557 II->getUnwindDest()->removePredecessor(II->getParent());
1563 }
else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
1565 struct CatchPadDenseMapInfo {
1577 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1578 RHS == getEmptyKey() || RHS == getTombstoneKey())
1588 detail::DenseSetEmpty Empty;
1590 E = CatchSwitch->handler_end();
1593 auto *CatchPad = cast<CatchPadInst>(HandlerBB->
getFirstNonPHI());
1594 if (!HandlerSet.insert({CatchPad, Empty}).second) {
1595 CatchSwitch->removeHandler(
I);
1607 }
while (!Worklist.empty());
1614 if (
auto *II = dyn_cast<InvokeInst>(TI)) {
1622 if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
1624 UnwindDest = CRI->getUnwindDest();
1625 }
else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
1627 CatchSwitch->getParentPad(),
nullptr, CatchSwitch->getNumHandlers(),
1628 CatchSwitch->getName(), CatchSwitch);
1629 for (
BasicBlock *PadBB : CatchSwitch->handlers())
1632 NewTI = NewCatchSwitch;
1633 UnwindDest = CatchSwitch->getUnwindDest();
1657 NumRemoved += F.
size()-Reachable.
size();
1662 if (Reachable.
count(&*BB))
1670 BB->dropAllReferences();
1674 if (!Reachable.
count(&*
I))
1687 for (
const auto &MD : Metadata) {
1688 unsigned Kind = MD.first;
1743 if (isa<LoadInst>(K) || isa<StoreInst>(K))
1748 unsigned KnownIDs[] = {
1769 DEBUG(
dbgs() <<
"Replace dominated use of '"
1771 << *To <<
" in " << *U <<
"\n");
1787 auto *
I = cast<Instruction>(U.
getUser());
1791 << *To <<
" in " << *U <<
"\n");
1803 if (
F->hasFnAttribute(
"gc-leaf-function"))
1806 if (
auto IID =
F->getIntrinsicID())
1808 return IID != Intrinsic::experimental_gc_statepoint &&
1809 IID != Intrinsic::experimental_deoptimize;
1819 BitPart(
Value *
P,
unsigned BW) : Provider(P) {
1820 Provenance.resize(BW);
1829 enum { Unset = -1 };
1860 auto I = BPS.find(V);
1864 auto &Result = BPS[V] =
None;
1871 MatchBitReversals, BPS);
1873 MatchBitReversals, BPS);
1878 if (!
A->Provider ||
A->Provider != B->Provider)
1881 Result = BitPart(
A->Provider, BitWidth);
1882 for (
unsigned i = 0;
i <
A->Provenance.size(); ++
i) {
1883 if (
A->Provenance[
i] != BitPart::Unset &&
1884 B->Provenance[
i] != BitPart::Unset &&
1885 A->Provenance[
i] != B->Provenance[
i])
1886 return Result =
None;
1888 if (
A->Provenance[
i] == BitPart::Unset)
1889 Result->Provenance[
i] = B->Provenance[
i];
1891 Result->Provenance[
i] =
A->Provenance[
i];
1898 if (
I->isLogicalShift() && isa<ConstantInt>(
I->getOperand(1))) {
1900 cast<ConstantInt>(
I->getOperand(1))->getLimitedValue(~0U);
1902 if (BitShift > BitWidth)
1906 MatchBitReversals, BPS);
1912 auto &
P = Result->Provenance;
1913 if (
I->getOpcode() == Instruction::Shl) {
1914 P.erase(std::prev(
P.end(), BitShift),
P.end());
1915 P.insert(
P.begin(), BitShift, BitPart::Unset);
1917 P.erase(
P.begin(), std::next(
P.begin(), BitShift));
1918 P.insert(
P.end(), BitShift, BitPart::Unset);
1927 isa<ConstantInt>(
I->getOperand(1))) {
1928 APInt Bit(
I->getType()->getPrimitiveSizeInBits(), 1);
1929 const APInt &AndMask = cast<ConstantInt>(
I->getOperand(1))->getValue();
1933 unsigned NumMaskedBits = AndMask.countPopulation();
1934 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
1938 MatchBitReversals, BPS);
1943 for (
unsigned i = 0;
i < BitWidth; ++
i,
Bit <<= 1)
1945 if ((AndMask & Bit) == 0)
1946 Result->Provenance[
i] = BitPart::Unset;
1951 if (
I->getOpcode() == Instruction::ZExt) {
1953 MatchBitReversals, BPS);
1957 Result = BitPart(Res->Provider, BitWidth);
1958 auto NarrowBitWidth =
1959 cast<IntegerType>(cast<ZExtInst>(
I)->getSrcTy())->
getBitWidth();
1960 for (
unsigned i = 0;
i < NarrowBitWidth; ++
i)
1961 Result->Provenance[
i] = Res->Provenance[
i];
1962 for (
unsigned i = NarrowBitWidth;
i < BitWidth; ++
i)
1963 Result->Provenance[
i] = BitPart::Unset;
1970 Result = BitPart(V, BitWidth);
1971 for (
unsigned i = 0;
i < BitWidth; ++
i)
1972 Result->Provenance[
i] =
i;
1977 unsigned BitWidth) {
1978 if (From % 8 != To % 8)
1984 return From == BitWidth - To - 1;
1988 unsigned BitWidth) {
1989 return From == BitWidth - To - 1;
1995 Instruction *
I,
bool MatchBSwaps,
bool MatchBitReversals,
1999 if (!MatchBSwaps && !MatchBitReversals)
2006 unsigned DemandedBW = BW;
2010 DemandedTy = cast<IntegerType>(Trunc->getType());
2016 std::map<Value *, Optional<BitPart>> BPS;
2020 auto &BitProvenance = Res->Provenance;
2024 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse =
true;
2025 for (
unsigned i = 0;
i < DemandedBW; ++
i) {
2033 if (OKForBSwap && MatchBSwaps)
2034 Intrin = Intrinsic::bswap;
2035 else if (OKForBitReverse && MatchBitReversals)
2036 Intrin = Intrinsic::bitreverse;
2040 if (ITy != DemandedTy) {
2042 Value *Provider = Res->Provider;
2043 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2045 if (DemandedTy != ProviderTy) {
AttributeSet getAttributes() const
Return the parameter attributes for this call.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type (if unknown returns 0).
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
static bool markAliveBlocks(Function &F, SmallPtrSetImpl< BasicBlock * > &Reachable)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
void push_back(const T &Elt)
use_iterator_impl< Use > use_iterator
A parsed version of the target data layout string in and methods for querying it. ...
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, bool Deref, int Offset=0)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
ConstantIntTy * getCaseValue()
Resolves case value for current case.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
iterator_range< use_iterator > uses()
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
static unsigned enforceKnownAlignment(Value *V, unsigned Align, unsigned PrefAlign, const DataLayout &DL)
enforceKnownAlignment - If the specified pointer points to an object that we control, modify the object's alignment to PrefAlign.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
LLVM Argument representation.
void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple llvm.dbg.value instructions when the alloca it describes is replaced with a new val...
uint64_t getZExtValue() const
Get zero extended value.
const Instruction & back() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
AttributeSet getAttributes() const
Return the parameter attributes for this invoke.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ)
CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an almost-empty BB ending in an unco...
DbgDeclareInst * FindAllocaDbgDeclare(Value *V)
Finds the llvm.dbg.declare intrinsic corresponding to an alloca, if any.
match_zero m_Zero()
Match an arbitrary zero/null constant.
Implements a dense probed hash-table based set.
This class represents zero extension of integer types.
unsigned getNumOperands() const
unsigned getNumOperands() const
Return number of MDNode operands.
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
value_op_iterator value_op_begin()
static MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
This class represents a function call, abstracting a target machine's calling convention.
size_type count(PtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DominatorTree *DT=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!)...
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
A cache of .assume calls within a function.
bool isTokenTy() const
Return true if this is 'token'.
value_op_iterator value_op_end()
const Function * getParent() const
Return the enclosing method, or null if none.
static void replaceUndefValuesInPhi(PHINode *PN, const IncomingValueMap &IncomingValues)
Replace the incoming undef values to a phi with the values from a block-to-value map.
bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
const Instruction & front() const
This class represents a sign extension of integer types.
An instruction for reading from memory.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred)
Like BasicBlock::removePredecessor, this method is called when we're about to delete Pred as a predec...
static Value * selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, IncomingValueMap &IncomingValues)
Determines the value to use as the phi node input for a block.
Type * getElementType() const
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
Instruction * insertDbgValueIntrinsic(llvm::Value *Val, uint64_t Offset, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, BasicBlock *InsertAtEnd)
Insert a new llvm.dbg.value intrinsic call.
uint64_t getOffset() const
void setAttributes(AttributeSet Attrs)
Set the parameter attributes for this invoke.
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
StringRef getName() const
Return a constant reference to the value's name.
block_iterator block_end()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
void setCallingConv(CallingConv::ID CC)
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Value * getAddress() const
The address of a basic block.
bool match(Val *V, const Pattern &P)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
const APInt & getValue() const
Return the constant as an APInt value reference.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
Instruction * insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, BasicBlock *InsertAtEnd)
Insert a new llvm.dbg.declare intrinsic call.
A Use represents the edge between a Value definition and its users.
bool hasOptimizedCodeGen(LibFunc::Func F) const
Tests if the function is both available and a candidate for optimized code generation.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
static const Optional< BitPart > & collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, std::map< Value *, Optional< BitPart >> &BPS)
Analyze the specified subexpression and see if it is capable of providing pieces of a bswap or bitrev...
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
bool canSimplifyInvokeNoUnwind(const Function *F)
Only used in LLVM metadata.
static const unsigned MaximumAlignment
block_iterator block_begin()
LLVM_NODISCARD bool empty() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress, DIBuilder &Builder, int Offset)
void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction...
user_iterator_impl< User > user_iterator
bool insert(const value_type &X)
Insert a new element into the SetVector.
static void changeToCall(InvokeInst *II)
changeToCall - Convert the specified invoke into a normal call.
static bool isEqual(const Function &Caller, const Function &Callee)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value handle that is nullable, but tries to track the Value.
bool isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
static bool areAllUsesEqual(Instruction *I)
areAllUsesEqual - Check whether the uses of a value are all the same.
static MDNode * intersect(MDNode *A, MDNode *B)
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
True if this is an instance of ArrayType.
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
static void gatherIncomingValuesToPhi(PHINode *PN, IncomingValueMap &IncomingValues)
Create a map from block to value for the operands of a given phi.
element_iterator elements_begin() const
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
bool doesNotAccessMemory() const
Determine if the function does not access memory.
This class represents a truncation of integer types.
BasicBlock * getNormalDest() const
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with etc Experimental Use value profile to guide fuzzing Number of simultaneous worker processes to run the jobs If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
void setAttributes(AttributeSet Attrs)
Set the parameter attributes for this call.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
unsigned getNumIncomingValues() const
Return the number of incoming edges.
DenseMap< BasicBlock *, Value * > IncomingValueMap
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
bool getLibFunc(StringRef funcName, LibFunc::Func &F) const
Searches for a particular function name.
static MDNode * getMostGenericRange(MDNode *A, MDNode *B)
element_iterator elements_end() const
Subclasses of this class are all able to terminate a basic block.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, Instruction *I)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DIExpression * getExpression() const
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
Conditional or Unconditional Branch instruction.
void ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, StoreInst *SI, DIBuilder &Builder)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
static MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
This function has undefined behavior.
This is an important base class in LLVM.
PointerType * getType() const
Overload to return most specific pointer type.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Indirect Branch Instruction.
std::pair< iterator, bool > insert(const ValueT &V)
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
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...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static bool CanMergeValues(Value *First, Value *Second)
CanMergeValues - Return true if we can choose one of these values to use in place of the other...
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
void splice(iterator where, iplist_impl &L2)
const InstListType & getInstList() const
Return the underlying instruction list container.
User * getUser() const
Returns the User that contains this Use.
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
Value * getOperand(unsigned i) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if this function has the given attribute.
Interval::pred_iterator pred_end(Interval *I)
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
self_iterator getIterator()
op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Class to represent integer types.
bool callsGCLeafFunction(ImmutableCallSite CS)
Return true if the CallSite CS calls a gc leaf function.
static void DIExprAddOffset(SmallVectorImpl< uint64_t > &Expr, int Offset)
op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
static MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
bool replaceDbgDeclare(Value *Address, Value *NewAddress, Instruction *InsertBefore, DIBuilder &Builder, bool Deref, int Offset)
Replaces llvm.dbg.declare instruction when the address it describes is replaced with a new value...
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, unsigned BitWidth)
LLVMContext & getContext() const
All values hold a context through their type.
bool LowerDbgDeclare(Function &F)
Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, const PredBlockVector &BBPreds, PHINode *PN)
Replace a value flowing from a block to a phi with potentially multiple instances of that value flowi...
bool recursivelySimplifyInstruction(Instruction *I, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
Recursively attempt to simplify an instruction.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
const MDOperand & getOperand(unsigned I) const
DIExpression * getExpression() const
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
const BasicBlockListType & getBasicBlockList() const
BasicBlock * getUnwindDest() const
This is the shared class of boolean and integer constants.
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, unsigned BitWidth)
bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI=nullptr)
Remove all blocks that can not be reached from the function's entry.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
void FindAllocaDbgValues(DbgValueList &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics corresponding to an alloca, if any.
LLVM_NODISCARD T pop_back_val()
BasicBlockTy * getCaseSuccessor()
Resolves successor for current case.
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
DIExpression * createExpression(ArrayRef< uint64_t > Addr=None)
Create a new descriptor for the specified variable which has a complex address expression for its add...
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.
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
const BasicBlock & getEntryBlock() const
unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than it's terminator and any present EH pad instruct...
Value handle that asserts if the Value is deleted.
SmallVector< BasicBlock *, 16 > PredBlockVector
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
bool exceedsNaturalStackAlignment(unsigned Align) const
Returns true if the given alignment exceeds the natural stack alignment.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static void DIExprAddDeref(SmallVectorImpl< uint64_t > &Expr)
iterator_range< user_iterator > users()
BasicBlock * getSinglePredecessor()
Return the predecessor of this block if it has a single predecessor block.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
void removeUnwindEdge(BasicBlock *BB)
Replace 'BB's terminator with one that does not have an unwind successor block.
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static bool simplifyAndDCEInstruction(Instruction *I, SmallSetVector< Instruction *, 16 > &WorkList, const DataLayout &DL, const TargetLibraryInfo *TLI)
static DIExpression * BuildReplacementDIExpr(DIBuilder &Builder, DIExpression *DIExpr, bool Deref, int Offset)
static IntegerType * getInt32Ty(LLVMContext &C)
This represents the llvm.dbg.value instruction.
ImmutableCallSite - establish a view to a call site for examination.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
iterator find(const KeyT &Val)
bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try and match a bswap or bitreverse idiom.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void destroyConstant()
Called if some element of this constant is no longer valid.
void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
static bool PhiHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, PHINode *APN)
See if there is a dbg.value intrinsic for DIVar for the PHI node.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
void combineMetadataForCSE(Instruction *K, const Instruction *J)
Combine the metadata of two instructions so that K can replace J.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void eraseBlock(BasicBlock *BB)
Inform the analysis cache that we have erased a block.
bool hasLocalLinkage() const
This pass computes, caches, and vends lazy value constraint information.
static bool isArray(AllocaInst *AI)
Determine whether this alloca is either a VLA or an array.
DILocalVariable * getVariable() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
LLVMContext & getContext() const
Get the context in which this basic block lives.
FunTy * getCalledFunction() const
getCalledFunction - Return the function being called if this is a direct call, otherwise return null ...
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
DILocalVariable * getVariable() const
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, Instruction *InsertBefore=nullptr)
static const Function * getParent(const Value *V)
void setCallingConv(CallingConv::ID CC)
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
Value * SimplifyInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
See if we can compute a simplified version of this instruction.
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void setIncomingValue(unsigned i, Value *V)
static void Split(std::vector< std::string > &V, StringRef S)
Split - Splits a string of comma separated items in to a vector of strings.
static MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
This represents the llvm.dbg.declare instruction.
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
const BasicBlock * getParent() const
InstListType::iterator iterator
Instruction iterators...
A wrapper class for inspecting calls to intrinsic functions.
an instruction to allocate memory on the stack